Skip to main content

qualia_core_db/identity/
identifier.rs

1//! `did:q42` topological coordinate resolver.
2//!
3//! A `did:q42` URI is a **physical topological coordinate** — an absolute
4//! pointer into the Qualia disk/memory layout — not a human identity.
5//!
6//! # Zero-allocation guarantee
7//! All operations work directly on `&[u8]`.  No `String` or `Vec` is
8//! constructed at any point in the hot path.
9//!
10//! # MSB flag convention
11//! Any `u64` returned by this module has bit 63 set to `1`.  The Webizen VM
12//! uses that bit to distinguish absolute hardware/disk pointers (MSB = 1) from
13//! local dictionary hashes produced by `q_hash` (MSB = 0).
14
15/// The mandatory URI prefix for all `did:q42` coordinates.
16const PREFIX: &[u8] = b"did:q42:";
17
18/// Errors returned by [`parse_did_q42`].
19#[derive(Debug, PartialEq)]
20pub enum IdentifierError {
21    /// The byte slice does not begin with `did:q42:`.
22    InvalidPrefix,
23    /// The payload section (after the prefix) is empty or contains bytes that
24    /// cannot form a valid base-58 / multibase coordinate.
25    MalformedHash,
26    /// Reserved for future checksum verification of the multicodec payload.
27    InvalidChecksum,
28}
29
30/// Parse a `did:q42:` URI byte slice into a 64-bit topological pointer.
31///
32/// # Contract
33/// * Input must start with `b"did:q42:"`.
34/// * The payload after the prefix must be non-empty.
35/// * The returned `u64` always has **bit 63 set** — signalling to the Webizen
36///   VM that this value is a hardware/disk coordinate, not a dictionary hash.
37///
38/// # Example
39/// ```
40/// use qualia_core_db::identifier::parse_did_q42;
41/// let ptr = parse_did_q42(b"did:q42:z6MkpTHR8VNs").unwrap();
42/// assert_eq!(ptr >> 63, 1, "MSB must be set for topological coordinates");
43/// ```
44pub fn parse_did_q42(uri: &[u8]) -> Result<u64, IdentifierError> {
45    // 1. Prefix check — `starts_with` operates entirely on `&[u8]`.
46    if !uri.starts_with(PREFIX) {
47        return Err(IdentifierError::InvalidPrefix);
48    }
49
50    // 2. Extract payload without any allocation.
51    let payload = &uri[PREFIX.len()..];
52    if payload.is_empty() {
53        return Err(IdentifierError::MalformedHash);
54    }
55
56    // 3. Hash the raw payload bytes with FNV-1a.
57    //    We mirror `crate::q_hash` but operate on `&[u8]` directly so this
58    //    module remains self-contained and `no_std`-compatible.
59    let base_hash = fnv1a(payload);
60
61    // 4. Apply the routing bitmask: flip bit 63 to mark this as a topological
62    //    pointer rather than a plain dictionary hash.
63    let pointer = base_hash | (1u64 << 63);
64
65    Ok(pointer)
66}
67
68/// FNV-1a over a raw byte slice — identical to `crate::q_hash` (60-bit identity).
69/// Kept local so this module has no runtime dependency on the crate root.
70/// Truncated to 60 bits so a did:q42 topological pointer shares the ONE identity
71/// space (low 60 bits) with dictionary hashes, differing only by its MSB tag —
72/// and so dictionary hashes (MSB always 0) never collide with topological
73/// pointers (MSB set), making the MSB a reliable discriminator.
74#[inline(always)]
75fn fnv1a(bytes: &[u8]) -> u64 {
76    let mut hash: u64 = 0xcbf29ce484222325;
77    for &b in bytes {
78        hash ^= b as u64;
79        hash = hash.wrapping_mul(0x100000001b3);
80    }
81    hash & 0x0FFF_FFFF_FFFF_FFFF
82}
83
84#[cfg(test)]
85mod tests {
86    use super::*;
87
88    #[test]
89    fn test_valid_did_q42_msb() {
90        let result = parse_did_q42(b"did:q42:z6MkpTHR8VNs").unwrap();
91        assert_eq!(result >> 63, 1, "MSB must be 1 for a topological pointer");
92    }
93
94    #[test]
95    fn test_invalid_prefix() {
96        assert_eq!(
97            parse_did_q42(b"did:key:z6MkpTHR8VNs"),
98            Err(IdentifierError::InvalidPrefix)
99        );
100    }
101
102    #[test]
103    fn test_empty_payload() {
104        assert_eq!(
105            parse_did_q42(b"did:q42:"),
106            Err(IdentifierError::MalformedHash)
107        );
108    }
109
110    #[test]
111    fn test_bare_prefix_without_colon() {
112        assert_eq!(
113            parse_did_q42(b"did:q42"),
114            Err(IdentifierError::InvalidPrefix)
115        );
116    }
117
118    #[test]
119    fn test_deterministic_output() {
120        let a = parse_did_q42(b"did:q42:z6MkpTHR8VNs").unwrap();
121        let b = parse_did_q42(b"did:q42:z6MkpTHR8VNs").unwrap();
122        assert_eq!(a, b, "parse_did_q42 must be deterministic");
123    }
124
125    #[test]
126    fn test_distinct_payloads_produce_distinct_pointers() {
127        let a = parse_did_q42(b"did:q42:z6MkpTHR8VNs").unwrap();
128        let b = parse_did_q42(b"did:q42:z6MkpTHR8VNt").unwrap();
129        assert_ne!(a, b, "distinct payloads must yield distinct pointers");
130    }
131
132    #[test]
133    fn pointer_is_base_hash_or_msb() {
134        // The contract is pointer == q_hash(payload) | (1 << 63), regardless
135        // of whether q_hash already has bit 63 set for this particular input.
136        let plain = crate::q_hash("z6MkpTHR8VNs");
137        let pointer = parse_did_q42(b"did:q42:z6MkpTHR8VNs").unwrap();
138        assert_eq!(pointer, plain | (1u64 << 63));
139    }
140}