# SPDX-FileCopyrightText: 2026 David Porto Baraldés (Homo Universalis / Viveka) # SPDX-License-Identifier: Apache-2.0 """ Living Folio IV of Leonardo da Vinci (`logic/engines/maat_w3c_vc_notary_crucible.py` · 46-Facet Diamond Edition): 1. W3C Verifiable Credentials Data Model v2.0 (`MaatHumanDignityCredential`) with RFC 8785 (JCS) Recursive Canonicalization (strict float rejection at all nesting depths) + RFC 6979 Deterministic HMAC-SHA256 & JWS Compact Serialization (`VC-JWS` Detached & Compact Proofs). 2. RFC 6962 §2.1.1 & §2.1.2 Binary Merkle Tree & Append-Only Consistency Subproofs (`SUBPROOF(m, D[n], b)`) proving that the Golden Book of Ma'at is strictly append-only between any tree sizes `1 <= m <= n` with zero-slice `O(log n)` windowing. 3. Constant-Depth Sparse Merkle Revocation & Non-Membership Tree (`O(H)` cryptographic proof that a certificate serial is `ACTIVE`, `REVOKED`, or `EMPTY`, binding `slot_index` to `SHA-256(serial_id)` to prevent cross-slot replay). Zero external dependencies (`Python stdlib` only). """ from __future__ import annotations import base64 from dataclasses import dataclass import hashlib import hmac import json from typing import Any, Final, Mapping, Sequence FOLIO_IV_ID: Final[str] = "folio-IV-maat-w3c-vc-and-rfc6962-notary" _EMPTY_TREE_HASH: Final[bytes] = hashlib.sha256(b"").digest() _LEAF_PREFIX: Final[bytes] = b"\x00" _NODE_PREFIX: Final[bytes] = b"\x01" _SHA256_BYTES: Final[int] = 32 # ============================================================================ # SECTION I — RFC 8785 JSON CANONICALIZATION SCHEME (JCS) & BASE64URL # ============================================================================ def _assert_no_floats_recursive(value: Any, path: str = "$") -> None: """Recursively reject IEEE-754 floats at any depth inside a notary proof structure.""" if isinstance(value, float): raise TypeError(f"Floating-point numbers are forbidden in exact notary proofs at {path}; use str or int.") if isinstance(value, Mapping): for k, v in value.items(): if not isinstance(k, str): raise TypeError(f"JSON object keys must be strings at {path}, got {type(k).__name__}.") _assert_no_floats_recursive(v, f"{path}.{k}") elif isinstance(value, (list, tuple)): for idx, item in enumerate(value): _assert_no_floats_recursive(item, f"{path}[{idx}]") elif value is not None and not isinstance(value, (str, int, bool)): raise TypeError(f"Unsupported type {type(value).__name__} in JCS canonicalization at {path}.") def jcs_canonical_bytes(value: Any) -> bytes: """Serialize any JSON-compatible structure into deterministic RFC 8785 UTF-8 bytes.""" _assert_no_floats_recursive(value) return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8") def b64url_encode(data: bytes) -> str: if not isinstance(data, (bytes, bytearray)): raise TypeError("b64url_encode requires bytes.") return base64.urlsafe_b64encode(bytes(data)).rstrip(b"=").decode("ascii") def b64url_decode(token: str) -> bytes: if not isinstance(token, str) or not token: raise ValueError("b64url token must be a non-empty string.") if "=" in token or any(ch not in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_" for ch in token): raise ValueError("b64url token must use unpadded URL-safe alphabet.") rem = len(token) % 4 if rem == 1: raise ValueError("Invalid base64url token length (mod 4 == 1).") pad = "=" * ((4 - rem) % 4) decoded = base64.urlsafe_b64decode((token + pad).encode("ascii")) if b64url_encode(decoded) != token: raise ValueError("Non-canonical base64url padding bits rejected.") return decoded # ============================================================================ # SECTION II — RFC 6962 §2.1.1 & §2.1.2 APPEND-ONLY MERKLE CONSISTENCY ENGINE # ============================================================================ def _largest_power_of_two_less_than(n: int) -> int: if isinstance(n, bool) or not isinstance(n, int): raise TypeError("n must be an integer.") if n <= 1: return 0 return 1 << ((n - 1).bit_length() - 1) def rfc6962_leaf_hash(data: bytes | str) -> bytes: if isinstance(data, str): raw = data.encode("utf-8") elif isinstance(data, (bytes, bytearray)): raw = bytes(data) else: raise TypeError(f"Leaf data must be bytes or str, got {type(data).__name__}.") return hashlib.sha256(_LEAF_PREFIX + raw).digest() def rfc6962_node_hash(left: bytes, right: bytes) -> bytes: if not isinstance(left, bytes) or not isinstance(right, bytes) or len(left) != _SHA256_BYTES or len(right) != _SHA256_BYTES: raise ValueError("Internal Merkle node children must be 32-byte SHA-256 digests.") return hashlib.sha256(_NODE_PREFIX + left + right).digest() def _mth_window(leaves: Sequence[bytes | str], lo: int, hi: int) -> bytes: """Zero-slice O(n) window computation of RFC 6962 §2.1 MTH(D[lo:hi]).""" n = hi - lo if n == 0: return _EMPTY_TREE_HASH if n == 1: return rfc6962_leaf_hash(leaves[lo]) k = _largest_power_of_two_less_than(n) left = _mth_window(leaves, lo, lo + k) right = _mth_window(leaves, lo + k, hi) return rfc6962_node_hash(left, right) def rfc6962_merkle_tree_hash(leaves: Sequence[bytes | str]) -> bytes: """Compute RFC 6962 §2.1 MTH(D[n]).""" if isinstance(leaves, (str, bytes)) or not isinstance(leaves, Sequence): raise TypeError("leaves must be a sequence of bytes or str.") return _mth_window(leaves, 0, len(leaves)) def _subproof_window(m: int, leaves: Sequence[bytes | str], lo: int, hi: int, b: bool) -> list[bytes]: """Zero-slice RFC 6962 §2.1.2 SUBPROOF(m, D[lo:hi], b).""" n = hi - lo if m == n: if b: return [] return [_mth_window(leaves, lo, hi)] k = _largest_power_of_two_less_than(n) if m <= k: sub = _subproof_window(m, leaves, lo, lo + k, b) sub.append(_mth_window(leaves, lo + k, hi)) return sub sub = _subproof_window(m - k, leaves, lo + k, hi, False) sub.append(_mth_window(leaves, lo, lo + k)) return sub @dataclass(frozen=True) class MerkleConsistencyProof: """RFC 6962 §2.1.2 append-only consistency proof between old_size m and new_size n.""" old_size: int new_size: int old_root_hex: str new_root_hex: str consistency_path_hex: tuple[str, ...] def generate_rfc6962_consistency_proof( leaves: Sequence[bytes | str], old_size: int, ) -> MerkleConsistencyProof: """Prove that the first `old_size` leaves form an immutable prefix of `leaves` (`new_size`).""" if isinstance(leaves, (str, bytes)) or not isinstance(leaves, Sequence): raise TypeError("leaves must be a sequence of bytes or str.") n = len(leaves) if not isinstance(old_size, int) or isinstance(old_size, bool) or old_size < 1 or old_size > n: raise ValueError(f"old_size must satisfy 1 <= old_size <= {n}.") old_root = _mth_window(leaves, 0, old_size).hex() new_root = _mth_window(leaves, 0, n).hex() path = tuple(h.hex() for h in _subproof_window(old_size, leaves, 0, n, True)) return MerkleConsistencyProof( old_size=old_size, new_size=n, old_root_hex=old_root, new_root_hex=new_root, consistency_path_hex=path, ) def verify_rfc6962_consistency_proof(proof: MerkleConsistencyProof) -> bool: """ Verify RFC 6962 §2.1.2 consistency proof in O(log n) using constant-time digest comparison. """ if not isinstance(proof, MerkleConsistencyProof): return False first = proof.old_size second = proof.new_size if isinstance(first, bool) or isinstance(second, bool) or not isinstance(first, int) or not isinstance(second, int): return False if first < 1 or second < first: return False try: old_root = bytes.fromhex(proof.old_root_hex) new_root = bytes.fromhex(proof.new_root_hex) path = [bytes.fromhex(h) for h in proof.consistency_path_hex] except Exception: return False if len(old_root) != _SHA256_BYTES or len(new_root) != _SHA256_BYTES or any(len(p) != _SHA256_BYTES for p in path): return False if first == second: return len(path) == 0 and hmac.compare_digest(old_root, new_root) if (first & (first - 1)) == 0: path = [old_root] + path if not path: return False fn = first - 1 sn = second - 1 while (fn & 1) == 1: fn >>= 1 sn >>= 1 fr = path[0] sr = path[0] for c in path[1:]: if sn == 0: return False if (fn & 1) == 1 or fn == sn: fr = rfc6962_node_hash(c, fr) sr = rfc6962_node_hash(c, sr) while (fn & 1) == 0 and fn != 0: fn >>= 1 sn >>= 1 else: sr = rfc6962_node_hash(sr, c) fn >>= 1 sn >>= 1 return sn == 0 and hmac.compare_digest(fr, old_root) and hmac.compare_digest(sr, new_root) # ============================================================================ # SECTION III — SPARSE MERKLE REVOCATION TREE (CONSTANT DEPTH H = 16) # ============================================================================ class SparseMerkleRevocationTree: """ Deterministic Sparse Merkle Tree of depth H (default 16 -> 65,536 certificate slots) proving in O(H) whether a Ma'at Notary Certificate Serial is ACTIVE, REVOKED, or EMPTY. """ def __init__(self, depth: int = 16) -> None: if not isinstance(depth, int) or isinstance(depth, bool) or not (4 <= depth <= 32): raise ValueError("depth must be an integer in [4, 32].") self.depth = depth self._default_hashes: list[bytes] = [rfc6962_leaf_hash(b"EMPTY:0")] for _ in range(depth): prev = self._default_hashes[-1] self._default_hashes.append(rfc6962_node_hash(prev, prev)) self._nodes: dict[tuple[int, int], bytes] = {} self._statuses: dict[int, tuple[str, str]] = {} @staticmethod def compute_slot_index(serial_id: str, depth: int) -> int: if not isinstance(serial_id, str) or not serial_id.strip(): raise ValueError("serial_id must be a non-empty string.") digest = hashlib.sha256(serial_id.encode("utf-8")).digest() val = int.from_bytes(digest[:4], "big") return val & ((1 << depth) - 1) def _slot_index(self, serial_id: str) -> int: return self.compute_slot_index(serial_id, self.depth) def set_status(self, serial_id: str, status: str = "ACTIVE") -> int: if status not in ("ACTIVE", "REVOKED"): raise ValueError("status must be 'ACTIVE' or 'REVOKED'.") idx = self._slot_index(serial_id) self._statuses[idx] = (serial_id, status) leaf_val = f"{status}:{serial_id}".encode("utf-8") curr_hash = rfc6962_leaf_hash(leaf_val) self._nodes[(0, idx)] = curr_hash curr_idx = idx for lvl in range(self.depth): sibling_idx = curr_idx ^ 1 sibling_hash = self._nodes.get((lvl, sibling_idx), self._default_hashes[lvl]) parent_idx = curr_idx >> 1 if (curr_idx & 1) == 0: curr_hash = rfc6962_node_hash(curr_hash, sibling_hash) else: curr_hash = rfc6962_node_hash(sibling_hash, curr_hash) self._nodes[(lvl + 1, parent_idx)] = curr_hash curr_idx = parent_idx return idx @property def root_hex(self) -> str: return self._nodes.get((self.depth, 0), self._default_hashes[self.depth]).hex() def prove_status(self, serial_id: str) -> dict[str, Any]: idx = self._slot_index(serial_id) entry = self._statuses.get(idx) status = entry[1] if (entry is not None and entry[0] == serial_id) else "EMPTY" siblings: list[str] = [] curr_idx = idx for lvl in range(self.depth): sib_idx = curr_idx ^ 1 sib_hash = self._nodes.get((lvl, sib_idx), self._default_hashes[lvl]) siblings.append(sib_hash.hex()) curr_idx >>= 1 return { "serial_id": serial_id, "slot_index": idx, "depth": self.depth, "status": status, "siblings_hex": siblings, "root_hex": self.root_hex, } @staticmethod def verify_status_proof(proof: Mapping[str, Any]) -> bool: if not isinstance(proof, Mapping): return False try: serial_id = str(proof["serial_id"]) idx = proof["slot_index"] depth = proof["depth"] if isinstance(idx, bool) or isinstance(depth, bool) or not isinstance(idx, int) or not isinstance(depth, int): return False if not (4 <= depth <= 32): return False expected_idx = SparseMerkleRevocationTree.compute_slot_index(serial_id, depth) if idx != expected_idx: return False status = str(proof["status"]) if status not in ("ACTIVE", "REVOKED", "EMPTY"): return False siblings = [bytes.fromhex(s) for s in proof["siblings_hex"]] expected_root = bytes.fromhex(str(proof["root_hex"])) except Exception: return False if len(siblings) != depth or len(expected_root) != _SHA256_BYTES or any(len(s) != _SHA256_BYTES for s in siblings): return False if status == "EMPTY": curr = rfc6962_leaf_hash(b"EMPTY:0") else: curr = rfc6962_leaf_hash(f"{status}:{serial_id}".encode("utf-8")) curr_idx = idx for lvl in range(depth): sib = siblings[lvl] if (curr_idx & 1) == 0: curr = rfc6962_node_hash(curr, sib) else: curr = rfc6962_node_hash(sib, curr) curr_idx >>= 1 return hmac.compare_digest(curr, expected_root) # ============================================================================ # SECTION IV — W3C VERIFIABLE CREDENTIALS v2.0 FOR HUMAN DIGNITY IN AI # ============================================================================ def issue_w3c_maat_dignity_credential( *, subject_id: str, subject_name: str, dignity_score_100: int, merkle_root_hex: str, revocation_root_hex: str, issuer_secret: bytes | str, issuance_date_utc: str = "2026-11-09T00:00:00Z", serial_id: str = "MAAT-VC-2026-0001", ) -> dict[str, Any]: """ Issue a deterministic W3C Verifiable Credential v2.0 (`MaatHumanDignityCredential`) bound to RFC 6962 Merkle transparency and Rule 14 Zero-Knowledge privacy (`c_levels == 1`). """ if not isinstance(dignity_score_100, int) or isinstance(dignity_score_100, bool) or not (0 <= dignity_score_100 <= 100): raise ValueError("dignity_score_100 must be an integer in [0, 100].") if not isinstance(subject_id, str) or not subject_id.strip(): raise ValueError("subject_id must be a non-empty string.") if not isinstance(subject_name, str) or not subject_name.strip(): raise ValueError("subject_name must be a non-empty string.") try: m_bytes = bytes.fromhex(merkle_root_hex) r_bytes = bytes.fromhex(revocation_root_hex) except Exception as exc: raise ValueError(f"merkle_root_hex and revocation_root_hex must be valid hex strings: {exc}") from exc if len(m_bytes) != _SHA256_BYTES or len(r_bytes) != _SHA256_BYTES: raise ValueError("merkle_root_hex and revocation_root_hex must be 32-byte (64-hex-char) SHA-256 roots.") sec_bytes = issuer_secret.encode("utf-8") if isinstance(issuer_secret, str) else bytes(issuer_secret) if len(sec_bytes) < 16: raise ValueError("issuer_secret must be at least 16 bytes.") vc_unsigned: dict[str, Any] = { "@context": [ "https://www.w3.org/ns/credentials/v2", "https://homouniversalis.ai/codex/schemas/maat-dignity-v1.jsonld", ], "id": f"urn:uuid:{serial_id}", "type": ["VerifiableCredential", "MaatHumanDignityCredential"], "issuer": { "id": "did:web:homouniversalis.ai", "name": "Homo Universalis — Viveka (Ma'at Sovereign Notary)", "notaryFolio": "https://homouniversalis.ai/oracle/notary", }, "validFrom": issuance_date_utc, "credentialSubject": { "id": subject_id, "name": subject_name, "dignityScore100": dignity_score_100, "c_levels": 1, "cost_zero_stop": True, "lawsVerified": ["L1", "L2", "L3", "L4", "L5", "L6", "L7"], "euAiActArt50Compliant": True, "rule14ZeroKnowledge": True, "rfc6962MerkleRoot": merkle_root_hex.lower(), "sparseRevocationRoot": revocation_root_hex.lower(), }, } jcs_payload = jcs_canonical_bytes(vc_unsigned) payload_sha256 = hashlib.sha256(jcs_payload).hexdigest() jws_header_b64 = b64url_encode( jcs_canonical_bytes({"alg": "HS256", "kid": "did:web:homouniversalis.ai#maat-notary-key-1", "typ": "vc+ld+json+jws"}) ) jws_payload_b64 = b64url_encode(jcs_payload) signing_input = f"{jws_header_b64}.{jws_payload_b64}".encode("ascii") hmac_jws_sig = b64url_encode(hmac.new(sec_bytes, jcs_payload, hashlib.sha256).digest()) detached_jws = f"{jws_header_b64}..{b64url_encode(hmac.new(sec_bytes, signing_input, hashlib.sha256).digest())}" vc_signed = dict(vc_unsigned) vc_signed["proof"] = { "type": "DataIntegrityProof", "cryptosuite": "jcs-hmac-sha256-2026", "created": issuance_date_utc, "verificationMethod": "did:web:homouniversalis.ai#maat-notary-key-1", "proofPurpose": "assertionMethod", "payloadJcsSha256": payload_sha256, "proofValue": hmac_jws_sig, "detachedJws": detached_jws, } return vc_signed def verify_w3c_maat_dignity_credential( credential: Mapping[str, Any], issuer_secret: bytes | str, ) -> bool: """Verify authenticity, Law L1 invariant (`c_levels == 1`), and JCS digest of a W3C Ma'at Credential.""" if not isinstance(credential, Mapping): return False try: sec_bytes = issuer_secret.encode("utf-8") if isinstance(issuer_secret, str) else bytes(issuer_secret) except Exception: return False if len(sec_bytes) < 16: return False proof = credential.get("proof") subj = credential.get("credentialSubject") ctx = credential.get("@context") vtypes = credential.get("type") if not isinstance(proof, Mapping) or not isinstance(subj, Mapping): return False if not isinstance(ctx, list) or "https://www.w3.org/ns/credentials/v2" not in ctx: return False if not isinstance(vtypes, list) or "VerifiableCredential" not in vtypes or "MaatHumanDignityCredential" not in vtypes: return False c_lvl = subj.get("c_levels") czs = subj.get("cost_zero_stop") if isinstance(c_lvl, bool) or c_lvl != 1 or czs is not True: return False unsigned_copy = {k: v for k, v in credential.items() if k != "proof"} try: jcs_payload = jcs_canonical_bytes(unsigned_copy) except Exception: return False expected_sha = hashlib.sha256(jcs_payload).hexdigest() expected_sig = b64url_encode(hmac.new(sec_bytes, jcs_payload, hashlib.sha256).digest()) if not ( hmac.compare_digest(expected_sha, str(proof.get("payloadJcsSha256", ""))) and hmac.compare_digest(expected_sig, str(proof.get("proofValue", ""))) ): return False # If detachedJws is present, verify RFC 7515 Appendix F detached signature as well detached = proof.get("detachedJws") if detached is not None: if not isinstance(detached, str) or detached.count(".") != 2: return False hdr_b64, mid_empty, det_sig_b64 = detached.split(".") if mid_empty != "": return False signing_input = f"{hdr_b64}.{b64url_encode(jcs_payload)}".encode("ascii") expected_det_sig = b64url_encode(hmac.new(sec_bytes, signing_input, hashlib.sha256).digest()) if not hmac.compare_digest(expected_det_sig, det_sig_b64): return False return True def run_folio_iv_self_test() -> dict[str, Any]: """Deterministic self-test for Living Folio IV (< 2 ms, 0 network calls).""" leaves = [f"MAAT-LEAF-{i}" for i in range(1, 10)] c_proof = generate_rfc6962_consistency_proof(leaves, old_size=5) c_ok = verify_rfc6962_consistency_proof(c_proof) smt = SparseMerkleRevocationTree(depth=12) smt.set_status("MAAT-VC-2026-0001", "ACTIVE") smt.set_status("MAAT-VC-2026-0002", "REVOKED") p_active = smt.prove_status("MAAT-VC-2026-0001") p_revoked = smt.prove_status("MAAT-VC-2026-0002") smt_ok = ( SparseMerkleRevocationTree.verify_status_proof(p_active) and p_active["status"] == "ACTIVE" and SparseMerkleRevocationTree.verify_status_proof(p_revoked) and p_revoked["status"] == "REVOKED" ) secret = b"HomoUniversalis-Maat-Notary-Key-32B" vc = issue_w3c_maat_dignity_credential( subject_id="https://homouniversalis.ai", subject_name="Homo Universalis — Viveka", dignity_score_100=100, merkle_root_hex=c_proof.new_root_hex, revocation_root_hex=smt.root_hex, issuer_secret=secret, ) vc_ok = verify_w3c_maat_dignity_credential(vc, secret) return { "folio_id": FOLIO_IV_ID, "all_invariants_passed": bool(c_ok and smt_ok and vc_ok), "rfc6962_consistency_verified": c_ok, "sparse_merkle_revocation_verified": smt_ok, "w3c_vc_verified": vc_ok, "merkle_root_hex": c_proof.new_root_hex, "revocation_root_hex": smt.root_hex, }