1use crate::verifiable_credential::Credential;
29use crate::webizen::SlgOpcode;
30
31pub const MAX_IDENTITY_BINDINGS: usize = 32;
35
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub enum CryptoScheme {
39 Ed25519,
40 MlDsa65,
41 Blake3Commitment,
42 X25519,
43 Unknown,
45}
46
47#[derive(Debug, Clone, Copy, PartialEq)]
51pub struct IdentifierBinding {
52 pub identifier: u64,
54 pub scheme: CryptoScheme,
55 pub attested: bool,
56 pub confidence: f32,
57}
58
59#[derive(Debug, Clone, Copy, PartialEq)]
61pub enum IdentityValidation {
62 Valid {
65 distinct: u16,
66 attested: u16,
67 aggregate_confidence: f32,
68 },
69 Underdetermined { distinct: u16, attested: u16 },
71 DefinitiveCollapse,
75}
76
77pub fn validate_enumerated_identity(
83 bindings: &[IdentifierBinding],
84 min_distinct: u16,
85 min_attested: u16,
86) -> IdentityValidation {
87 let mut distinct = 0u16;
88 let mut attested = 0u16;
89 let mut not_prob = 1.0f32; for (i, b) in bindings.iter().enumerate() {
92 if !b.confidence.is_finite() || b.confidence >= 1.0 {
94 return IdentityValidation::DefinitiveCollapse;
95 }
96 let first_seen = !bindings[..i].iter().any(|p| p.identifier == b.identifier);
98 if first_seen {
99 distinct += 1;
100 }
101 if b.attested && b.scheme != CryptoScheme::Unknown {
103 attested += 1;
104 not_prob *= 1.0 - b.confidence.clamp(0.0, 1.0);
105 }
106 }
107
108 if distinct < min_distinct || attested < min_attested {
109 return IdentityValidation::Underdetermined { distinct, attested };
110 }
111 let max_open_unit = f32::from_bits(1.0f32.to_bits() - 1);
112 IdentityValidation::Valid {
113 distinct,
114 attested,
115 aggregate_confidence: (1.0 - not_prob).min(max_open_unit),
116 }
117}
118
119pub fn enumerated_identity_opcodes(
123 min_distinct: u32,
124 min_attested: u32,
125 out: &mut [SlgOpcode],
126) -> usize {
127 let ops = [
128 SlgOpcode::CheckMinCount(min_distinct),
129 SlgOpcode::CheckMinCount(min_attested),
130 ];
131 let n = ops.len().min(out.len());
132 out[..n].copy_from_slice(&ops[..n]);
133 n
134}
135
136pub const MAX_SHAPE_ROUTES: usize = 256;
140
141#[derive(Debug, Clone, Copy, PartialEq, Eq)]
145pub struct ShapeRoute {
146 pub shape: u64,
147 pub locus: u64,
148}
149
150pub fn shapes_for_locus(routes: &[ShapeRoute], locus: u64, out: &mut [u64]) -> usize {
153 let mut n = 0usize;
154 for r in routes {
155 if r.locus != locus || out[..n].contains(&r.shape) {
156 continue;
157 }
158 if n >= out.len() {
159 break;
160 }
161 out[n] = r.shape;
162 n += 1;
163 }
164 n
165}
166
167pub fn loci_for_shape(routes: &[ShapeRoute], shape: u64, out: &mut [u64]) -> usize {
170 let mut n = 0usize;
171 for r in routes {
172 if r.shape != shape || out[..n].contains(&r.locus) {
173 continue;
174 }
175 if n >= out.len() {
176 break;
177 }
178 out[n] = r.locus;
179 n += 1;
180 }
181 n
182}
183
184pub fn route_is_local(routes: &[ShapeRoute], shape: u64, self_locus: u64) -> bool {
186 routes
187 .iter()
188 .any(|r| r.shape == shape && r.locus == self_locus)
189}
190
191#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
195pub enum ShaclSeverity {
196 Info,
197 Warning,
198 Violation,
199 Critical,
201}
202
203#[derive(Debug, Clone, Copy, PartialEq, Eq)]
205pub enum OperationMode {
206 Online,
207 OffGrid,
208}
209
210#[derive(Debug, Clone, Copy, PartialEq, Eq)]
212pub struct ShapeViolation {
213 pub shape: u64,
214 pub focus_node: u64,
215 pub severity: ShaclSeverity,
216}
217
218#[derive(Debug, Clone, Copy, PartialEq, Eq)]
220pub struct DegradationOutcome {
221 pub blocking: u16,
223 pub degraded: u16,
225 pub subgraph_usable: bool,
227}
228
229pub fn degrade_violations(
236 violations: &[ShapeViolation],
237 mode: OperationMode,
238 out: &mut [ShapeViolation],
239) -> DegradationOutcome {
240 let mut blocking = 0u16;
241 let mut degraded = 0u16;
242 let count = violations.len().min(out.len());
243
244 for (i, v) in violations.iter().take(count).enumerate() {
245 let mut adjusted = *v;
246 let blocks = match mode {
247 OperationMode::Online => v.severity >= ShaclSeverity::Violation,
248 OperationMode::OffGrid => {
249 if v.severity == ShaclSeverity::Critical {
250 true
251 } else {
252 if v.severity >= ShaclSeverity::Violation {
254 adjusted.severity = ShaclSeverity::Warning;
255 degraded += 1;
256 }
257 false
258 }
259 }
260 };
261 if blocks {
262 blocking += 1;
263 }
264 out[i] = adjusted;
265 }
266
267 DegradationOutcome {
268 blocking,
269 degraded,
270 subgraph_usable: blocking == 0,
271 }
272}
273
274#[derive(Debug, Clone, Copy, PartialEq, Eq)]
279pub struct CredentialGate {
280 pub shape: u64,
282 pub required_claim_predicate: u64,
284 pub required_claim_object: u64,
286 pub accepted_issuer: u64,
288}
289
290pub fn credential_gates_target(gate: &CredentialGate, focus_node: u64, vc: &Credential) -> bool {
299 if vc.subject != focus_node {
300 return false;
301 }
302 if gate.accepted_issuer != 0 && vc.issuer != gate.accepted_issuer {
303 return false;
304 }
305 vc.claims.iter().any(|q| {
306 q.predicate == gate.required_claim_predicate
307 && (gate.required_claim_object == 0 || q.object == gate.required_claim_object)
308 })
309}
310
311pub fn get_identity_shacl_ttl() -> &'static str {
315 r#"
316@prefix q42: <https://webizen.org/q42#> .
317@prefix sh: <http://www.w3.org/ns/shacl#> .
318@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
319
320# Identity is an ENUMERATED state over multiple cryptographically-attested
321# identifiers — never a single definitive identifier. The out-of-band remainder is
322# preserved: identifier confidence is a RELATION strictly in (0,1), never certainty.
323q42:EnumeratedIdentityShape a sh:NodeShape ;
324 sh:targetClass q42:Principal ;
325 sh:property [
326 sh:path q42:hasIdentifier ;
327 sh:minCount 2 ;
328 sh:message "An identity must enumerate at least two distinct identifiers; a single definitive identifier collapses the out-of-band remainder." ;
329 ] ;
330 sh:property [
331 sh:path q42:identifierAttestation ;
332 sh:minCount 1 ;
333 sh:nodeKind sh:BlankNodeOrIRI ;
334 sh:message "Each identifier must carry a cryptographic attestation (Ed25519 / ML-DSA-65 / BLAKE3 commitment)." ;
335 ] ;
336 sh:property [
337 sh:path q42:identifierConfidence ;
338 sh:datatype xsd:decimal ;
339 sh:minExclusive 0 ;
340 sh:maxExclusive 1 ;
341 sh:message "Identifier confidence is strictly in (0,1); certainty (1.0) is a definitive-collapse and is rejected." ;
342 ] .
343
344# Decentralized routing: a shape is bound to the locus where its targets live, so
345# validation is dispatched locally rather than aggregating personal data centrally.
346q42:ShapeRouteShape a sh:NodeShape ;
347 sh:targetClass q42:ShapeRoute ;
348 sh:property [
349 sh:path q42:routedToLocus ;
350 sh:minCount 1 ;
351 sh:message "Every shape route must name a storage locus; validation goes to the data, not the data to a central index." ;
352 ] .
353
354# A SHACL target gated by a presented, verified Verifiable Credential.
355q42:CredentialGatedTargetShape a sh:NodeShape ;
356 sh:targetSubjectsOf q42:presentsCredential ;
357 sh:property [
358 sh:path q42:presentsCredential ;
359 sh:minCount 1 ;
360 sh:message "This target requires a presented, verified Verifiable Credential." ;
361 ] .
362"#
363}
364
365#[cfg(test)]
366mod tests {
367 use super::*;
368 use crate::verifiable_credential::Credential;
369 use crate::{q_hash, NQuin};
370
371 fn binding(
372 id: &str,
373 scheme: CryptoScheme,
374 attested: bool,
375 confidence: f32,
376 ) -> IdentifierBinding {
377 IdentifierBinding {
378 identifier: q_hash(id),
379 scheme,
380 attested,
381 confidence,
382 }
383 }
384
385 #[test]
386 fn enumerated_identity_valid_stays_below_certainty() {
387 let bindings = [
388 binding("did:key:a", CryptoScheme::Ed25519, true, 0.6),
389 binding("did:key:b", CryptoScheme::MlDsa65, true, 0.7),
390 binding("handle:c", CryptoScheme::Blake3Commitment, true, 0.5),
391 ];
392 match validate_enumerated_identity(&bindings, 2, 2) {
393 IdentityValidation::Valid {
394 distinct,
395 attested,
396 aggregate_confidence,
397 } => {
398 assert_eq!(distinct, 3);
399 assert_eq!(attested, 3);
400 assert!(aggregate_confidence > 0.9 && aggregate_confidence < 1.0);
402 }
403 other => panic!("expected Valid, got {other:?}"),
404 }
405 }
406
407 #[test]
408 fn enumerated_identity_underdetermined_when_too_few() {
409 let bindings = [
411 binding("did:key:a", CryptoScheme::Ed25519, true, 0.6),
412 binding("guess:b", CryptoScheme::Unknown, true, 0.4),
413 ];
414 assert_eq!(
415 validate_enumerated_identity(&bindings, 2, 2),
416 IdentityValidation::Underdetermined {
417 distinct: 2,
418 attested: 1
419 }
420 );
421 }
422
423 #[test]
424 fn certainty_is_a_definitive_collapse() {
425 let bindings = [
428 binding("did:key:a", CryptoScheme::Ed25519, true, 0.6),
429 binding("gov:id", CryptoScheme::MlDsa65, true, 1.0),
430 ];
431 assert_eq!(
432 validate_enumerated_identity(&bindings, 1, 1),
433 IdentityValidation::DefinitiveCollapse
434 );
435 let over_one = [binding("gov:id", CryptoScheme::MlDsa65, true, 1.25)];
436 assert_eq!(
437 validate_enumerated_identity(&over_one, 1, 1),
438 IdentityValidation::DefinitiveCollapse
439 );
440 let nan_binding = [binding("gov:id", CryptoScheme::MlDsa65, true, f32::NAN)];
441 assert_eq!(
442 validate_enumerated_identity(&nan_binding, 1, 1),
443 IdentityValidation::DefinitiveCollapse
444 );
445 }
446
447 #[test]
448 fn decentralized_routing_dispatches_to_loci() {
449 let routes = [
450 ShapeRoute {
451 shape: 1,
452 locus: 100,
453 },
454 ShapeRoute {
455 shape: 2,
456 locus: 100,
457 },
458 ShapeRoute {
459 shape: 1,
460 locus: 200,
461 },
462 ShapeRoute {
463 shape: 1,
464 locus: 100,
465 }, ];
467 let mut shapes = [0u64; 8];
468 let n = shapes_for_locus(&routes, 100, &mut shapes);
469 assert_eq!(n, 2);
470 assert!(shapes[..n].contains(&1) && shapes[..n].contains(&2));
471
472 let mut loci = [0u64; 8];
473 let m = loci_for_shape(&routes, 1, &mut loci);
474 assert_eq!(m, 2); assert!(loci[..m].contains(&100) && loci[..m].contains(&200));
476
477 assert!(route_is_local(&routes, 1, 100));
478 assert!(!route_is_local(&routes, 2, 200));
479 }
480
481 #[test]
482 fn severity_degradation_offgrid_keeps_partial_subgraph_usable() {
483 let violations = [
484 ShapeViolation {
485 shape: 1,
486 focus_node: 10,
487 severity: ShaclSeverity::Violation,
488 },
489 ShapeViolation {
490 shape: 2,
491 focus_node: 11,
492 severity: ShaclSeverity::Warning,
493 },
494 ];
495 let mut out = [violations[0]; 2];
496
497 let online = degrade_violations(&violations, OperationMode::Online, &mut out);
499 assert_eq!(online.blocking, 1);
500 assert!(!online.subgraph_usable);
501
502 let offgrid = degrade_violations(&violations, OperationMode::OffGrid, &mut out);
504 assert_eq!(offgrid.blocking, 0);
505 assert_eq!(offgrid.degraded, 1);
506 assert!(offgrid.subgraph_usable);
507 assert_eq!(out[0].severity, ShaclSeverity::Warning); }
509
510 #[test]
511 fn critical_never_degrades_even_offgrid() {
512 let violations = [ShapeViolation {
513 shape: 9,
514 focus_node: 99,
515 severity: ShaclSeverity::Critical,
516 }];
517 let mut out = [violations[0]; 1];
518 let outcome = degrade_violations(&violations, OperationMode::OffGrid, &mut out);
519 assert_eq!(outcome.blocking, 1);
520 assert_eq!(outcome.degraded, 0);
521 assert!(!outcome.subgraph_usable); assert_eq!(out[0].severity, ShaclSeverity::Critical);
523 }
524
525 #[test]
526 fn verifiable_credential_gates_the_target() {
527 let alice = q_hash("did:example:alice");
528 let issuer = q_hash("did:example:gov");
529 let cap_pred = q_hash("https://ns.webcivics.net/capability/heldBy");
530 let cap_obj = q_hash("cap:LicensedPractitioner");
531
532 let claim = NQuin {
533 subject: alice,
534 predicate: cap_pred,
535 object: cap_obj,
536 context: 0,
537 metadata: 0,
538 parity: 0,
539 };
540 let vc = Credential {
541 issuer,
542 subject: alice,
543 issued_at: 1000,
544 valid_until: 0,
545 claims: vec![claim],
546 };
547 let gate = CredentialGate {
548 shape: 1,
549 required_claim_predicate: cap_pred,
550 required_claim_object: cap_obj,
551 accepted_issuer: issuer,
552 };
553
554 assert!(credential_gates_target(&gate, alice, &vc));
556 assert!(!credential_gates_target(
558 &gate,
559 q_hash("did:example:bob"),
560 &vc
561 ));
562 let gate_other_issuer = CredentialGate {
564 accepted_issuer: q_hash("did:example:rogue"),
565 ..gate
566 };
567 assert!(!credential_gates_target(&gate_other_issuer, alice, &vc));
568 let gate_other_claim = CredentialGate {
570 required_claim_object: q_hash("cap:Something_Else"),
571 ..gate
572 };
573 assert!(!credential_gates_target(&gate_other_claim, alice, &vc));
574 let gate_any_issuer = CredentialGate {
576 accepted_issuer: 0,
577 ..gate
578 };
579 assert!(credential_gates_target(&gate_any_issuer, alice, &vc));
580 }
581}