1use 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#[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
29pub 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
41pub 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50pub enum DidQiError {
51 RejectedPrefix,
54 InvalidPrefix,
56 MalformedId,
58 InvalidHint,
60 DigestMismatch,
62 NonMonotonicGeneration,
64 Deactivated,
66 UnauthorizedRelationship,
69 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
101pub enum DidQiBackingHint {
102 Memory,
103 Git,
104 Utxo,
105 Mailbox,
106}
107
108#[derive(Debug, Clone, Copy, PartialEq, Eq)]
110pub enum VerificationRelationship {
111 Authentication,
113 AssertionMethod,
115 CapabilityInvocation,
118}
119
120#[derive(Debug, Clone, Copy, PartialEq, Eq)]
122pub enum DidQiOperation {
123 AuthenticateSession,
124 IssueClaimOrCredential,
125 UpdateDocument,
126 DeactivateTombstone,
127 AuthorizeRouteUpdate,
128}
129
130#[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
147pub 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 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 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
233pub 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
242pub 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
258pub 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}