1use serde::{Deserialize, Serialize};
16use sha2::{Digest, Sha256};
17
18use super::format::BundleError;
19
20pub const CBOR_LD_CONTEXT_CREDENTIALS_V1: &str = "https://www.w3.org/2018/credentials/v1";
21pub const CBOR_LD_CONTEXT_WEBCIVICS_V1: &str = "hmc://schemas/webcivics/v1";
22
23pub const CBOR_LD_MANIFEST_ENTRY_KEY: &str = "manifest/entity_manifest.cborld";
24pub const CBOR_LD_MANIFEST_LEGACY_KEY: &str = "manifest/twin_manifest.cborld";
25pub const CBOR_LD_MANIFEST_KIND: &str = "cborld_manifest";
26
27#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
29pub struct CborLdManifest {
30 #[serde(rename = "@context")]
31 pub context: Vec<String>,
32 pub id: String,
33 #[serde(rename = "type")]
34 pub credential_type: Vec<String>,
35 pub issuer: String,
36 #[serde(rename = "issuanceDate")]
37 pub issuance_date: String,
38 #[serde(rename = "credentialSubject")]
39 pub credential_subject: CredentialSubject,
40 pub proof: CredentialProof,
41}
42
43#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
45pub struct CredentialSubject {
46 pub id: String,
47 #[serde(rename = "type")]
48 pub entity_type: String, pub affordances: SubjectAffordances,
50 pub geometry_layout: GeometryLayout,
51 #[serde(default, skip_serializing_if = "Option::is_none")]
52 pub commons_obligation: Option<CommonsObligation>,
53 #[serde(default, skip_serializing_if = "Vec::is_empty")]
55 pub payload_catalogue: Vec<PayloadCatalogueEntry>,
56}
57
58#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
60pub struct PayloadCatalogueEntry {
61 pub payload_key: String,
62 pub mime_type: String,
63 #[serde(default, skip_serializing_if = "Option::is_none")]
64 pub language: Option<String>,
65 pub role: String,
66 pub byte_length: u64,
67 pub sha256_hex: String,
68}
69
70#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
90pub struct CommonsObligation {
91 pub licence_class: String,
93 #[serde(default)]
95 pub production_cost_cents: u64,
96 #[serde(default)]
98 pub roi_cap_percent: u64,
99 #[serde(default)]
101 pub accumulated_pool_cents: u64,
102 #[serde(default)]
104 pub transaction_cost_per_mib_cents: u64,
105 #[serde(default = "default_true")]
107 pub perpetual_fees_prohibited: bool,
108}
109
110fn default_true() -> bool {
111 true
112}
113
114impl CommonsObligation {
115 pub fn is_discharged(&self) -> bool {
117 if self.production_cost_cents == 0 {
118 return true;
119 }
120 let total_cost = crate::modalities::socioeconomics::commons_cost(
121 self.production_cost_cents,
122 self.roi_cap_percent,
123 20,
124 );
125 crate::modalities::socioeconomics::is_commons_discharged(
126 self.accumulated_pool_cents,
127 total_cost,
128 )
129 }
130
131 pub fn outstanding_obligation(&self) -> u64 {
133 let total_cost = crate::modalities::socioeconomics::commons_cost(
134 self.production_cost_cents,
135 self.roi_cap_percent,
136 20,
137 );
138 crate::modalities::socioeconomics::outstanding(self.accumulated_pool_cents, total_cost)
139 }
140
141 pub fn discharge_to_commons(&mut self) -> bool {
144 if self.is_discharged() {
145 self.licence_class = "SocialPermissiveCommons".to_string();
146 self.perpetual_fees_prohibited = true;
147 true
148 } else {
149 false
150 }
151 }
152}
153
154#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
156pub struct SubjectAffordances {
157 pub procedural_seed: String,
158 pub acoustic_anchors: AcousticAnchors,
159}
160
161#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
163pub struct AcousticAnchors {
164 pub low_hz: u32, pub mid_hz: u32, pub high_hz: u32, }
168
169impl Default for AcousticAnchors {
170 fn default() -> Self {
171 Self {
172 low_hz: 200,
173 mid_hz: 1000,
174 high_hz: 8000,
175 }
176 }
177}
178
179#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
181pub struct GeometryLayout {
182 pub surf1: SectionLayoutEntry,
183 pub impo1: SectionLayoutEntry,
184 pub mesh1: SectionLayoutEntry,
185 #[serde(default, skip_serializing_if = "Option::is_none")]
186 pub mesh2: Option<SectionLayoutEntry>,
187}
188
189#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
191pub struct SectionLayoutEntry {
192 pub offset: u64,
193 pub length: u64,
194 pub digest: String, }
196
197#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
199pub struct CredentialProof {
200 #[serde(rename = "type")]
201 pub proof_type: String,
202 pub created: String,
203 #[serde(rename = "verificationMethod")]
204 pub verification_method: String,
205 #[serde(rename = "proofPurpose")]
206 pub proof_purpose: String,
207 #[serde(rename = "proofValue")]
208 pub proof_value: String,
209}
210
211impl CborLdManifest {
212 pub fn new(
214 credential_id: impl Into<String>,
215 issuer_did: impl Into<String>,
216 issuance_date: impl Into<String>,
217 subject_id: impl Into<String>,
218 entity_type: impl Into<String>,
219 procedural_seed: impl Into<String>,
220 acoustic_anchors: AcousticAnchors,
221 geometry_layout: GeometryLayout,
222 verification_method: impl Into<String>,
223 proof_value: impl Into<String>,
224 ) -> Self {
225 let created = issuance_date.into();
226 Self {
227 context: vec![
228 CBOR_LD_CONTEXT_CREDENTIALS_V1.to_string(),
229 CBOR_LD_CONTEXT_WEBCIVICS_V1.to_string(),
230 ],
231 id: credential_id.into(),
232 credential_type: vec![
233 "VerifiableCredential".to_string(),
234 "QualiaEntity".to_string(),
235 ],
236 issuer: issuer_did.into(),
237 issuance_date: created.clone(),
238 credential_subject: CredentialSubject {
239 id: subject_id.into(),
240 entity_type: entity_type.into(),
241 affordances: SubjectAffordances {
242 procedural_seed: procedural_seed.into(),
243 acoustic_anchors,
244 },
245 geometry_layout,
246 commons_obligation: None,
247 payload_catalogue: Vec::new(),
248 },
249 proof: CredentialProof {
250 proof_type: "Ed25519Signature2020".to_string(),
251 created,
252 verification_method: verification_method.into(),
253 proof_purpose: "assertionMethod".to_string(),
254 proof_value: proof_value.into(),
255 },
256 }
257 }
258
259 pub fn new_specimen(
261 credential_id: impl Into<String>,
262 issuer_did: impl Into<String>,
263 issuance_date: impl Into<String>,
264 taxon_id: impl Into<String>,
265 procedural_seed: impl Into<String>,
266 acoustic_anchors: AcousticAnchors,
267 geometry_layout: GeometryLayout,
268 verification_method: impl Into<String>,
269 proof_value: impl Into<String>,
270 ) -> Self {
271 let mut manifest = Self::new(
272 credential_id,
273 issuer_did,
274 issuance_date,
275 taxon_id,
276 "DarwinianTaxon",
277 procedural_seed,
278 acoustic_anchors,
279 geometry_layout,
280 verification_method,
281 proof_value,
282 );
283 manifest.credential_type = vec!["VerifiableCredential".into(), "TaxonSpecimen".into()];
284 manifest.credential_subject.commons_obligation = Some(CommonsObligation {
285 licence_class: "SocialPermissiveCommons".into(),
286 production_cost_cents: 0,
287 roi_cap_percent: 20,
288 accumulated_pool_cents: 0,
289 transaction_cost_per_mib_cents: 0,
290 perpetual_fees_prohibited: true,
291 });
292 manifest
293 }
294
295 pub fn new_persona(
298 credential_id: impl Into<String>,
299 human_did: impl Into<String>,
300 issuance_date: impl Into<String>,
301 subject_did: impl Into<String>,
302 procedural_seed: impl Into<String>,
303 acoustic_anchors: AcousticAnchors,
304 geometry_layout: GeometryLayout,
305 verification_method: impl Into<String>,
306 proof_value: impl Into<String>,
307 ) -> Self {
308 let mut manifest = Self::new(
309 credential_id,
310 human_did,
311 issuance_date,
312 subject_did,
313 "NaturalPerson",
314 procedural_seed,
315 acoustic_anchors,
316 geometry_layout,
317 verification_method,
318 proof_value,
319 );
320 manifest.credential_type = vec![
321 "VerifiableCredential".into(),
322 "HumanPersona".into(),
323 "SovereignLikeness".into(),
324 ];
325 manifest
326 }
327
328 pub fn new_construct(
330 credential_id: impl Into<String>,
331 issuer_did: impl Into<String>,
332 issuance_date: impl Into<String>,
333 property_id: impl Into<String>,
334 procedural_seed: impl Into<String>,
335 acoustic_anchors: AcousticAnchors,
336 geometry_layout: GeometryLayout,
337 verification_method: impl Into<String>,
338 proof_value: impl Into<String>,
339 ) -> Self {
340 let mut manifest = Self::new(
341 credential_id,
342 issuer_did,
343 issuance_date,
344 property_id,
345 "ManufacturedProperty",
346 procedural_seed,
347 acoustic_anchors,
348 geometry_layout,
349 verification_method,
350 proof_value,
351 );
352 manifest.credential_type = vec![
353 "VerifiableCredential".into(),
354 "ManufacturedConstruct".into(),
355 ];
356 manifest
357 }
358
359 pub fn encode_to_cbor(&self) -> Result<Vec<u8>, BundleError> {
361 let mut buf = Vec::new();
362 ciborium::into_writer(self, &mut buf).map_err(|e| BundleError::Cbor(e.to_string()))?;
363 Ok(buf)
364 }
365
366 pub fn decode_from_cbor(bytes: &[u8]) -> Result<Self, BundleError> {
368 ciborium::from_reader(bytes).map_err(|e| BundleError::Cbor(e.to_string()))
369 }
370
371 pub fn encode_to_json(&self) -> Result<String, BundleError> {
373 serde_json::to_string_pretty(self).map_err(|e| BundleError::Cbor(e.to_string()))
374 }
375
376 pub fn decode_from_json(json: &str) -> Result<Self, BundleError> {
378 serde_json::from_str(json).map_err(|e| BundleError::Cbor(e.to_string()))
379 }
380
381 pub fn compute_sha256_digest(bytes: &[u8]) -> String {
383 let mut hasher = Sha256::new();
384 hasher.update(bytes);
385 let hash = hasher.finalize();
386 let mut hex_str = String::with_capacity(64);
387 for byte in hash {
388 use std::fmt::Write;
389 let _ = write!(hex_str, "{:02x}", byte);
390 }
391 format!("sha256-{}", hex_str)
392 }
393
394 pub fn verify_geometry_digests(&self, bundle_bytes: &[u8]) -> Result<bool, BundleError> {
396 let entries = [
397 &self.credential_subject.geometry_layout.surf1,
398 &self.credential_subject.geometry_layout.impo1,
399 &self.credential_subject.geometry_layout.mesh1,
400 ];
401
402 for entry in entries {
403 let start = entry.offset as usize;
404 let end = start + entry.length as usize;
405 if end > bundle_bytes.len() {
406 return Err(BundleError::EntryOutOfBounds {
407 key: "geometry_layout".to_string(),
408 offset: entry.offset,
409 length: entry.length,
410 });
411 }
412 let actual = Self::compute_sha256_digest(&bundle_bytes[start..end]);
413 if actual != entry.digest {
414 return Ok(false);
415 }
416 }
417
418 if let Some(ref m2) = self.credential_subject.geometry_layout.mesh2 {
419 let start = m2.offset as usize;
420 let end = start + m2.length as usize;
421 if end > bundle_bytes.len() {
422 return Err(BundleError::EntryOutOfBounds {
423 key: "mesh2".to_string(),
424 offset: m2.offset,
425 length: m2.length,
426 });
427 }
428 let actual = Self::compute_sha256_digest(&bundle_bytes[start..end]);
429 if actual != m2.digest {
430 return Ok(false);
431 }
432 }
433
434 Ok(true)
435 }
436}
437
438#[cfg(test)]
439mod tests {
440 use super::*;
441
442 #[test]
443 fn cbor_ld_manifest_roundtrips_json_and_cbor() {
444 let layout = GeometryLayout {
445 surf1: SectionLayoutEntry {
446 offset: 2048,
447 length: 32768,
448 digest: "sha256-1111".to_string(),
449 },
450 impo1: SectionLayoutEntry {
451 offset: 34816,
452 length: 524288,
453 digest: "sha256-2222".to_string(),
454 },
455 mesh1: SectionLayoutEntry {
456 offset: 559104,
457 length: 14500000,
458 digest: "sha256-3333".to_string(),
459 },
460 mesh2: None,
461 };
462
463 let manifest = CborLdManifest::new(
464 "urn:uuid:3f8a42e0-2026-eucalyptus",
465 "did:web:trustfactory.org:compiler",
466 "2026-10-13T08:46:00Z",
467 "urn:qualia:taxon:eucalyptus_regnans_01",
468 "DarwinianTaxon",
469 "hmc://seeds/voronoi_bark",
470 AcousticAnchors::default(),
471 layout,
472 "did:web:trustfactory.org:compiler#key-1",
473 "z58DfakeSignatureValue2026",
474 );
475
476 let json_str = manifest.encode_to_json().expect("json encode");
478 assert!(json_str.contains("@context"));
479 assert!(json_str.contains("DarwinianTaxon"));
480 assert!(json_str.contains("did:web:trustfactory.org:compiler"));
481 let json_dec = CborLdManifest::decode_from_json(&json_str).expect("json decode");
482 assert_eq!(json_dec, manifest);
483
484 let cbor_bytes = manifest.encode_to_cbor().expect("cbor encode");
486 let cbor_dec = CborLdManifest::decode_from_cbor(&cbor_bytes).expect("cbor decode");
487 assert_eq!(cbor_dec, manifest);
488 }
489
490 #[test]
491 fn typed_constructors_bind_expected_credentials() {
492 let dummy_layout = GeometryLayout {
493 surf1: SectionLayoutEntry {
494 offset: 0,
495 length: 10,
496 digest: CborLdManifest::compute_sha256_digest(&[1; 10]),
497 },
498 impo1: SectionLayoutEntry {
499 offset: 16,
500 length: 10,
501 digest: CborLdManifest::compute_sha256_digest(&[2; 10]),
502 },
503 mesh1: SectionLayoutEntry {
504 offset: 32,
505 length: 10,
506 digest: CborLdManifest::compute_sha256_digest(&[3; 10]),
507 },
508 mesh2: None,
509 };
510
511 let specimen = CborLdManifest::new_specimen(
512 "urn:uuid:specimen-01",
513 "did:web:trustfactory.org:compiler",
514 "2026-10-13T08:46:00Z",
515 "urn:qualia:taxon:eucalyptus",
516 "hmc://seeds/bark",
517 AcousticAnchors::default(),
518 dummy_layout.clone(),
519 "did:web:trustfactory.org:compiler#key-1",
520 "zProof",
521 );
522 assert_eq!(specimen.credential_subject.entity_type, "DarwinianTaxon");
523 assert!(specimen
524 .credential_type
525 .contains(&"TaxonSpecimen".to_string()));
526
527 let persona = CborLdManifest::new_persona(
528 "urn:uuid:persona-01",
529 "did:key:citizen",
530 "2026-10-13T08:46:00Z",
531 "did:key:citizen",
532 "hmc://seeds/face",
533 AcousticAnchors::default(),
534 dummy_layout.clone(),
535 "did:key:citizen#key-1",
536 "zProof",
537 );
538 assert_eq!(persona.credential_subject.entity_type, "NaturalPerson");
539 assert!(persona
540 .credential_type
541 .contains(&"HumanPersona".to_string()));
542
543 let construct = CborLdManifest::new_construct(
544 "urn:uuid:construct-01",
545 "did:web:trustfactory.org:compiler",
546 "2026-10-13T08:46:00Z",
547 "urn:qualia:artifact:pump",
548 "hmc://seeds/pump",
549 AcousticAnchors::default(),
550 dummy_layout,
551 "did:web:trustfactory.org:compiler#key-1",
552 "zProof",
553 );
554 assert_eq!(
555 construct.credential_subject.entity_type,
556 "ManufacturedProperty"
557 );
558 assert!(construct
559 .credential_type
560 .contains(&"ManufacturedConstruct".to_string()));
561 }
562}