Skip to main content

qualia_core_db/identity/
identifier.rs

1//! `did:q42` Q42 Resource Coordinate (`QrcCoordinate`) resolver.
2//!
3//! A `did:q42` URI is a **60-bit + MSB (`1 << 63`) Q42 Resource Coordinate (QRC)**
4//! belonging to `Plane::Handle` / `Plane::Instrument` — a physical/topological
5//! coordinate into the Qualia disk/memory layout — **never** a W3C DID Document
6//! root and **never** a `NaturalAgent` (`Who`) identity.
7//!
8//! # Zero-allocation guarantee
9//! All operations work directly on `&[u8]`.  No `String` or `Vec` is
10//! constructed at any point in the hot path.
11//!
12//! # MSB flag convention
13//! Any `u64` returned by this module has bit 63 set to `1`.  The Webizen VM
14//! uses that bit to distinguish absolute hardware/disk QRC pointers (MSB = 1)
15//! from local dictionary hashes produced by `q_hash` (MSB = 0).
16
17/// The mandatory URI prefix for all `did:q42` coordinates.
18const PREFIX: &[u8] = b"did:q42:";
19/// Display-formatted pointer prefix emitted by `resolver::format_ntriples_to`.
20const PTR_PREFIX: &[u8] = b"did:q42:ptr/";
21
22/// Errors returned by [`parse_did_q42`] and [`parse_did_q42_or_ptr`].
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub enum IdentifierError {
25    /// The byte slice does not begin with `did:q42:`.
26    InvalidPrefix,
27    /// The payload section (after the prefix) is empty or contains bytes that
28    /// cannot form a valid coordinate or hex pointer.
29    MalformedHash,
30    /// Reserved for future checksum verification of the multicodec payload.
31    InvalidChecksum,
32}
33
34/// Parse a `did:q42:` URI byte slice into a 64-bit Q42 Resource Coordinate (QRC).
35///
36/// # Contract
37/// * Input must start with `b"did:q42:"`.
38/// * The payload after the prefix must be non-empty.
39/// * The returned `u64` always has **bit 63 set** — signalling to the Webizen
40///   VM that this value is a QRC coordinate, not a dictionary hash.
41///
42/// # Example
43/// ```
44/// use qualia_core_db::identifier::parse_did_q42;
45/// let ptr = parse_did_q42(b"did:q42:z6MkpTHR8VNs").unwrap();
46/// assert_eq!(ptr >> 63, 1, "MSB must be set for QRC coordinates");
47/// ```
48pub fn parse_did_q42(uri: &[u8]) -> Result<u64, IdentifierError> {
49    // 1. Prefix check — `starts_with` operates entirely on `&[u8]`.
50    if !uri.starts_with(PREFIX) {
51        return Err(IdentifierError::InvalidPrefix);
52    }
53
54    // 2. Extract payload without any allocation.
55    let payload = &uri[PREFIX.len()..];
56    if payload.is_empty() {
57        return Err(IdentifierError::MalformedHash);
58    }
59
60    // 3. Hash the raw payload bytes with FNV-1a.
61    //    We mirror `crate::q_hash` but operate on `&[u8]` directly so this
62    //    module remains self-contained and `no_std`-compatible.
63    let base_hash = fnv1a(payload);
64
65    // 4. Apply the routing bitmask: flip bit 63 to mark this as a topological
66    //    pointer rather than a plain dictionary hash.
67    let pointer = base_hash | (1u64 << 63);
68
69    Ok(pointer)
70}
71
72/// Parse either a standard `did:q42:<payload>` coordinate or a display-serialized
73/// `did:q42:ptr/<hex>` / `<did:q42:ptr/<hex>>` coordinate emitted by
74/// `resolver::format_ntriples_to`, returning the canonical 64-bit QRC pointer
75/// (`MSB = 1`, low 60 bits = coordinate payload).
76///
77/// Note: `did:q42:ptr/{hex}` is strictly a display round-trip parser and never
78/// grants raw memory dereference authority.
79pub fn parse_did_q42_or_ptr(uri: &[u8]) -> Result<u64, IdentifierError> {
80    let inner = if uri.len() >= 2 && uri[0] == b'<' && uri[uri.len() - 1] == b'>' {
81        &uri[1..uri.len() - 1]
82    } else {
83        uri
84    };
85
86    if inner.starts_with(PTR_PREFIX) {
87        let hex = &inner[PTR_PREFIX.len()..];
88        if hex.is_empty() || hex.len() > 16 {
89            return Err(IdentifierError::MalformedHash);
90        }
91        let mut val: u64 = 0;
92        for &b in hex {
93            let nibble = match b {
94                b'0'..=b'9' => (b - b'0') as u64,
95                b'a'..=b'f' => (b - b'a' + 10) as u64,
96                b'A'..=b'F' => (b - b'A' + 10) as u64,
97                _ => return Err(IdentifierError::MalformedHash),
98            };
99            val = (val << 4) | nibble;
100        }
101        // Bits 60..62 are reserved for inline type tags when MSB=0; for QRC
102        // pointers (MSB=1), only bit 63 and the 60-bit payload may be set.
103        if (val & 0x7000_0000_0000_0000) != 0 {
104            return Err(IdentifierError::MalformedHash);
105        }
106        return Ok((val & 0x0FFF_FFFF_FFFF_FFFF) | (1u64 << 63));
107    }
108
109    parse_did_q42(inner)
110}
111
112/// FNV-1a over a raw byte slice — identical to `crate::q_hash` (60-bit identity).
113/// Kept local so this module has no runtime dependency on the crate root.
114/// Truncated to 60 bits so a did:q42 topological pointer shares the ONE identity
115/// space (low 60 bits) with dictionary hashes, differing only by its MSB tag —
116/// and so dictionary hashes (MSB always 0) never collide with topological
117/// pointers (MSB set), making the MSB a reliable discriminator.
118#[inline(always)]
119fn fnv1a(bytes: &[u8]) -> u64 {
120    let mut hash: u64 = 0xcbf29ce484222325;
121    for &b in bytes {
122        hash ^= b as u64;
123        hash = hash.wrapping_mul(0x100000001b3);
124    }
125    hash & 0x0FFF_FFFF_FFFF_FFFF
126}
127
128#[cfg(test)]
129mod tests {
130    use super::*;
131
132    #[test]
133    fn test_valid_did_q42_msb() {
134        let result = parse_did_q42(b"did:q42:z6MkpTHR8VNs").unwrap();
135        assert_eq!(result >> 63, 1, "MSB must be 1 for a topological pointer");
136    }
137
138    #[test]
139    fn test_invalid_prefix() {
140        assert_eq!(
141            parse_did_q42(b"did:key:z6MkpTHR8VNs"),
142            Err(IdentifierError::InvalidPrefix)
143        );
144    }
145
146    #[test]
147    fn test_empty_payload() {
148        assert_eq!(
149            parse_did_q42(b"did:q42:"),
150            Err(IdentifierError::MalformedHash)
151        );
152    }
153
154    #[test]
155    fn test_bare_prefix_without_colon() {
156        assert_eq!(
157            parse_did_q42(b"did:q42"),
158            Err(IdentifierError::InvalidPrefix)
159        );
160    }
161
162    #[test]
163    fn test_deterministic_output() {
164        let a = parse_did_q42(b"did:q42:z6MkpTHR8VNs").unwrap();
165        let b = parse_did_q42(b"did:q42:z6MkpTHR8VNs").unwrap();
166        assert_eq!(a, b, "parse_did_q42 must be deterministic");
167    }
168
169    #[test]
170    fn test_distinct_payloads_produce_distinct_pointers() {
171        let a = parse_did_q42(b"did:q42:z6MkpTHR8VNs").unwrap();
172        let b = parse_did_q42(b"did:q42:z6MkpTHR8VNt").unwrap();
173        assert_ne!(a, b, "distinct payloads must yield distinct pointers");
174    }
175
176    #[test]
177    fn pointer_is_base_hash_or_msb() {
178        let plain = crate::q_hash("z6MkpTHR8VNs");
179        let pointer = parse_did_q42(b"did:q42:z6MkpTHR8VNs").unwrap();
180        assert_eq!(pointer, plain | (1u64 << 63));
181    }
182
183    #[test]
184    fn test_parse_did_q42_or_ptr_roundtrip() {
185        let orig = parse_did_q42(b"did:q42:z6MkpTHR8VNs").unwrap();
186        let formatted = format!("<did:q42:ptr/{orig:016x}>");
187        let recovered = parse_did_q42_or_ptr(formatted.as_bytes()).unwrap();
188        assert_eq!(recovered, orig);
189    }
190}