Skip to main content

qualia_core_db/did_qi/
document.rs

1//! Bounded Qualia Identifier document and QCDE-1 canonical encoding (spec §8–§9).
2//! SHA-256 of QCDE-1 JSON is the digest for git blobs and UTXO OP_RETURN.
3
4use sha2::{Digest, Sha256};
5
6use super::id::{encode_b58, format_did, DidQi, MAX_DID_TEXT};
7use super::service::{check_relay_only, CscpMailbox, Disclosure, MAX_HINTS};
8use super::QiError;
9
10pub const MAX_AKA: usize = 4;
11pub const MAX_AKA_LEN: usize = 96;
12pub const MAX_SERVICES: usize = 8;
13pub const MAX_UNSIGNED: usize = 8192;
14pub const MAX_SIGNED: usize = 9216;
15pub const MAX_CANONICAL: usize = MAX_UNSIGNED;
16pub const CREATED_UNIX_VECTOR: u32 = 1_788_998_400;
17const CTX: &[u8] = b"[\"https://www.w3.org/ns/did/v1\",\"https://w3id.org/security/suites/ed25519-2020/v1\",\"https://webizen.network/ns/did-qi/v1\"]";
18const PROOF_PREFIX: &[u8] = b"did:qi:document:v1\0";
19
20#[derive(Clone, Copy, Debug, PartialEq, Eq)]
21pub struct AkaEntry {
22    pub bytes: [u8; MAX_AKA_LEN],
23    pub len: u8,
24}
25
26impl AkaEntry {
27    /// Copy `s` into the fixed-size entry; `BufferTooSmall` when it
28    /// exceeds `MAX_AKA_LEN`.
29    pub fn from_slice(s: &[u8]) -> Result<Self, QiError> {
30        if s.len() > MAX_AKA_LEN {
31            return Err(QiError::BufferTooSmall);
32        }
33        let mut e = Self {
34            bytes: [0u8; MAX_AKA_LEN],
35            len: s.len() as u8,
36        };
37        e.bytes[..s.len()].copy_from_slice(s);
38        Ok(e)
39    }
40}
41
42#[derive(Clone, Copy, Debug, PartialEq, Eq)]
43pub struct QiDocument {
44    pub controller_pk: [u8; 32],
45    pub created_unix: u32,
46    pub generation: u32,
47    pub deactivated: bool,
48    pub has_previous: bool,
49    pub previous_digest: [u8; 32],
50    pub aka_count: u8,
51    pub aka: [AkaEntry; MAX_AKA],
52    pub service_count: u8,
53    pub services: [CscpMailbox; MAX_SERVICES],
54    pub has_hostname_alias: bool,
55    pub hostname_did_web: AkaEntry,
56}
57
58impl QiDocument {
59    /// Empty document: zeroed keys/digests, no services or aliases,
60    /// `created_unix` set to the canonical test vector.
61    pub const fn empty() -> Self {
62        Self {
63            controller_pk: [0u8; 32],
64            created_unix: CREATED_UNIX_VECTOR,
65            generation: 0,
66            deactivated: false,
67            has_previous: false,
68            previous_digest: [0u8; 32],
69            aka_count: 0,
70            aka: [AkaEntry {
71                bytes: [0u8; MAX_AKA_LEN],
72                len: 0,
73            }; MAX_AKA],
74            service_count: 0,
75            services: [CscpMailbox::mailbox([0u8; 32], Disclosure::ApprovedRelaysOnly);
76                MAX_SERVICES],
77            has_hostname_alias: false,
78            hostname_did_web: AkaEntry {
79                bytes: [0u8; MAX_AKA_LEN],
80                len: 0,
81            },
82        }
83    }
84
85    /// The live services (`service_count` prefix of the fixed array).
86    pub fn services_slice(&self) -> &[CscpMailbox] {
87        &self.services[..self.service_count as usize]
88    }
89
90    /// Bounds check on counts plus the relay-only disclosure policy
91    /// on every service.
92    pub fn validate(&self) -> Result<(), QiError> {
93        if self.aka_count as usize > MAX_AKA || self.service_count as usize > MAX_SERVICES {
94            return Err(QiError::MalformedDocument);
95        }
96        check_relay_only(self.services_slice())
97    }
98}
99
100/// SHA-256 of `bytes` as a fixed array.
101pub fn sha256_32(bytes: &[u8]) -> [u8; 32] {
102    Sha256::digest(bytes).into()
103}
104
105/// Build the proof signing message — `PROOF_PREFIX` || unsigned
106/// digest — into `out`.
107pub fn proof_message(unsigned_digest: &[u8; 32], out: &mut [u8]) -> Result<usize, QiError> {
108    let n = PROOF_PREFIX.len() + 32;
109    if out.len() < n {
110        return Err(QiError::BufferTooSmall);
111    }
112    out[..PROOF_PREFIX.len()].copy_from_slice(PROOF_PREFIX);
113    out[PROOF_PREFIX.len()..n].copy_from_slice(unsigned_digest);
114    Ok(n)
115}
116
117/// Multibase-encode an Ed25519 key: `0xed01` multicodec prefix +
118/// base58btc with the `z` marker.
119pub fn encode_pk_multibase(pk: &[u8; 32], out: &mut [u8]) -> Result<usize, QiError> {
120    let mut raw = [0u8; 34];
121    raw[0] = 0xed;
122    raw[1] = 0x01;
123    raw[2..].copy_from_slice(pk);
124    let mut digits = [0u8; 64];
125    let n = encode_b58(&raw, &mut digits)?;
126    if out.len() < 1 + n {
127        return Err(QiError::BufferTooSmall);
128    }
129    out[0] = b'z';
130    out[1..1 + n].copy_from_slice(&digits[..n]);
131    Ok(1 + n)
132}
133
134/// Multibase-encode a raw 32-byte digest (base58btc + `z`, no
135/// multicodec prefix).
136pub fn encode_mb32(raw32: &[u8; 32], out: &mut [u8]) -> Result<usize, QiError> {
137    let mut digits = [0u8; 64];
138    let n = encode_b58(raw32, &mut digits)?;
139    if out.len() < 1 + n {
140        return Err(QiError::BufferTooSmall);
141    }
142    out[0] = b'z';
143    out[1..1 + n].copy_from_slice(&digits[..n]);
144    Ok(1 + n)
145}
146
147/// Append `bytes` at cursor `n`; `BufferTooSmall` on overflow.
148fn push(out: &mut [u8], n: usize, bytes: &[u8]) -> Result<usize, QiError> {
149    if n + bytes.len() > out.len() {
150        return Err(QiError::BufferTooSmall);
151    }
152    out[n..n + bytes.len()].copy_from_slice(bytes);
153    Ok(n + bytes.len())
154}
155
156/// Append a decimal u32 at cursor `n`.
157fn push_u32(out: &mut [u8], n: usize, v: u32) -> Result<usize, QiError> {
158    let mut tmp = [0u8; 10];
159    let mut x = v;
160    if x == 0 {
161        return push(out, n, b"0");
162    }
163    let mut i = 10;
164    while x > 0 {
165        i -= 1;
166        tmp[i] = b'0' + (x % 10) as u8;
167        x /= 10;
168    }
169    push(out, n, &tmp[i..])
170}
171
172/// Lowercase-hex encode `bytes` into `out`.
173fn hex_lower(bytes: &[u8], out: &mut [u8]) -> Result<usize, QiError> {
174    const H: &[u8; 16] = b"0123456789abcdef";
175    if out.len() < bytes.len() * 2 {
176        return Err(QiError::BufferTooSmall);
177    }
178    let mut i = 0;
179    while i < bytes.len() {
180        out[i * 2] = H[(bytes[i] >> 4) as usize];
181        out[i * 2 + 1] = H[(bytes[i] & 0xf) as usize];
182        i += 1;
183    }
184    Ok(bytes.len() * 2)
185}
186
187/// Emit `"did:qi:<hash><suffix>"` — the quoted DID URL form.
188fn emit_did_url(
189    out: &mut [u8],
190    n: usize,
191    id: Option<&DidQi>,
192    frag: &[u8],
193) -> Result<usize, QiError> {
194    let mut n = n;
195    n = push(out, n, b"\"")?;
196    if let Some(id) = id {
197        let mut did = [0u8; MAX_DID_TEXT];
198        let d = format_did(id, &mut did)?;
199        n = push(out, n, &did[..d])?;
200    }
201    n = push(out, n, frag)?;
202    push(out, n, b"\"")
203}
204
205/// Emit one `service` object (id, type, serviceEndpoint, hints).
206fn emit_service(
207    out: &mut [u8],
208    mut n: usize,
209    id: Option<&DidQi>,
210    s: &CscpMailbox,
211) -> Result<usize, QiError> {
212    n = push(out, n, b"{\"id\":")?;
213    n = emit_did_url(out, n, id, b"#mailbox")?;
214    n = push(out, n, b",\"serviceEndpoint\":{\"contactKeyMultibase\":\"")?;
215    let mut mb = [0u8; 64];
216    let m = encode_mb32(&s.contact_key, &mut mb)?;
217    n = push(out, n, &mb[..m])?;
218    n = push(out, n, b"\",\"disclosure\":\"")?;
219    n = push(out, n, s.disclosure.json_name())?;
220    n = push(out, n, b"\",\"generation\":")?;
221    n = push_u32(out, n, s.generation)?;
222    n = push(out, n, b",\"locatorKind\":\"")?;
223    n = push(out, n, s.kind.json_name())?;
224    n = push(out, n, b"\",\"publicDht\":")?;
225    n = push(out, n, if s.public_dht { b"true" } else { b"false" })?;
226    n = push(out, n, b",\"relayHints\":[")?;
227    let mut i = 0;
228    while i < s.hint_count as usize && i < MAX_HINTS {
229        if i > 0 {
230            n = push(out, n, b",")?;
231        }
232        n = push(out, n, b"{\"hintId\":\"")?;
233        n = push(
234            out,
235            n,
236            &s.hints[i].hint_id[..s.hints[i].hint_id_len as usize],
237        )?;
238        n = push(out, n, b"\",\"operatorHashHex\":\"")?;
239        let mut hx = [0u8; 64];
240        hex_lower(&s.hints[i].operator_hash, &mut hx)?;
241        n = push(out, n, &hx)?;
242        n = push(out, n, b"\"}")?;
243        i += 1;
244    }
245    n = push(out, n, b"]},\"type\":\"CscpMailbox\"}")?;
246    Ok(n)
247}
248
249/// Emit the hostname-alias service entry (`did:web`-style locator).
250fn emit_hostname_alias(
251    out: &mut [u8],
252    mut n: usize,
253    id: Option<&DidQi>,
254    did_web: &AkaEntry,
255) -> Result<usize, QiError> {
256    n = push(out, n, b"{\"id\":")?;
257    n = emit_did_url(out, n, id, b"#frontdoor")?;
258    n = push(out, n, b",\"serviceEndpoint\":{\"didWeb\":\"")?;
259    n = push(out, n, &did_web.bytes[..did_web.len as usize])?;
260    push(out, n, b"\"},\"type\":\"HostnameAlias\"}")
261}
262
263/// Emit the `verificationMethod` entry — controller DID, Ed25519
264/// multibase public key.
265fn emit_vm(
266    out: &mut [u8],
267    mut n: usize,
268    id: Option<&DidQi>,
269    pk: &[u8; 32],
270) -> Result<usize, QiError> {
271    n = push(out, n, b"{\"")?;
272    if id.is_some() {
273        n = push(out, n, b"controller\":")?;
274        n = emit_did_url(out, n, id, b"")?;
275        n = push(out, n, b",\"id\":")?;
276    } else {
277        n = push(out, n, b"id\":")?;
278    }
279    n = emit_did_url(out, n, id, b"#key-0")?;
280    n = push(out, n, b",\"publicKeyMultibase\":\"")?;
281    let mut mb = [0u8; 64];
282    let m = encode_pk_multibase(pk, &mut mb)?;
283    n = push(out, n, &mb[..m])?;
284    push(out, n, b"\",\"type\":\"Ed25519VerificationKey2020\"}")
285}
286
287/// Emit the `authentication`/`assertionMethod`/`capabilityInvocation`
288/// relationship arrays referencing `#key-0`.
289fn emit_relationships(out: &mut [u8], mut n: usize, id: Option<&DidQi>) -> Result<usize, QiError> {
290    for key in [
291        b"\"assertionMethod\":[" as &[u8],
292        b"],\"authentication\":[",
293        b"],\"capabilityInvocation\":[",
294    ] {
295        n = push(out, n, key)?;
296        n = emit_did_url(out, n, id, b"#key-0")?;
297    }
298    push(out, n, b"]")
299}
300
301/// Encode the genesis form (no `id`/`controller` — those are derived
302/// from this document's digest). Caller-buffered canonical JSON-LD.
303pub fn encode_genesis(doc: &QiDocument, out: &mut [u8]) -> Result<usize, QiError> {
304    doc.validate()?;
305    let mut n = push(out, 0, b"{\"@context\":")?;
306    n = push(out, n, CTX)?;
307    n = push(out, n, b",")?;
308    n = emit_relationships(out, n, None)?;
309    n = push(out, n, b",\"service\":[")?;
310    n = emit_service_array(out, n, None, doc)?;
311    n = push(out, n, b"],\"verificationMethod\":[")?;
312    n = emit_vm(out, n, None, &doc.controller_pk)?;
313    n = push(out, n, b"]}")?;
314    finish_encode(out, n, false)
315}
316
317/// Canonical unsigned JSON-LD encoding of the document for `id`.
318pub fn encode_unsigned(id: &DidQi, doc: &QiDocument, out: &mut [u8]) -> Result<usize, QiError> {
319    encode_document(id, doc, None, out)
320}
321
322/// Canonical signed encoding — adds the `proof` block with the
323/// multibase-encoded Ed25519 `signature`.
324pub fn encode_signed(
325    id: &DidQi,
326    doc: &QiDocument,
327    signature: &[u8; 64],
328    out: &mut [u8],
329) -> Result<usize, QiError> {
330    encode_document(id, doc, Some(signature), out)
331}
332
333/// Shared encoder for `encode_unsigned`/`encode_signed` — validates
334/// `doc`, emits the canonical key order, optional `proof` block,
335/// then the `qi` metadata object.
336fn encode_document(
337    id: &DidQi,
338    doc: &QiDocument,
339    signature: Option<&[u8; 64]>,
340    out: &mut [u8],
341) -> Result<usize, QiError> {
342    doc.validate()?;
343    let mut n = push(out, 0, b"{\"@context\":")?;
344    n = push(out, n, CTX)?;
345    if doc.aka_count > 0 {
346        n = push(out, n, b",\"alsoKnownAs\":[")?;
347        let mut i = 0;
348        while i < doc.aka_count as usize {
349            if i > 0 {
350                n = push(out, n, b",")?;
351            }
352            n = push(out, n, b"\"")?;
353            n = push(out, n, &doc.aka[i].bytes[..doc.aka[i].len as usize])?;
354            n = push(out, n, b"\"")?;
355            i += 1;
356        }
357        n = push(out, n, b"]")?;
358    }
359    n = push(out, n, b",")?;
360    n = emit_relationships(out, n, Some(id))?;
361    n = push(out, n, b",\"controller\":")?;
362    n = emit_did_url(out, n, Some(id), b"")?;
363    n = push(out, n, b",\"id\":")?;
364    n = emit_did_url(out, n, Some(id), b"")?;
365    if let Some(sig) = signature {
366        n = push(
367            out,
368            n,
369            b",\"proof\":{\"created\":\"2026-09-10T00:00:00Z\",\"proofPurpose\":\"capabilityInvocation\",\"proofValue\":\"",
370        )?;
371        let mut pv = [0u8; 96];
372        let pn = encode_mb32_sig(sig, &mut pv)?;
373        n = push(out, n, &pv[..pn])?;
374        n = push(
375            out,
376            n,
377            b"\",\"type\":\"QiDocumentSignature2026\",\"verificationMethod\":",
378        )?;
379        n = emit_did_url(out, n, Some(id), b"#key-0")?;
380        n = push(out, n, b"}")?;
381    }
382    n = push(out, n, b",\"qi\":{\"createdUnix\":")?;
383    n = push_u32(out, n, doc.created_unix)?;
384    n = push(out, n, b",\"deactivated\":")?;
385    n = push(out, n, if doc.deactivated { b"true" } else { b"false" })?;
386    n = push(out, n, b",\"generation\":")?;
387    n = push_u32(out, n, doc.generation)?;
388    if doc.has_previous {
389        n = push(out, n, b",\"previousDigest\":\"")?;
390        let mut pd = [0u8; 64];
391        let p = encode_mb32(&doc.previous_digest, &mut pd)?;
392        n = push(out, n, &pd[..p])?;
393        n = push(out, n, b"\"")?;
394    }
395    n = push(out, n, b"},\"service\":[")?;
396    n = emit_service_array(out, n, Some(id), doc)?;
397    n = push(out, n, b"],\"verificationMethod\":[")?;
398    n = emit_vm(out, n, Some(id), &doc.controller_pk)?;
399    n = push(out, n, b"]}")?;
400    finish_encode(out, n, signature.is_some())
401}
402
403/// Post-encode gate: reject forbidden locators and enforce the
404/// signed/unsigned canonical-size ceiling.
405fn finish_encode(out: &[u8], n: usize, signed: bool) -> Result<usize, QiError> {
406    super::document_decode::reject_forbidden_locators(&out[..n])?;
407    let cap = if signed { MAX_SIGNED } else { MAX_UNSIGNED };
408    if n > cap {
409        return Err(QiError::CanonicalTooLarge);
410    }
411    Ok(n)
412}
413
414/// Emit the `service` array — all mailboxes plus the optional
415/// hostname alias.
416fn emit_service_array(
417    out: &mut [u8],
418    mut n: usize,
419    id: Option<&DidQi>,
420    doc: &QiDocument,
421) -> Result<usize, QiError> {
422    let mut wrote = false;
423    let mut i = 0;
424    while i < doc.service_count as usize {
425        if wrote {
426            n = push(out, n, b",")?;
427        }
428        n = emit_service(out, n, id, &doc.services[i])?;
429        wrote = true;
430        i += 1;
431    }
432    if doc.has_hostname_alias {
433        if wrote {
434            n = push(out, n, b",")?;
435        }
436        n = emit_hostname_alias(out, n, id, &doc.hostname_did_web)?;
437    }
438    Ok(n)
439}
440
441/// Multibase-encode the 64-byte proof signature (base58btc + `z`).
442fn encode_mb32_sig(sig: &[u8; 64], out: &mut [u8]) -> Result<usize, QiError> {
443    let mut digits = [0u8; 96];
444    let n = encode_b58(sig, &mut digits)?;
445    if out.len() < 1 + n {
446        return Err(QiError::BufferTooSmall);
447    }
448    out[0] = b'z';
449    out[1..1 + n].copy_from_slice(&digits[..n]);
450    Ok(1 + n)
451}
452
453/// SHA-256 of the canonical unsigned encoding — the value the proof
454/// signs.
455pub fn unsigned_digest(id: &DidQi, doc: &QiDocument) -> Result<[u8; 32], QiError> {
456    let mut buf = [0u8; MAX_CANONICAL];
457    let n = encode_unsigned(id, doc, &mut buf)?;
458    Ok(sha256_32(&buf[..n]))
459}
460
461/// SHA-256 of the genesis encoding — the digest that names the DID.
462pub fn genesis_digest(doc: &QiDocument) -> Result<[u8; 32], QiError> {
463    let mut buf = [0u8; MAX_CANONICAL];
464    let n = encode_genesis(doc, &mut buf)?;
465    Ok(sha256_32(&buf[..n]))
466}
467
468/// Alias for `encode_genesis` — the canonical self-describing form.
469pub fn encode_canonical(doc: &QiDocument, out: &mut [u8]) -> Result<usize, QiError> {
470    encode_genesis(doc, out)
471}
472
473/// Alias for `genesis_digest`.
474pub fn canonical_digest(doc: &QiDocument) -> Result<[u8; 32], QiError> {
475    genesis_digest(doc)
476}
477
478/// Alias for `encode_unsigned` — the cold-path JSON-LD export form.
479pub fn encode_jsonld_cold(id: &DidQi, doc: &QiDocument, out: &mut [u8]) -> Result<usize, QiError> {
480    encode_unsigned(id, doc, out)
481}
482
483/// Git blob object-id of the canonical signed encoding — the
484/// content-addressed identity used for provenance chains.
485pub fn signed_git_object_id(
486    id: &DidQi,
487    doc: &QiDocument,
488    signature: &[u8; 64],
489) -> Result<[u8; 32], QiError> {
490    let mut buf = [0u8; MAX_SIGNED];
491    let n = encode_signed(id, doc, signature, &mut buf)?;
492    Ok(super::git_object::blob_object_id(&buf[..n]))
493}
494
495#[cfg(test)]
496mod tests {
497    use super::super::service::RelayHint;
498    use super::*;
499
500    fn rfc8032_pk() -> [u8; 32] {
501        let hex = b"d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a";
502        let mut pk = [0u8; 32];
503        for i in 0..32 {
504            pk[i] = ((hex_n(hex[i * 2]) << 4) | hex_n(hex[i * 2 + 1])) as u8;
505        }
506        pk
507    }
508    fn hex_n(c: u8) -> u8 {
509        match c {
510            b'0'..=b'9' => c - b'0',
511            b'a'..=b'f' => c - b'a' + 10,
512            _ => 0,
513        }
514    }
515
516    #[test]
517    fn genesis_qcde_matches_spec_vector_did() {
518        let mut doc = QiDocument::empty();
519        doc.controller_pk = rfc8032_pk();
520        doc.services[0] = CscpMailbox::mailbox(
521            sha256_32(b"did:qi:test-vector:contact-key-0"),
522            Disclosure::ApprovedRelaysOnly,
523        );
524        doc.services[0].hints[0] =
525            RelayHint::new(b"invite-1", sha256_32(b"did:qi:test-vector:operator-0")).unwrap();
526        doc.services[0].hint_count = 1;
527        doc.service_count = 1;
528        let d = genesis_digest(&doc).unwrap();
529        let mut did = [0u8; MAX_DID_TEXT];
530        let n = format_did(&DidQi(d), &mut did).unwrap();
531        assert_eq!(
532            &did[..n],
533            b"did:qi:zDgtiZgtgfbh7upfLB47yVTWLdSN4CcoaPHok9sew2BVu"
534        );
535    }
536
537    #[test]
538    fn canonical_rejects_relay_only_direct() {
539        let mut doc = QiDocument::empty();
540        doc.controller_pk = [3u8; 32];
541        doc.services[0] = CscpMailbox::direct([3u8; 32], Disclosure::ApprovedRelaysOnly);
542        doc.service_count = 1;
543        let mut buf = [0u8; MAX_CANONICAL];
544        assert_eq!(
545            encode_genesis(&doc, &mut buf),
546            Err(QiError::DirectLocatorForbidden)
547        );
548    }
549}