Skip to main content

qualia_core_db/identity/
webizen_did.rs

1//! `did:webizen:` Web of Data identifier parser and deterministic concept UUID engine.
2//!
3//! # Universal Rules Compliance
4//! * **Zero heap in hot paths:** All operations take `&[u8]` and caller-owned stack buffers.
5//!   No `String`, `Vec`, or `Box` are allocated.
6//! * **60-bit Quin Token:** Concept tokens are masked with `0x0FFF_FFFF_FFFF_FFFF` with
7//!   bit 63 cleared (`MSB = 0`), denoting a dictionary/lexicon entity rather than
8//!   a physical topological coordinate (`did:q42` pointer, `MSB = 1`).
9//!
10//! Reference: `docs/manuals/standards/did-webizen-method.md`
11
12use sha1::{Digest, Sha1};
13
14/// Mandatory URI prefix for all Webizen identifiers.
15pub const PREFIX: &[u8] = b"did:webizen:";
16
17/// Canonical Webizen Ontology Namespace UUID (RFC 4122 Namespace UUID for Web of Data concepts).
18/// UUID: `7f18b320-9dad-11d1-80b4-00c04fd430c8`
19pub const WEBIZEN_ONTOLOGY_NAMESPACE: [u8; 16] = [
20    0x7f, 0x18, 0xb3, 0x20, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8,
21];
22
23/// The functional realm of a `did:webizen` identifier.
24#[derive(Clone, Copy, Debug, PartialEq, Eq)]
25pub enum WebizenRealm {
26    /// Domain-decoupled semantic concept, class, or predicate.
27    Concept,
28    /// Versioned ontology package (`name@semver`).
29    Ont,
30    /// Ratified bilateral or multi-party micro-commons agreement.
31    Agreement,
32    /// Web of Data citizen or autonomous agent principal.
33    Agent,
34}
35
36/// Zero-copy reference over a validated `did:webizen:` identifier.
37#[derive(Clone, Copy, Debug, PartialEq, Eq)]
38pub struct WebizenDidRef<'a> {
39    pub realm: WebizenRealm,
40    pub payload: &'a [u8],
41}
42
43/// Errors returned by [`parse_did_webizen`].
44#[derive(Clone, Copy, Debug, PartialEq, Eq)]
45pub enum WebizenDidError {
46    /// URI does not start with `did:webizen:`.
47    InvalidPrefix,
48    /// Specifically rejected competitor or alternative method (e.g. `did:q42:`, `did:qi:`).
49    RejectedMethod,
50    /// The realm component is unknown or missing.
51    UnknownRealm,
52    /// The realm payload (after realm and colon) is empty.
53    EmptyPayload,
54    /// Caller-supplied buffer is too small for output.
55    BufferTooSmall,
56}
57
58/// Parse a `did:webizen:` byte slice into a zero-copy [`WebizenDidRef`].
59///
60/// # Hot Path Contract
61/// Guaranteed zero-heap. Operates entirely on the input byte slice.
62pub fn parse_did_webizen(uri: &[u8]) -> Result<WebizenDidRef<'_>, WebizenDidError> {
63    // 1. Explicitly reject other DID methods
64    if starts_ignore_ascii(uri, b"did:q42:")
65        || starts_ignore_ascii(uri, b"did:qi:")
66        || starts_ignore_ascii(uri, b"did:hcai:")
67        || starts_ignore_ascii(uri, b"did:hcinet:")
68        || starts_ignore_ascii(uri, b"did:qualia:")
69    {
70        return Err(WebizenDidError::RejectedMethod);
71    }
72
73    // 2. Prefix validation
74    if !starts_ignore_ascii(uri, PREFIX) {
75        return Err(WebizenDidError::InvalidPrefix);
76    }
77
78    let rest = &uri[PREFIX.len()..];
79    if rest.is_empty() {
80        return Err(WebizenDidError::UnknownRealm);
81    }
82
83    // 3. Realm dispatch
84    if let Some(payload) = strip_prefix_exact(rest, b"concept:") {
85        if payload.is_empty() {
86            return Err(WebizenDidError::EmptyPayload);
87        }
88        Ok(WebizenDidRef {
89            realm: WebizenRealm::Concept,
90            payload,
91        })
92    } else if let Some(payload) = strip_prefix_exact(rest, b"ont:") {
93        if payload.is_empty() {
94            return Err(WebizenDidError::EmptyPayload);
95        }
96        Ok(WebizenDidRef {
97            realm: WebizenRealm::Ont,
98            payload,
99        })
100    } else if let Some(payload) = strip_prefix_exact(rest, b"agreement:") {
101        if payload.is_empty() {
102            return Err(WebizenDidError::EmptyPayload);
103        }
104        Ok(WebizenDidRef {
105            realm: WebizenRealm::Agreement,
106            payload,
107        })
108    } else if let Some(payload) = strip_prefix_exact(rest, b"agent:") {
109        if payload.is_empty() {
110            return Err(WebizenDidError::EmptyPayload);
111        }
112        Ok(WebizenDidRef {
113            realm: WebizenRealm::Agent,
114            payload,
115        })
116    } else {
117        Err(WebizenDidError::UnknownRealm)
118    }
119}
120
121/// Compute a deterministic RFC 4122 / RFC 9562 UUIDv5 for a concept name.
122///
123/// Combines the canonical [`WEBIZEN_ONTOLOGY_NAMESPACE`] with the supplied
124/// concept name bytes via SHA-1, setting UUID version 5 and RFC 4122 variant bits.
125///
126/// Guaranteed zero heap allocations. Returns the raw 16-byte UUID.
127pub fn derive_concept_uuid(concept_name: &[u8]) -> [u8; 16] {
128    let mut hasher = Sha1::new();
129    hasher.update(WEBIZEN_ONTOLOGY_NAMESPACE);
130    hasher.update(concept_name);
131    let digest = hasher.finalize();
132
133    let mut uuid = [0u8; 16];
134    uuid.copy_from_slice(&digest[0..16]);
135
136    // Set UUIDv5 version (0101 in high 4 bits of octet 6)
137    uuid[6] = (uuid[6] & 0x0f) | 0x50;
138    // Set RFC 4122 variant (10 in high 2 bits of octet 8)
139    uuid[8] = (uuid[8] & 0x3f) | 0x80;
140
141    uuid
142}
143
144/// Compute a post-quantum collision-resistant deterministic UUID (RFC 9562 UUIDv8)
145/// for a concept name using SHA-256.
146///
147/// Under Grover's quantum search algorithm, SHA-256 retains 128 bits of quantum security,
148/// making this concept derivation immune to quantum preimage attacks.
149///
150/// Guaranteed zero heap allocations.
151pub fn derive_concept_uuid_pq(concept_name: &[u8]) -> [u8; 16] {
152    use sha2::{Digest as Sha2Digest, Sha256};
153    let mut hasher = Sha256::new();
154    hasher.update(WEBIZEN_ONTOLOGY_NAMESPACE);
155    hasher.update(concept_name);
156    let digest = hasher.finalize();
157
158    let mut uuid = [0u8; 16];
159    uuid.copy_from_slice(&digest[0..16]);
160
161    // Set UUIDv8 version (1000 in high 4 bits of octet 6: custom/vendor-defined)
162    uuid[6] = (uuid[6] & 0x0f) | 0x80;
163    // Set RFC 4122 / RFC 9562 variant (10 in high 2 bits of octet 8)
164    uuid[8] = (uuid[8] & 0x3f) | 0x80;
165
166    uuid
167}
168
169/// Verify an ML-DSA-65 (FIPS-204) post-quantum digital signature over a message.
170///
171/// Hot-path guarantee: operates on fixed-size byte references with zero heap allocation.
172pub fn verify_pq_signature(
173    public_key_bytes: &[u8; 1952],
174    message: &[u8],
175    signature_bytes: &[u8; 3309],
176    context: &[u8],
177) -> bool {
178    crate::crypto::network::mldsa::verify(public_key_bytes, message, context, signature_bytes)
179        .is_ok()
180}
181
182/// Verify a hybrid DualProof (ML-DSA-65 + Ed25519) digital signature over a message.
183///
184/// Both signatures must verify over the identical message and context bytes.
185/// Hot-path guarantee: operates on fixed-size byte references with zero heap allocation.
186pub fn verify_dual_signature(
187    mldsa_pk: &[u8; 1952],
188    ed25519_pk: &[u8; 32],
189    message: &[u8],
190    context: &[u8],
191    proof: &crate::crypto::network::dual_sign::DualProof,
192) -> bool {
193    crate::crypto::network::dual_sign::verify_dual(mldsa_pk, ed25519_pk, message, context, proof)
194        .is_ok()
195}
196
197/// Format a 16-byte UUID into standard 36-character hyphenated lowercase hex ASCII.
198///
199/// Output format: `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx`
200pub fn format_uuid_hex(uuid: &[u8; 16], out: &mut [u8; 36]) {
201    const HEX_CHARS: &[u8; 16] = b"0123456789abcdef";
202
203    let mut cursor = 0;
204    for (i, &byte) in uuid.iter().enumerate() {
205        if i == 4 || i == 6 || i == 8 || i == 10 {
206            out[cursor] = b'-';
207            cursor += 1;
208        }
209        out[cursor] = HEX_CHARS[(byte >> 4) as usize];
210        out[cursor + 1] = HEX_CHARS[(byte & 0x0f) as usize];
211        cursor += 2;
212    }
213}
214
215/// Format a 16-byte concept UUID into a 45-character `urn:uuid:...` ASCII slice.
216pub fn format_concept_urn(uuid: &[u8; 16], out: &mut [u8; 45]) {
217    out[..9].copy_from_slice(b"urn:uuid:");
218    let mut hex = [0u8; 36];
219    format_uuid_hex(uuid, &mut hex);
220    out[9..45].copy_from_slice(&hex);
221}
222
223/// Compute the 60-bit FNV-1a Quin token for an identifier or UUID URN.
224///
225/// Bit 63 is unconditionally cleared (`0`) to mark this as a lexicon dictionary entity
226/// rather than a `did:q42:` hardware/RAM coordinate.
227#[inline(always)]
228pub fn quin_concept_token(bytes: &[u8]) -> u64 {
229    let mut hash: u64 = 0xcbf29ce484222325;
230    for &b in bytes {
231        hash ^= b as u64;
232        hash = hash.wrapping_mul(0x100000001b3);
233    }
234    // Mask to 60 bits, MSB is always 0
235    hash & 0x0FFF_FFFF_FFFF_FFFF
236}
237
238fn starts_ignore_ascii(s: &[u8], prefix: &[u8]) -> bool {
239    s.len() >= prefix.len()
240        && s[..prefix.len()]
241            .iter()
242            .zip(prefix.iter())
243            .all(|(a, b)| a.to_ascii_lowercase() == b.to_ascii_lowercase())
244}
245
246fn strip_prefix_exact<'a>(s: &'a [u8], prefix: &[u8]) -> Option<&'a [u8]> {
247    if s.len() >= prefix.len() && &s[..prefix.len()] == prefix {
248        Some(&s[prefix.len()..])
249    } else {
250        None
251    }
252}
253
254#[cfg(test)]
255mod tests {
256    use super::*;
257
258    #[test]
259    fn test_parse_valid_realms() {
260        let c = parse_did_webizen(b"did:webizen:concept:hasTrackId").unwrap();
261        assert_eq!(c.realm, WebizenRealm::Concept);
262        assert_eq!(c.payload, b"hasTrackId");
263
264        let o = parse_did_webizen(b"did:webizen:ont:perception@1.2.0").unwrap();
265        assert_eq!(o.realm, WebizenRealm::Ont);
266        assert_eq!(o.payload, b"perception@1.2.0");
267
268        let a = parse_did_webizen(b"did:webizen:agreement:z6MkpTHR8VNs").unwrap();
269        assert_eq!(a.realm, WebizenRealm::Agreement);
270        assert_eq!(a.payload, b"z6MkpTHR8VNs");
271
272        let ag = parse_did_webizen(b"did:webizen:agent:z6MkpAgent").unwrap();
273        assert_eq!(ag.realm, WebizenRealm::Agent);
274        assert_eq!(ag.payload, b"z6MkpAgent");
275    }
276
277    #[test]
278    fn test_reject_competing_dids() {
279        assert_eq!(
280            parse_did_webizen(b"did:q42:z6MkpTHR8VNs"),
281            Err(WebizenDidError::RejectedMethod)
282        );
283        assert_eq!(
284            parse_did_webizen(b"did:qi:z6MkpTHR8VNs"),
285            Err(WebizenDidError::RejectedMethod)
286        );
287        assert_eq!(
288            parse_did_webizen(b"did:qualia:0x3f8a"),
289            Err(WebizenDidError::RejectedMethod)
290        );
291    }
292
293    #[test]
294    fn test_deterministic_uuidv5() {
295        let u1 = derive_concept_uuid(b"hasTrackId");
296        let u2 = derive_concept_uuid(b"hasTrackId");
297        assert_eq!(u1, u2, "UUIDv5 must be deterministic");
298
299        // Verify version 5 and variant bits
300        assert_eq!(u1[6] >> 4, 5, "UUID must be version 5");
301        assert_eq!(u1[8] >> 6, 2, "UUID must be RFC 4122 variant");
302
303        let mut urn = [0u8; 45];
304        format_concept_urn(&u1, &mut urn);
305        assert!(urn.starts_with(b"urn:uuid:"));
306        assert_eq!(urn.len(), 45);
307
308        let token = quin_concept_token(&urn);
309        assert_eq!(token >> 63, 0, "MSB must be 0 for dictionary entities");
310        assert_eq!(token >> 60, 0, "Bits 60-63 must be 0 in masked token");
311    }
312}