Skip to main content

qualia_core_db/identity/
did_qi.rs

1//! `did:qi` Sovereign Identity Method — Zero-Heap URI Grammar, Hint Parser,
2//! Genesis SHA-256 Verifier, and Verification-Relationship Gate (Packet `IDF-03`).
3//!
4//! `did:qi` is the sole sovereign W3C DID method in Qualia (`Plane::Instrument`
5//! controller document anchored by a genesis SHA-256 digest). It is strictly
6//! disjoint from `did:q42:` (Q42 Resource Coordinates) and `did:webizen:`
7//! (dual-signed ontology concept identifiers), and explicitly rejects legacy
8//! or retired prefixes (`did:hcai:`, `did:hci:`, `did:hcinet:`, `did:qualia:`,
9//! `did:q42:`) with [`DidQiError::RejectedPrefix`].
10
11use sha2::{Digest, Sha256};
12
13pub use crate::did_qi::{
14    format_did, genesis_digest, parse_did, reject_forbidden_locators, sha256_32, DidQi,
15    GitObjectStore, QiDocument, QiError, QiStore, MAX_DID_TEXT, METHOD_NAME,
16};
17
18/// Fixed-size genesis key/nonce bundle for zero-heap `did:qi` genesis digest derivation.
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub struct GenesisPayload {
21    pub controller_ed25519: [u8; 32],
22    pub controller_ml_dsa_65_hash: [u8; 32],
23    pub session_ed25519: [u8; 32],
24    pub q_link_x25519: [u8; 32],
25    pub q_link_ml_kem_768_hash: [u8; 32],
26    pub genesis_nonce: [u8; 16],
27}
28
29/// Serialize [`GenesisPayload`] into a deterministic 176-byte canonical buffer.
30pub fn canonical_genesis_bytes(g: &GenesisPayload) -> [u8; 176] {
31    let mut out = [0u8; 176];
32    out[0..32].copy_from_slice(&g.controller_ed25519);
33    out[32..64].copy_from_slice(&g.controller_ml_dsa_65_hash);
34    out[64..96].copy_from_slice(&g.session_ed25519);
35    out[96..128].copy_from_slice(&g.q_link_x25519);
36    out[128..160].copy_from_slice(&g.q_link_ml_kem_768_hash);
37    out[160..176].copy_from_slice(&g.genesis_nonce);
38    out
39}
40
41/// Derive a [`DidQi`] from [`GenesisPayload`] via SHA-256 over [`canonical_genesis_bytes`].
42pub fn did_qi_from_genesis_payload(g: &GenesisPayload) -> DidQi {
43    let bytes = canonical_genesis_bytes(g);
44    let digest: [u8; 32] = Sha256::digest(bytes).into();
45    DidQi(digest)
46}
47
48/// Errors returned by the zero-heap `did:qi` URI parser and lifecycle verifiers.
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50pub enum DidQiError {
51    /// A retired or non-sovereign prefix (`did:hcai:`, `did:hci:`, `did:hcinet:`,
52    /// `did:qualia:`, or `did:q42:`) was supplied where `did:qi:` is required.
53    RejectedPrefix,
54    /// Input does not begin with `did:qi:`.
55    InvalidPrefix,
56    /// Method-specific identifier is malformed or fails base58btc decoding.
57    MalformedId,
58    /// Unknown or malformed DID parameter hint (`;versionId=` or `;qi:backing=`).
59    InvalidHint,
60    /// Genesis SHA-256 digest does not match the canonical genesis payload.
61    DigestMismatch,
62    /// Update generation is not strictly `prev_generation + 1`.
63    NonMonotonicGeneration,
64    /// Document has been permanently deactivated via a tombstone record.
65    Deactivated,
66    /// Verification relationship is not authorized for the requested operation
67    /// (e.g. `Authentication` key attempting a document update or route update).
68    UnauthorizedRelationship,
69    /// Service endpoint violates the no-direct-locator invariant (`https://`, IP, etc.).
70    DirectLocatorForbidden,
71}
72
73impl From<QiError> for DidQiError {
74    fn from(err: QiError) -> Self {
75        match err {
76            QiError::RejectedMethod => DidQiError::RejectedPrefix,
77            QiError::InvalidPrefix => DidQiError::InvalidPrefix,
78            QiError::MalformedId
79            | QiError::Encoding
80            | QiError::MalformedDocument
81            | QiError::BufferTooSmall
82            | QiError::CanonicalTooLarge
83            | QiError::NotFound
84            | QiError::StoreFull => DidQiError::MalformedId,
85            QiError::MalformedChainId | QiError::UnsupportedChain | QiError::MalformedTx => {
86                DidQiError::InvalidHint
87            }
88            QiError::CommitmentMismatch => DidQiError::DigestMismatch,
89            QiError::StaleGeneration => DidQiError::NonMonotonicGeneration,
90            QiError::Deactivated | QiError::TombstoneRequiresDeactivate => DidQiError::Deactivated,
91            QiError::BadSignature | QiError::InvalidKey | QiError::ControllerMismatch => {
92                DidQiError::UnauthorizedRelationship
93            }
94            QiError::DirectLocatorForbidden => DidQiError::DirectLocatorForbidden,
95        }
96    }
97}
98
99/// Parameterized backing-store / resolution hints on a `did:qi:` URI.
100#[derive(Debug, Clone, Copy, PartialEq, Eq)]
101pub enum DidQiBackingHint {
102    Memory,
103    Git,
104    Utxo,
105    Mailbox,
106}
107
108/// W3C DID verification relationships supported by `did:qi`.
109#[derive(Debug, Clone, Copy, PartialEq, Eq)]
110pub enum VerificationRelationship {
111    /// `authentication` — session/challenge authentication only.
112    Authentication,
113    /// `assertionMethod` — signing Claims and Verifiable Credentials.
114    AssertionMethod,
115    /// `capabilityInvocation` — required for DID Document update, rotation,
116    /// tombstone deactivation, and RAR route-update operations.
117    CapabilityInvocation,
118}
119
120/// Operations gated by [`VerificationRelationship`].
121#[derive(Debug, Clone, Copy, PartialEq, Eq)]
122pub enum DidQiOperation {
123    AuthenticateSession,
124    IssueClaimOrCredential,
125    UpdateDocument,
126    DeactivateTombstone,
127    AuthorizeRouteUpdate,
128}
129
130/// Zero-heap parsed representation of a `did:qi:` URI with optional hints and fragment.
131#[derive(Debug, Clone, Copy, PartialEq, Eq)]
132pub struct ParsedDidQiUri<'a> {
133    pub did: DidQi,
134    pub version_id: Option<u32>,
135    pub backing_hint: Option<DidQiBackingHint>,
136    pub fragment: Option<&'a [u8]>,
137}
138
139const REJECTED_PREFIXES: &[&[u8]] = &[
140    b"did:hcai:",
141    b"did:hci:",
142    b"did:hcinet:",
143    b"did:qualia:",
144    b"did:q42:",
145];
146
147/// Parse a `did:qi:` URI byte slice in zero-heap fashion, extracting the 256-bit
148/// genesis digest (`DidQi`), optional `;versionId=<u32>`, optional
149/// `;qi:backing=git|utxo|memory|mailbox` hint, and optional `#fragment`.
150///
151/// Explicitly rejects `did:hcai:`, `did:hci:`, `did:hcinet:`, `did:qualia:`, and
152/// `did:q42:` with [`DidQiError::RejectedPrefix`].
153pub fn parse_did_qi_uri(uri: &[u8]) -> Result<ParsedDidQiUri<'_>, DidQiError> {
154    for &bad in REJECTED_PREFIXES {
155        if uri.len() >= bad.len() && uri[..bad.len()].eq_ignore_ascii_case(bad) {
156            return Err(DidQiError::RejectedPrefix);
157        }
158    }
159    if uri.len() < 7 || !uri[..7].eq_ignore_ascii_case(b"did:qi:") {
160        return Err(DidQiError::InvalidPrefix);
161    }
162
163    // Split optional `#fragment` without heap allocation.
164    let (before_frag, fragment) = match uri.iter().position(|&b| b == b'#') {
165        Some(idx) => {
166            let frag = &uri[idx + 1..];
167            if frag.is_empty() {
168                return Err(DidQiError::InvalidHint);
169            }
170            (&uri[..idx], Some(frag))
171        }
172        None => (uri, None),
173    };
174
175    // Split base DID and `;param=value` segments.
176    let (base_bytes, params_bytes) = match before_frag.iter().position(|&b| b == b';') {
177        Some(idx) => (&before_frag[..idx], Some(&before_frag[idx + 1..])),
178        None => (before_frag, None),
179    };
180
181    let did = parse_did(base_bytes)?;
182
183    let mut version_id = None;
184    let mut backing_hint = None;
185
186    if let Some(mut rest) = params_bytes {
187        while !rest.is_empty() {
188            let (seg, next) = match rest.iter().position(|&b| b == b';') {
189                Some(i) => (&rest[..i], &rest[i + 1..]),
190                None => (rest, &[][..]),
191            };
192            rest = next;
193            if seg.is_empty() {
194                continue;
195            }
196            if let Some(val) = seg.strip_prefix(b"versionId=") {
197                if val.is_empty() {
198                    return Err(DidQiError::InvalidHint);
199                }
200                let mut v: u32 = 0;
201                for &b in val {
202                    if !b.is_ascii_digit() {
203                        return Err(DidQiError::InvalidHint);
204                    }
205                    v = v
206                        .checked_mul(10)
207                        .and_then(|x| x.checked_add((b - b'0') as u32))
208                        .ok_or(DidQiError::InvalidHint)?;
209                }
210                version_id = Some(v);
211            } else if let Some(val) = seg.strip_prefix(b"qi:backing=") {
212                backing_hint = Some(match val {
213                    b"memory" => DidQiBackingHint::Memory,
214                    b"git" => DidQiBackingHint::Git,
215                    b"utxo" => DidQiBackingHint::Utxo,
216                    b"mailbox" => DidQiBackingHint::Mailbox,
217                    _ => return Err(DidQiError::InvalidHint),
218                });
219            } else {
220                return Err(DidQiError::InvalidHint);
221            }
222        }
223    }
224
225    Ok(ParsedDidQiUri {
226        did,
227        version_id,
228        backing_hint,
229        fragment,
230    })
231}
232
233/// Verify that a `DidQi`'s 256-bit genesis digest equals `SHA-256(genesis_payload_bytes)`.
234pub fn verify_genesis_sha256(did: &DidQi, genesis_payload_bytes: &[u8]) -> Result<(), DidQiError> {
235    let digest: [u8; 32] = Sha256::digest(genesis_payload_bytes).into();
236    if digest != did.0 {
237        return Err(DidQiError::DigestMismatch);
238    }
239    Ok(())
240}
241
242/// Enforce strict monotonic `qi.generation` (`next_generation == current_generation + 1`)
243/// and reject any mutation once `deactivated` (tombstone) is set.
244pub fn validate_generation_transition(
245    current_generation: u32,
246    next_generation: u32,
247    is_deactivated: bool,
248) -> Result<(), DidQiError> {
249    if is_deactivated {
250        return Err(DidQiError::Deactivated);
251    }
252    if next_generation != current_generation.saturating_add(1) {
253        return Err(DidQiError::NonMonotonicGeneration);
254    }
255    Ok(())
256}
257
258/// Enforce W3C DID verification-relationship separation:
259/// - `Authentication` keys may ONLY authenticate sessions (`AuthenticateSession`);
260///   they MUST NOT authorize document updates, tombstone deactivation, or route updates.
261/// - `AssertionMethod` keys may ONLY issue claims/credentials (`IssueClaimOrCredential`).
262/// - `CapabilityInvocation` keys are required for `UpdateDocument`, `DeactivateTombstone`,
263///   and `AuthorizeRouteUpdate`.
264pub fn check_verification_relationship(
265    relationship: VerificationRelationship,
266    operation: DidQiOperation,
267) -> Result<(), DidQiError> {
268    let allowed = matches!(
269        (relationship, operation),
270        (
271            VerificationRelationship::Authentication,
272            DidQiOperation::AuthenticateSession
273        ) | (
274            VerificationRelationship::AssertionMethod,
275            DidQiOperation::IssueClaimOrCredential
276        ) | (
277            VerificationRelationship::CapabilityInvocation,
278            DidQiOperation::UpdateDocument
279                | DidQiOperation::DeactivateTombstone
280                | DidQiOperation::AuthorizeRouteUpdate
281        )
282    );
283    if allowed {
284        Ok(())
285    } else {
286        Err(DidQiError::UnauthorizedRelationship)
287    }
288}