Skip to main content

qualia_core_db/bundle/
cbor_ld_manifest.rs

1//! CBOR-LD Self-Contained Verifiable Credential Manifest for `.hmc` Bundles.
2//!
3//! Bridges the Webizen decentralized identity layer (W3C Verifiable Credentials,
4//! JSON-LD/CBOR-LD `@context`, `did:web:...`) with physical digital twin binary payloads.
5//!
6//! Binds the Tripartite Ontology (`DarwinianTaxon`, `ManufacturedProperty`), affordances
7//! (procedural seeds, continuous acoustic anchors), and physical geometry layout offsets/digests
8//! sequenced in Reverse-LOD order:
9//! 1. Header & CBOR-LD Manifest
10//! 2. Section 20: SURF1 Hierarchical Surfels (far-field macro view)
11//! 3. Section 19: IMPO1 Octahedral Atlases (mid-to-far field proxy)
12//! 4. Section 2: Decimated Meshlets (mid-range geometry)
13//! 5. Section 1: Hero Meshlets (close-up detailed geometry)
14
15use 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/// W3C Verifiable Credential manifest encoded as CBOR-LD.
28#[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/// The credential subject binding physical affordances and geometry layout.
44#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
45pub struct CredentialSubject {
46    pub id: String,
47    #[serde(rename = "type")]
48    pub entity_type: String, // e.g. "DarwinianTaxon", "ManufacturedProperty"
49    pub affordances: SubjectAffordances,
50    pub geometry_layout: GeometryLayout,
51    #[serde(default, skip_serializing_if = "Option::is_none")]
52    pub commons_obligation: Option<CommonsObligation>,
53    /// ADR 0014 Payload catalogue for prose-overflow and multimodal commentary.
54    #[serde(default, skip_serializing_if = "Vec::is_empty")]
55    pub payload_catalogue: Vec<PayloadCatalogueEntry>,
56}
57
58/// ADR 0014 Payload Catalogue Entry for prose-overflow, multi-lingual notes, or oral history audio.
59#[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/// Humanitarian ICT & Permissive Commons terms for living biosphere & cognitive heritage.
71///
72/// ## Ontological Demarcation:
73/// 1. **Commercial Rights / Manufactured Property (`ManufacturedProperty`)**:
74///    Commercial vendors (e.g. Nike, industrial manufacturers, proprietary software authors)
75///    retain full commercial freedom to set market prices, profit margins, and licensing terms.
76///    Consumers have a right to fundamental bodily needs (shoes to walk, shelter, clothing),
77///    but not an entitlement to a specific trademarked commercial design of shoe.
78/// 2. **"World of God" / Biosphere / Knowledge for Life (`DarwinianTaxon`, `AbioticEnvironment`)**:
79///    Pertains to living species, ecological heritage, and foundational knowledge necessary for
80///    life, being, and freedom of thought. These CANNOT be enclosed behind perpetual tollbooths
81///    or privatized royalties.
82///    Instead, under Humanitarian ICT principles:
83///    - **Finite Obligation Cost**: The limited, auditable labor and digitization cost to produce
84///      the virtual entity may be recovered up to an ROI cap via an accumulated compensation pool.
85///    - **Direct Carriage / Bandwidth Recovery**: Actual transaction cost per MiB for network
86///      transport may be met at cost.
87///    - **No Perpetual Fees**: Once production obligations are discharged, the asset remains
88///      in pure permissive commons with zero perpetual tolls.
89#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
90pub struct CommonsObligation {
91    /// Licencing framework: "SocialPermissiveCommons", "CC0-1.0", "CC-BY-4.0", etc.
92    pub licence_class: String,
93    /// Finite, audited cost of production in minor units (e.g. cents) - 0 if purely donated commons.
94    #[serde(default)]
95    pub production_cost_cents: u64,
96    /// Legal ROI cap percentage (capped to prevent extractive rent).
97    #[serde(default)]
98    pub roi_cap_percent: u64,
99    /// Cumulative compensation payments made towards discharging production cost.
100    #[serde(default)]
101    pub accumulated_pool_cents: u64,
102    /// Allowed carrier/bandwidth transaction recovery cost in minor units per MiB.
103    #[serde(default)]
104    pub transaction_cost_per_mib_cents: u64,
105    /// Prohibits perpetual fees or rent-seeking tolls in perpetuity.
106    #[serde(default = "default_true")]
107    pub perpetual_fees_prohibited: bool,
108}
109
110fn default_true() -> bool {
111    true
112}
113
114impl CommonsObligation {
115    /// `true` when `discharged`.
116    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    /// Outstanding commons obligation in cents.
132    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    /// Automatically discharges the obligation when accumulated compensation meets
142    /// the capped production cost, transitioning licence to SocialPermissiveCommons.
143    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/// Physical and procedural affordances attached to the entity.
155#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
156pub struct SubjectAffordances {
157    pub procedural_seed: String,
158    pub acoustic_anchors: AcousticAnchors,
159}
160
161/// 3-band continuous acoustic frequency anchors.
162#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
163pub struct AcousticAnchors {
164    pub low_hz: u32,  // 200 Hz
165    pub mid_hz: u32,  // 1000 Hz
166    pub high_hz: u32, // 8000 Hz
167}
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/// Reverse-LOD physical layout within the container or bundle.
180#[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/// Byte offset, byte length, and SHA-256 cryptographic digest of a binary section.
190#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
191pub struct SectionLayoutEntry {
192    pub offset: u64,
193    pub length: u64,
194    pub digest: String, // e.g. "sha256-..."
195}
196
197/// W3C Data Integrity proof (e.g. Ed25519Signature2020).
198#[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    /// Construct a new Verifiable Credential manifest with default context and types.
213    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    /// Construct a verified botanical/ecological Specimen manifest (DarwinianTaxon).
260    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    /// Construct a sovereign Human Persona / Likeness manifest (NaturalPerson).
296    /// Inalienable: cannot be commodified or assigned as property.
297    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    /// Construct a Manufactured Construct manifest (ManufacturedProperty).
329    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    /// Serialise the manifest into binary CBOR-LD.
360    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    /// Deserialise a manifest from binary CBOR-LD bytes.
367    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    /// Serialise the manifest into standard JSON-LD representation.
372    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    /// Deserialise the manifest from JSON-LD string.
377    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    /// Compute SHA-256 digest string in the format "sha256-<hex>".
382    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    /// Verify that physical byte slices match the declared offsets, lengths, and digests.
395    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        // JSON roundtrip
477        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        // CBOR roundtrip
485        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}