# SPDX-FileCopyrightText: 2026 David Porto Baraldés (Homo Universalis / Viveka) # SPDX-License-Identifier: Apache-2.0 """quantum_eternal_provenance_core.py — HU-ETERNAL-PROVENANCE v1.0 (Living Folio VIII). Post-Quantum Triple-Anchor Cryptography (NIST P-256 ES256 + WOTS+-SHA256 + FIPS 204 Ring NTT Witness) & C2PA-MCP Symbiotic Human-AI Co-Creation Provenance Kernel. Central Barycenter (Reina de la Rosa · Axial Foc-Aigua) | F0c=Ca0s*0rdre(Am0r_Un1f1cat_Etern) """ from __future__ import annotations from dataclasses import dataclass, field, fields, is_dataclass, replace from fractions import Fraction import hashlib import hmac import json import re import string import time from typing import Any, Collection, Mapping, Sequence import uuid PROTOCOL_VERSION = "HU-ETERNAL-PROVENANCE-v1.0" SACRED_EQUATION = "F0c=Ca0s*0rdre(Am0r_Un1f1cat_Etern)" DEFAULT_MASTER_SEED = b"HU-LIVING-FOLIO-VIII-BARYCENTER-SEED" PEARL_EARTH_HEART = "Pearl 027 — Unir l'Instint de la Terra amb la Devocio del Cor: ground every mathematical seal in living human dignity." PEARL_SACRED_BALANCE = "Pearl 064 — L'Equilibri Sagrat Masculi-Femeni: structural exactness and compassionate clarity walk as equals." PEARL_TRANSPARENT_STREAM = "Pearl 081 — L'Aigua Clara del Llinatge Honest: disclose every synthetic current so trust flows unbroken." PEARL_SILENT_SANCTUARY = "Pearl 108 — El Santuari de l'Aigua Serena: shelter the rough draft in intimacy and honor the moral veto in peace." IJSON_MAX_INT = (1 << 53) - 1 IJSON_MIN_INT = -IJSON_MAX_INT # NIST P-256 (secp256r1) Exact Field & Subgroup Constants (P1a) P = 0xFFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF A = P - 3 B = 0x5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B N = 0xFFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551 GX = 0x6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296 GY = 0x4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5 P256_HALF_N = N // 2 # WOTS+-SHA256 & 4-Leaf RFC 6962 Key Tree Constants (P1b) WOTS_W = 16 WOTS_MSG_CHAINS = 64 WOTS_CSUM_CHAINS = 3 WOTS_TOTAL_CHAINS = 67 WOTS_MAX_STEP = 15 WOTS_TREE_LEAVES = 4 _WOTS_LEAF_LEN = 32 + 4 + WOTS_TOTAL_CHAINS * 32 _WOTS_STEP_BYTES = tuple(i.to_bytes(2, "big") for i in range(WOTS_W)) _WOTS_SIG_REQ_KEYS = frozenset({"pub_seed_b64", "leaf_idx", "chains_b64", "auth_path_hex"}) _WOTS_SIG_ALL_KEYS = _WOTS_SIG_REQ_KEYS | {"merkle_root_hex"} # FIPS 204 Algebraic Ring Z_8380417[X]/(X^256 + 1) NTT Constants (P1c) NTT_Q = 8380417 NTT_ZETA = 1753 NTT_N = 256 NTT_INV_N = 8347681 NTT_ETA = 2 NTT_TAU = 16 NTT_BETA = 32 NTT_GAMMA1 = 131072 NTT_NORM_BOUND = NTT_GAMMA1 - NTT_BETA _U32_SHIFTS = (224, 192, 160, 128, 96, 64, 32, 0) # Symbiotic Co-Creation Taxonomy & Sovereign Revocation Signals HUMAN_LYRIC_GENESIS = "HUMAN_LYRIC_GENESIS" AI_INSTRUMENTAL_SYNTHESIS = "AI_INSTRUMENTAL_SYNTHESIS" HUMAN_SURGICAL_STEM_EDIT = "HUMAN_SURGICAL_STEM_EDIT" ACOUSTIC_SILK_MASTERING = "ACOUSTIC_SILK_MASTERING" VALID_STAGE_TYPES = frozenset( {HUMAN_LYRIC_GENESIS, AI_INSTRUMENTAL_SYNTHESIS, HUMAN_SURGICAL_STEM_EDIT, ACOUSTIC_SILK_MASTERING} ) VALID_HOP_PROTOCOLS = frozenset({"C2PA_GENESIS", "MCP_TOOL_CALL", "A2A_SYNTHESIS", "C2PA_MASTER_SEAL"}) _HOP_PROTO_RE = re.compile(r"^(?:C2PA|MCP|A2A)_[A-Z0-9_]{2,32}$") AUTHOR_MORAL_VETO = "AUTHOR_MORAL_VETO" COST_ZERO_STOP = "COST_ZERO_STOP" VALID_REVOCATION_REASONS = frozenset({AUTHOR_MORAL_VETO, COST_ZERO_STOP}) # === Section 1: Compassionate Exceptions & Disjoint Zero-Float Guards (P5) === class _DisjointScalarTypeError(TypeError): """Raised when float or bool violates strict scalar disjointness under P5.""" class ProvenanceError(ValueError): """Fail-closed boundary pairing diagnostic precision with 108 Pearls guidance.""" DEFAULT_PEARL = PEARL_SACRED_BALANCE def __init__(self, message: str, pearl_guidance: str | None = None) -> None: pearl = self.DEFAULT_PEARL if pearl_guidance is None else pearl_guidance super().__init__(f"{message} | {pearl}") self.reason = message self.pearl_guidance = pearl class AuthorshipSlopOrLicenseError(ProvenanceError): """Raised when human authorship ratio, AI licenses, stage weights, or peak ceiling fail.""" class ImpersonationOrBiometricError(ProvenanceError): """Raised fail-closed when living-voice cloning prompts or biometric keys appear.""" DEFAULT_PEARL = PEARL_EARTH_HEART class ContentIdAbuseError(ProvenanceError): """Raised when Content-ID fingerprinting is claimed on AI-synthesized audio.""" class C2paIntegrityOrDisclosureError(ProvenanceError): """Raised when RFC 6962 Merkle proofs, Art. 50 disclosure, or Rule 14 hygiene fail.""" DEFAULT_PEARL = PEARL_TRANSPARENT_STREAM class SignatureVerificationError(ProvenanceError): """Raised when any anchor of the Triple Sovereign Seal fails verification.""" class RoyaltyOrBudgetError(ProvenanceError): """Raised when rational royalty conservation or 0 <= L <= B governance fails.""" class RevokedProvenanceError(ProvenanceError): """Raised when an envelope, hop, or ancestor was halted by Moral Veto or Cost-Zero.""" DEFAULT_PEARL = PEARL_SILENT_SANCTUARY def _req_type(value, expected, name): if type(value) is not expected: err_cls = _DisjointScalarTypeError if isinstance(value, (float, bool)) else TypeError raise err_cls(f"{name} must be strict {expected.__name__}, got {type(value).__name__}") return value def require_strict_int(value: Any, name: str = "value") -> int: """Accept exact Python int while strictly rejecting float, bool, and subclasses.""" return _req_type(value, int, name) def require_strict_bool(value: Any, name: str = "flag") -> bool: """Accept exact Python bool while rejecting int, float, and other types.""" return _req_type(value, bool, name) def require_strict_bytes(value: Any, name: str = "data") -> bytes: """Accept exact Python bytes while rejecting float, bool, str, and bytearray.""" return _req_type(value, bytes, name) def require_strict_str(value: Any, name: str = "text") -> str: """Accept exact Python str while rejecting float, bool, bytes, and other types.""" return _req_type(value, str, name) def require_strict_fraction(value: Any, name: str = "rational") -> Fraction: """Accept exact Fraction or strict int (never float or bool) and return Fraction.""" t = type(value) if t is Fraction: return value if t is int: return Fraction(value, 1) err_cls = _DisjointScalarTypeError if isinstance(value, (float, bool)) else TypeError raise err_cls(f"{name} must be Fraction or strict int, got {t.__name__}") def _is_seq(value): return type(value) in (list, tuple) or ( isinstance(value, Sequence) and not isinstance(value, (str, bytes, bytearray, memoryview)) ) def _require_seq(value, name="sequence"): if not _is_seq(value): err_cls = _DisjointScalarTypeError if isinstance(value, (float, bool)) else TypeError raise err_cls(f"{name} must be a non-string/bytes Sequence") return value def _req_strs(obj, *names): for name in names: if type(getattr(obj, name)) is not str: require_strict_str(getattr(obj, name), name) def _ct_str_eq(a, b): return type(a) is str and type(b) is str and hmac.compare_digest(a.encode("utf-8"), b.encode("utf-8")) _FAST_ATOMS = frozenset({int, bool, str, bytes, Fraction, type(None)}) _DC_FIELDS_CACHE: dict[type, tuple[str, ...]] = {} def assert_no_floats(obj: Any, _active: set[int] | None = None) -> None: """Reject float instances (TypeError) and cyclic containers (ValueError) in O(N).""" t = type(obj) if t in _FAST_ATOMS: return if isinstance(obj, float): raise _DisjointScalarTypeError("Floating-point value rejected under Zero-Float Covenant (P5)") oid = id(obj) stack = set() if _active is None else _active if oid in stack: raise ValueError("Cyclic container forbidden") stack.add(oid) try: if is_dataclass(obj) and not isinstance(obj, type): fnames = _DC_FIELDS_CACHE.get(t) if fnames is None: if len(_DC_FIELDS_CACHE) >= 64: _DC_FIELDS_CACHE.clear() fnames = _DC_FIELDS_CACHE[t] = tuple(f.name for f in fields(obj)) for fn in fnames: v = getattr(obj, fn) if type(v) not in _FAST_ATOMS: assert_no_floats(v, stack) elif isinstance(obj, Mapping): for k, v in obj.items(): if type(k) not in _FAST_ATOMS: assert_no_floats(k, stack) if type(v) not in _FAST_ATOMS: assert_no_floats(v, stack) elif isinstance(obj, Collection) and not isinstance(obj, (str, bytes, bytearray, memoryview)): for x in obj: if type(x) not in _FAST_ATOMS: assert_no_floats(x, stack) inst_d = getattr(obj, "__dict__", None) if isinstance(inst_d, Mapping): for k, v in inst_d.items(): if type(k) not in _FAST_ATOMS: assert_no_floats(k, stack) if type(v) not in _FAST_ATOMS: assert_no_floats(v, stack) raw_slots = getattr(t, "__slots__", ()) for sname in ((raw_slots,) if type(raw_slots) is str else raw_slots): if sname not in ("__dict__", "__weakref__") and hasattr(obj, sname): assert_no_floats(getattr(obj, sname), stack) finally: stack.remove(oid) _SHA256_HEX_RE = re.compile(r"^[0-9a-f]{64}$") def require_sha256_hex(digest_hex: Any, name: str = "sha256_hex") -> str: """Require an exact 64-character lowercase ASCII hexadecimal SHA-256 string.""" s = require_strict_str(digest_hex, name) if not _SHA256_HEX_RE.match(s): raise ValueError(f"{name} must be 64 lowercase hexadecimal characters") return s # === Section 2: Base64url (RFC 4648 §5), RFC 8785 JCS & Fixed-Point Rule 14 (P5) === _B64URL_ALPHABET = string.ascii_uppercase + string.ascii_lowercase + string.digits + "-_" _B64URL_DECODE_MAP = {ch: idx for idx, ch in enumerate(_B64URL_ALPHABET)} def b64url_encode(data: bytes) -> str: """Encode strict bytes into unpadded URL-safe Base64 obeying RFC 4648 §5.""" raw = require_strict_bytes(data, "data") n = len(raw) if n == 0: return "" out, alpha, full_end = [], _B64URL_ALPHABET, (n // 3) * 3 for i in range(0, full_end, 3): triple = (raw[i] << 16) | (raw[i + 1] << 8) | raw[i + 2] out.extend((alpha[(triple >> 18) & 0x3F], alpha[(triple >> 12) & 0x3F], alpha[(triple >> 6) & 0x3F], alpha[triple & 0x3F])) rem = n - full_end if rem == 1: val = raw[full_end] << 4 out.extend((alpha[(val >> 6) & 0x3F], alpha[val & 0x3F])) elif rem == 2: val = (raw[full_end] << 10) | (raw[full_end + 1] << 2) out.extend((alpha[(val >> 12) & 0x3F], alpha[(val >> 6) & 0x3F], alpha[val & 0x3F])) return "".join(out) def b64url_decode(token: str) -> bytes: """Decode unpadded canonical RFC 4648 §5 Base64url string into bytes in O(N) space.""" tok = require_strict_str(token, "token") m = len(tok) if m == 0: return b"" rem = m % 4 if rem == 1 or "=" in tok: raise ValueError("Invalid unpadded RFC 4648 §5 Base64url length or '=' padding") dmap, out, full_quads = _B64URL_DECODE_MAP, bytearray(), (m // 4) * 4 for i in range(0, full_quads, 4): s0, s1, s2, s3 = dmap.get(tok[i]), dmap.get(tok[i + 1]), dmap.get(tok[i + 2]), dmap.get(tok[i + 3]) if s0 is None or s1 is None or s2 is None or s3 is None: raise ValueError("Invalid Base64url character") quad = (s0 << 18) | (s1 << 12) | (s2 << 6) | s3 out.extend(((quad >> 16) & 0xFF, (quad >> 8) & 0xFF, quad & 0xFF)) if rem == 2: s0, s1 = dmap.get(tok[full_quads]), dmap.get(tok[full_quads + 1]) if s0 is None or s1 is None or (s1 & 0x0F) != 0: raise ValueError("Invalid or non-canonical 2-char Base64url tail") out.append(((s0 << 2) | (s1 >> 4)) & 0xFF) elif rem == 3: s0, s1, s2 = dmap.get(tok[full_quads]), dmap.get(tok[full_quads + 1]), dmap.get(tok[full_quads + 2]) if s0 is None or s1 is None or s2 is None or (s2 & 0x03) != 0: raise ValueError("Invalid or non-canonical 3-char Base64url tail") trio = (s0 << 10) | (s1 << 4) | (s2 >> 2) out.extend(((trio >> 8) & 0xFF, trio & 0xFF)) return bytes(out) _JCS_SHORT_ESCAPES = {0x08: "\\b", 0x09: "\\t", 0x0A: "\\n", 0x0C: "\\f", 0x0D: "\\r", 0x22: '\\"', 0x5C: "\\\\"} def _assert_no_lone_surrogates(text): for ch in text: cp = ord(ch) if 0xD800 <= cp <= 0xDFFF: raise ValueError(f"Lone UTF-16 surrogate U+{cp:04X} forbidden in RFC 8785 JCS") def _jcs_escape_str(text): parts = ['"'] for ch in text: cp = ord(ch) if 0xD800 <= cp <= 0xDFFF: raise ValueError(f"Lone UTF-16 surrogate U+{cp:04X} forbidden in RFC 8785 JCS") esc = _JCS_SHORT_ESCAPES.get(cp) parts.append(esc if esc is not None else (f"\\u{cp:04x}" if cp < 0x20 else ch)) parts.append('"') return "".join(parts) def _jcs_serialize(obj): if isinstance(obj, float): raise _DisjointScalarTypeError("Float forbidden in RFC 8785 JCS under Zero-Float Covenant") if obj is None: return "null" t = type(obj) if t is bool: return "true" if obj else "false" if t is int: if obj < IJSON_MIN_INT or obj > IJSON_MAX_INT: raise ValueError(f"Integer {obj} exceeds RFC 8785 I-JSON +/- (2^53 - 1) bounds") return str(obj) if t is str: return _jcs_escape_str(obj) if _is_seq(obj): return "[" + ",".join(_jcs_serialize(item) for item in obj) + "]" if isinstance(obj, Mapping): keyed, seen = [], set() for k, v in obj.items(): ks = require_strict_str(k, "jcs_key") if ks in seen: raise ValueError(f"Duplicate JSON object key {ks!r} forbidden in RFC 8785") seen.add(ks) _assert_no_lone_surrogates(ks) keyed.append((ks.encode("utf-16-be"), ks, v)) keyed.sort(key=lambda entry: entry[0]) return "{" + ",".join(f"{_jcs_escape_str(k)}:{_jcs_serialize(v)}" for _, k, v in keyed) + "}" raise TypeError(f"Unsupported type for RFC 8785 JCS: {t.__name__}") def jcs_canonical_bytes(obj: Any) -> bytes: """Serialize exact JSON-compatible Python data into RFC 8785 canonical UTF-8 bytes.""" assert_no_floats(obj) return _jcs_serialize(obj).encode("utf-8") # Zero-backtracking fixed-point Rule 14 sweep: Paths -> Email -> VVK -> Coords -> Date -> Phone _RE_UNIX_PATH = re.compile( r"(?:(?i:\bfile:(?://(?:localhost)?)?)(?=/)|(?|\[\])(){}]*[^\s.,;:\"?!'<>|\[\])(){}]|/)" ) _RE_WIN_PATH = re.compile( r"(?:(?:(?i:\bfile://(?:localhost)?/)|(?|\[\])(){}]*[^\s.,;:\"?!'<>|\[\])(){}])?" ) _RE_EMAIL = re.compile( r"(? str: """Idempotently scrub paths, emails, VVK keys, coordinates, ISO dates, and phones.""" cur = require_strict_str(text, "text") for _ in range(16): nxt = _rule14_sweep_once(cur) if nxt == cur: return cur cur = nxt return cur def _mask_collision_safe_dict(pairs, domain): buckets = {} for ks, val in pairs: buckets.setdefault(rule14_mask_provenance_text(ks), []).append((ks.encode("utf-16-be"), ks, val)) out = {} for mk in sorted(buckets): entries = sorted(buckets[mk], key=lambda item: item[0]) if len(entries) == 1 and mk not in out: out[mk] = entries[0][2] else: for _, rk, mv in entries: tag = hashlib.sha256(domain + rk.encode("utf-8")).hexdigest()[:8] ck, sfx = f"{mk}#{tag}", 1 while ck in out: sfx += 1 ck = f"{mk}#{tag}-{sfx}" out[ck] = mv return out def _mask_structure_deep(obj): if type(obj) is str: return rule14_mask_provenance_text(obj) if isinstance(obj, Mapping): return _mask_collision_safe_dict( [(require_strict_str(k, "meta_key"), _mask_structure_deep(v)) for k, v in obj.items()], b"HU-META-KEY\x00", ) if type(obj) is list: return [_mask_structure_deep(x) for x in obj] if _is_seq(obj): return tuple(_mask_structure_deep(x) for x in obj) return obj def _assert_rule14_clean_deep(obj): stack = [obj] while stack: cur = stack.pop() if type(cur) is str: if rule14_mask_provenance_text(cur) != cur: raise C2paIntegrityOrDisclosureError("Unmasked Rule 14 PII/VVK detected in public field") elif isinstance(cur, Mapping): stack.extend(cur.keys()) stack.extend(cur.values()) elif isinstance(cur, (set, frozenset)) or _is_seq(cur): stack.extend(cur) # === Section 3: Classical NIST P-256 ES256 (4-Bit Window + Subgroup + RFC 6979 + low-S) === _P256_INF = (0, 1, 0) _VALIDATED_P256_PUBKEYS: set[tuple[int, int]] = {(GX, GY), (GX, (P - GY) % P)} _MAX_P256_PUBKEY_CACHE = 1024 _P256_G_TABLE: tuple[tuple[int, int, int], ...] = () def _p256_jac_double(pt): x, y, z = pt if z == 0 or y == 0: return _P256_INF yy, zz = (y * y) % P, (z * z) % P s = (4 * x * yy) % P m = (3 * (x - zz) * (x + zz)) % P x3 = (m * m - 2 * s) % P return (x3, (m * (s - x3) - 8 * yy * yy) % P, (2 * y * z) % P) def _p256_jac_add(p1, p2): x1, y1, z1 = p1 x2, y2, z2 = p2 if z1 == 0: return p2 if z2 == 0: return p1 z1z1, z2z2 = (z1 * z1) % P, (z2 * z2) % P u1, u2 = (x1 * z2z2) % P, (x2 * z1z1) % P s1, s2 = (y1 * z2 * z2z2) % P, (y2 * z1 * z1z1) % P if u1 == u2: return _p256_jac_double(p1) if s1 == s2 else _P256_INF h, r = (u2 - u1) % P, (s2 - s1) % P hh = (h * h) % P hhh, v = (h * hh) % P, (u1 * hh) % P x3 = (r * r - hhh - 2 * v) % P return (x3, (r * (v - x3) - s1 * hhh) % P, (z1 * z2 * h) % P) def _p256_scalar_mul_g(k): global _P256_G_TABLE k_mod = (k if type(k) is int else require_strict_int(k, "k")) % N if k_mod == 0: return _P256_INF if not _P256_G_TABLE: g1 = (GX, GY, 1) tbl = [_P256_INF, g1] for _ in range(2, 16): tbl.append(_p256_jac_add(tbl[-1], g1)) _P256_G_TABLE = tuple(tbl) tbl, acc = _P256_G_TABLE, _P256_INF for shift in range(252, -1, -4): if acc[2] != 0: acc = _p256_jac_double(_p256_jac_double(_p256_jac_double(_p256_jac_double(acc)))) nib = (k_mod >> shift) & 0x0F if nib: acc = tbl[nib] if acc[2] == 0 else _p256_jac_add(acc, tbl[nib]) return acc def _p256_to_affine(pt): x, y, z = pt if z == 0: return None inv_z = pow(z, -1, P) inv_z2 = (inv_z * inv_z) % P return ((x * inv_z2) % P, (y * inv_z2 * inv_z) % P) def _p256_shamir_mul_add(u1, u2, qx, qy): g_pt, q_pt = (GX, GY, 1), (qx, qy, 1) gq_pt, acc = _p256_jac_add(g_pt, q_pt), _P256_INF for bit_idx in range(max(u1.bit_length(), u2.bit_length()) - 1, -1, -1): acc = _p256_jac_double(acc) b1, b2 = (u1 >> bit_idx) & 1, (u2 >> bit_idx) & 1 if b1 and b2: acc = _p256_jac_add(acc, gq_pt) elif b1: acc = _p256_jac_add(acc, g_pt) elif b2: acc = _p256_jac_add(acc, q_pt) return acc def _p256_encode_sec1(pub_xy, compressed=False): qx, qy = require_strict_int(pub_xy[0], "qx"), require_strict_int(pub_xy[1], "qy") if require_strict_bool(compressed, "compressed"): return (b"\x03" if (qy & 1) else b"\x02") + qx.to_bytes(32, "big") return b"\x04" + qx.to_bytes(32, "big") + qy.to_bytes(32, "big") def _p256_validate_pubkey(public_key): assert_no_floats(public_key) if type(public_key) is bytes: if len(public_key) == 65 and public_key[0] == 0x04: qx, qy = int.from_bytes(public_key[1:33], "big"), int.from_bytes(public_key[33:65], "big") elif len(public_key) == 64: qx, qy = int.from_bytes(public_key[:32], "big"), int.from_bytes(public_key[32:], "big") elif len(public_key) == 33 and public_key[0] in (0x02, 0x03): qx = int.from_bytes(public_key[1:33], "big") if qx >= P: return None rhs = (qx * qx * qx + A * qx + B) % P qy = pow(rhs, (P + 1) >> 2, P) if (qy * qy) % P != rhs: return None if (qy & 1) != (public_key[0] & 1): qy = (P - qy) % P if (qy & 1) != (public_key[0] & 1): return None else: return None elif type(public_key) is tuple and len(public_key) == 2: qx, qy = require_strict_int(public_key[0], "pub_xy[0]"), require_strict_int(public_key[1], "pub_xy[1]") else: raise TypeError("P-256 public_key must be (qx, qy) tuple or SEC1 bytes") if not (0 <= qx < P and 0 <= qy < P) or (qy * qy) % P != (qx * qx * qx + A * qx + B) % P: return None pair = (qx, qy) if pair not in _VALIDATED_P256_PUBKEYS: if _p256_shamir_mul_add(0, N, qx, qy)[2] != 0: return None if len(_VALIDATED_P256_PUBKEYS) >= _MAX_P256_PUBKEY_CACHE: _VALIDATED_P256_PUBKEYS.clear() _VALIDATED_P256_PUBKEYS.add(pair) return pair def p256_derive_keypair(seed: bytes) -> tuple[int, tuple[int, int]]: """Derive a deterministic secp256r1 keypair (d, (qx, qy)) from non-empty seed.""" raw_seed = require_strict_bytes(seed, "seed") if not raw_seed: raise ProvenanceError("p256_derive_keypair requires non-empty seed bytes") ctr = 0 while True: d = int.from_bytes(hashlib.sha256(b"HU-P256-KEYGEN-v1\x00" + raw_seed + ctr.to_bytes(4, "big")).digest(), "big") ctr += 1 if 1 <= d < N: aff = _p256_to_affine(_p256_scalar_mul_g(d)) if aff is not None: if len(_VALIDATED_P256_PUBKEYS) >= _MAX_P256_PUBKEY_CACHE: _VALIDATED_P256_PUBKEYS.clear() _VALIDATED_P256_PUBKEYS.add(aff) return (d, aff) def p256_sign_es256(priv_d: int, message: bytes) -> bytes: """Sign message with ES256 (RFC 6979 HMAC-SHA256 deterministic k + canonical low-S).""" d, msg = require_strict_int(priv_d, "priv_d"), require_strict_bytes(message, "message") if not (1 <= d < N): raise ProvenanceError("priv_d out of P-256 scalar range [1, N-1]") z = int.from_bytes(hashlib.sha256(msg).digest(), "big") bx = d.to_bytes(32, "big") + (z % N).to_bytes(32, "big") v = b"\x01" * 32 k_mac = hmac.new(b"\x00" * 32, v + b"\x00" + bx, hashlib.sha256).digest() v = hmac.new(k_mac, v, hashlib.sha256).digest() k_mac = hmac.new(k_mac, v + b"\x01" + bx, hashlib.sha256).digest() v = hmac.new(k_mac, v, hashlib.sha256).digest() while True: v = hmac.new(k_mac, v, hashlib.sha256).digest() k_cand = int.from_bytes(v, "big") if 1 <= k_cand < N: aff = _p256_to_affine(_p256_scalar_mul_g(k_cand)) if aff is not None: r = aff[0] % N s = (pow(k_cand, -1, N) * (z + r * d)) % N if r != 0 and s != 0: s = N - s if s > P256_HALF_N else s return r.to_bytes(32, "big") + s.to_bytes(32, "big") k_mac = hmac.new(k_mac, v + b"\x00", hashlib.sha256).digest() v = hmac.new(k_mac, v, hashlib.sha256).digest() def p256_verify_es256(public_key: tuple[int, int] | bytes, message: bytes, signature: bytes) -> bool: """Verify 64-byte IEEE P1363 r||s ES256 signature enforcing subgroup and low-S.""" msg, sig = require_strict_bytes(message, "message"), require_strict_bytes(signature, "signature") parsed = _p256_validate_pubkey(public_key) if parsed is None or len(sig) != 64: return False r, s = int.from_bytes(sig[:32], "big"), int.from_bytes(sig[32:], "big") if not (1 <= r < N and 1 <= s <= P256_HALF_N): return False qx, qy = parsed z = int.from_bytes(hashlib.sha256(msg).digest(), "big") w = pow(s, -1, N) aff = _p256_to_affine(_p256_shamir_mul_add((z * w) % N, (r * w) % N, qx, qy)) return aff is not None and hmac.compare_digest((aff[0] % N).to_bytes(32, "big"), r.to_bytes(32, "big")) # === Section 4: RFC 6962 Merkle Engine & Stateless WOTS+-SHA256 Key Tree (P1b) === def rfc6962_leaf_hash(leaf_payload: bytes) -> bytes: """Compute RFC 6962 §2.1 domain-separated leaf hash SHA256(0x00 || leaf_payload).""" return hashlib.sha256(b"\x00" + require_strict_bytes(leaf_payload, "leaf_payload")).digest() def rfc6962_node_hash(left_32b: bytes, right_32b: bytes) -> bytes: """Compute RFC 6962 §2.1 internal node hash SHA256(0x01 || left_32b || right_32b).""" lb, rb = require_strict_bytes(left_32b, "left_32b"), require_strict_bytes(right_32b, "right_32b") if len(lb) != 32 or len(rb) != 32: raise ValueError("RFC 6962 internal child hashes must be 32 bytes") return hashlib.sha256(b"\x01" + lb + rb).digest() def _rfc6962_prehash_leaves(leaf_payloads): leaves = _require_seq(leaf_payloads, "leaf_payloads") assert_no_floats(leaves) return [rfc6962_leaf_hash(leaf) for leaf in leaves] def _rfc6962_span_root(leaf_hashes, lo, hi): span = hi - lo if span == 1: return leaf_hashes[lo] k = 1 << ((span - 1).bit_length() - 1) return rfc6962_node_hash(_rfc6962_span_root(leaf_hashes, lo, lo + k), _rfc6962_span_root(leaf_hashes, lo + k, hi)) def rfc6962_merkle_root(leaf_payloads: Sequence[bytes]) -> bytes: """Compute exact RFC 6962 §2.1 Merkle Tree Hash (MTH) over N >= 0 leaves in O(N) time.""" leaf_hashes = _rfc6962_prehash_leaves(leaf_payloads) return hashlib.sha256(b"").digest() if not leaf_hashes else _rfc6962_span_root(leaf_hashes, 0, len(leaf_hashes)) def rfc6962_inclusion_proof(leaf_payloads: Sequence[bytes], leaf_index: int) -> list[str]: """Generate position-bound dyadic O(log N) RFC 6962 §2.1.1 audit path in O(N) time.""" leaf_hashes = _rfc6962_prehash_leaves(leaf_payloads) idx, n = require_strict_int(leaf_index, "leaf_index"), len(leaf_hashes) if not (0 <= idx < n): raise ValueError(f"leaf_index {idx} out of bounds for tree size {n}") siblings_rev, lo, hi, cur_idx = [], 0, n, idx while hi - lo > 1: k = 1 << ((hi - lo - 1).bit_length() - 1) if cur_idx < k: siblings_rev.append(_rfc6962_span_root(leaf_hashes, lo + k, hi).hex()) hi = lo + k else: siblings_rev.append(_rfc6962_span_root(leaf_hashes, lo, lo + k).hex()) lo += k cur_idx -= k siblings_rev.reverse() return siblings_rev def _rfc6962_root_and_all_proofs(leaf_payloads): leaf_hashes = _rfc6962_prehash_leaves(leaf_payloads) n = len(leaf_hashes) if n == 0: return (hashlib.sha256(b"").digest(), ()) proofs = [[] for _ in range(n)] def _build(lo, hi): if hi - lo == 1: return leaf_hashes[lo] k = 1 << ((hi - lo - 1).bit_length() - 1) left_h, right_h = _build(lo, lo + k), _build(lo + k, hi) r_hex, l_hex = right_h.hex(), left_h.hex() for i in range(lo, lo + k): proofs[i].append(r_hex) for i in range(lo + k, hi): proofs[i].append(l_hex) return rfc6962_node_hash(left_h, right_h) return (_build(0, n), tuple(tuple(p) for p in proofs)) def rfc6962_verify_inclusion( leaf_payload: bytes, leaf_index: int, tree_size: int, audit_path_hex: Sequence[str], expected_root: bytes ) -> bool: """Verify dyadic O(log N) RFC 6962 §2.1.1 inclusion proof bound to (leaf_index, tree_size).""" path = _require_seq(audit_path_hex, "audit_path_hex") assert_no_floats(path) leaf, root = require_strict_bytes(leaf_payload, "leaf_payload"), require_strict_bytes(expected_root, "expected_root") idx, n = require_strict_int(leaf_index, "leaf_index"), require_strict_int(tree_size, "tree_size") if n < 1 or not (0 <= idx < n) or len(root) != 32: return False splits, cur_n, cur_idx = [], n, idx while cur_n > 1: k = 1 << ((cur_n - 1).bit_length() - 1) is_right = cur_idx >= k splits.append(is_right) cur_idx = cur_idx - k if is_right else cur_idx cur_n = cur_n - k if is_right else k if len(splits) != len(path): return False sib_nodes = [] for h in path: if type(h) is not str: return False try: sib_nodes.append(bytes.fromhex(require_sha256_hex(h, "audit_sibling"))) except ValueError: return False acc = rfc6962_leaf_hash(leaf) for is_right_child, sib in zip(reversed(splits), sib_nodes): acc = rfc6962_node_hash(sib, acc) if is_right_child else rfc6962_node_hash(acc, sib) return hmac.compare_digest(acc, root) def _wots_msg_to_67_digits(message): digest = hashlib.sha256(message).digest() digits, csum = [], 0 for byte_val in digest: hi, lo = (byte_val >> 4) & 0x0F, byte_val & 0x0F digits.extend((hi, lo)) csum += (WOTS_MAX_STEP - hi) + (WOTS_MAX_STEP - lo) digits.extend(((csum >> 8) & 0x0F, (csum >> 4) & 0x0F, csum & 0x0F)) return digits def _wots_chain_step(node_32b, pub_seed_32b, leaf_idx, chain_idx, start_step, steps): cur = node_32b prefix = b"HU-WOTS-CHAIN-v1\x00" + pub_seed_32b + leaf_idx.to_bytes(4, "big") + chain_idx.to_bytes(2, "big") step_tbl, sha256 = _WOTS_STEP_BYTES, hashlib.sha256 for step_idx in range(start_step, start_step + steps): cur = sha256(prefix + step_tbl[step_idx] + cur).digest() return cur @dataclass(frozen=True) class WotsKeyTree: """4-leaf stateless WOTS+-SHA256 key tree anchored in an RFC 6962 Merkle root.""" pub_seed: bytes merkle_root: bytes secret_leaves: tuple[tuple[bytes, ...], ...] leaf_payloads: tuple[bytes, ...] _used_leaves: dict[int, bytes] = field(default_factory=dict, repr=False, compare=False) def __post_init__(self) -> None: assert_no_floats(self) if not isinstance(self._used_leaves, dict): raise TypeError("_used_leaves must be a dict") if len(require_strict_bytes(self.pub_seed, "pub_seed")) != 32 or len(require_strict_bytes(self.merkle_root, "merkle_root")) != 32: raise ProvenanceError("WotsKeyTree pub_seed and merkle_root must be 32 bytes") if len(self.secret_leaves) != WOTS_TREE_LEAVES or len(self.leaf_payloads) != WOTS_TREE_LEAVES: raise ProvenanceError("WotsKeyTree requires exact 4 secret_leaves and leaf_payloads") for leaf_sk, payload in zip(self.secret_leaves, self.leaf_payloads): if len(require_strict_bytes(payload, "leaf_payload")) != _WOTS_LEAF_LEN or len(leaf_sk) != WOTS_TOTAL_CHAINS: raise ProvenanceError("Malformed WOTS+ leaf secret chain count or payload size") if any(len(require_strict_bytes(sk, "sk_node")) != 32 for sk in leaf_sk): raise ProvenanceError("Each WOTS+ secret chain seed must be 32 bytes") if not hmac.compare_digest(rfc6962_merkle_root(self.leaf_payloads), self.merkle_root): raise ProvenanceError("WotsKeyTree merkle_root inconsistent with leaf_payloads") @property def merkle_root_hex(self) -> str: return self.merkle_root.hex() def wots_keygen_tree(master_seed: bytes, num_leaves: int = WOTS_TREE_LEAVES) -> WotsKeyTree: """Generate a deterministic 4-leaf WOTS+-SHA256 key tree with RFC 6962 Merkle root.""" seed, n_leaves = require_strict_bytes(master_seed, "master_seed"), require_strict_int(num_leaves, "num_leaves") if not seed: raise ProvenanceError("wots_keygen_tree requires non-empty master_seed bytes") if n_leaves != WOTS_TREE_LEAVES: raise ProvenanceError("HU-ETERNAL-PROVENANCE v1.0 mandates a 4-leaf WOTS+ RFC 6962 tree") sha256 = hashlib.sha256 pub_seed = sha256(b"HU-WOTS-PUBSEED-v1\x00" + seed).digest() sk_master = sha256(b"HU-WOTS-SKSEED-v1\x00" + seed).digest() secret_leaves, leaf_payloads = [], [] for leaf_idx in range(n_leaves): sk_chains, pk_chains, leaf_b = [], [], leaf_idx.to_bytes(4, "big") for chain_idx in range(WOTS_TOTAL_CHAINS): sk_i = sha256(b"HU-WOTS-SK-v1\x00" + sk_master + pub_seed + leaf_b + chain_idx.to_bytes(2, "big")).digest() sk_chains.append(sk_i) pk_chains.append(_wots_chain_step(sk_i, pub_seed, leaf_idx, chain_idx, 0, WOTS_MAX_STEP)) secret_leaves.append(tuple(sk_chains)) leaf_payloads.append(pub_seed + leaf_b + b"".join(pk_chains)) return WotsKeyTree(pub_seed, rfc6962_merkle_root(leaf_payloads), tuple(secret_leaves), tuple(leaf_payloads)) def wots_sign(tree: WotsKeyTree, message: bytes, leaf_idx: int = 0) -> dict[str, Any]: """Sign message with WOTS+-SHA256 leaf_idx, guarding against one-time leaf reuse.""" if not isinstance(tree, WotsKeyTree): raise TypeError("wots_sign requires WotsKeyTree") msg, idx = require_strict_bytes(message, "message"), require_strict_int(leaf_idx, "leaf_idx") if not (0 <= idx < WOTS_TREE_LEAVES): raise ProvenanceError(f"WOTS+ leaf_idx {idx} outside 0..{WOTS_TREE_LEAVES - 1}") msg_hash = hashlib.sha256(msg).digest() prior = tree._used_leaves.get(idx) if prior is not None and not hmac.compare_digest(prior, msg_hash): raise ProvenanceError(f"WOTS+ one-time leaf {idx} reuse forbidden on distinct message") tree._used_leaves[idx] = msg_hash digits, sk_chains = _wots_msg_to_67_digits(msg), tree.secret_leaves[idx] chains_b64 = tuple( b64url_encode(_wots_chain_step(sk_chains[c], tree.pub_seed, idx, c, 0, digits[c])) for c in range(WOTS_TOTAL_CHAINS) ) return { "merkle_root_hex": tree.merkle_root_hex, "pub_seed_b64": b64url_encode(tree.pub_seed), "leaf_idx": idx, "chains_b64": chains_b64, "auth_path_hex": tuple(rfc6962_inclusion_proof(tree.leaf_payloads, idx)), } def wots_verify(merkle_root: bytes | str | WotsKeyTree, message: bytes, signature: Mapping[str, Any]) -> bool: """Verify WOTS+-SHA256 signature chains, header binding, and 4-leaf RFC 6962 root.""" assert_no_floats(merkle_root) assert_no_floats(signature) msg = require_strict_bytes(message, "message") if not isinstance(signature, Mapping): raise TypeError("wots_verify requires Mapping signature") if not (_WOTS_SIG_REQ_KEYS <= set(signature.keys()) <= _WOTS_SIG_ALL_KEYS): return False expected_pub_seed = None if isinstance(merkle_root, WotsKeyTree): root_bytes, expected_pub_seed = merkle_root.merkle_root, merkle_root.pub_seed elif type(merkle_root) is str: try: root_bytes = bytes.fromhex(require_sha256_hex(merkle_root, "merkle_root")) except ValueError: return False elif type(merkle_root) is bytes: if len(merkle_root) != 32: return False root_bytes = merkle_root else: raise TypeError("merkle_root must be 32-byte bytes, hex str, or WotsKeyTree") sig_root = signature.get("merkle_root_hex") if sig_root is not None: if type(sig_root) is not str: return False try: if not hmac.compare_digest(bytes.fromhex(require_sha256_hex(sig_root, "sig_root")), root_bytes): return False except ValueError: return False raw_idx = signature["leaf_idx"] if type(raw_idx) is bool: require_strict_int(raw_idx, "leaf_idx") if type(raw_idx) is not int or not (0 <= raw_idx < WOTS_TREE_LEAVES): return False pub_seed_tok, chains_b64, auth_path_hex = signature["pub_seed_b64"], signature["chains_b64"], signature["auth_path_hex"] if type(pub_seed_tok) is not str or not _is_seq(chains_b64) or not _is_seq(auth_path_hex): return False if len(chains_b64) != WOTS_TOTAL_CHAINS or len(auth_path_hex) != 2: return False try: pub_seed = b64url_decode(pub_seed_tok) if len(pub_seed) != 32 or (expected_pub_seed is not None and not hmac.compare_digest(pub_seed, expected_pub_seed)): return False digits, pk_chains = _wots_msg_to_67_digits(msg), [] for c in range(WOTS_TOTAL_CHAINS): tok = chains_b64[c] if type(tok) is not str: return False node = b64url_decode(tok) if len(node) != 32: return False d_i = digits[c] pk_chains.append(_wots_chain_step(node, pub_seed, raw_idx, c, d_i, WOTS_MAX_STEP - d_i)) except ValueError: return False leaf_payload = pub_seed + raw_idx.to_bytes(4, "big") + b"".join(pk_chains) return rfc6962_verify_inclusion(leaf_payload, raw_idx, WOTS_TREE_LEAVES, auth_path_hex, root_bytes) # === Section 5: Post-Quantum FIPS 204 Algebraic Ring NTT Witness (P1c) === def brv8(x: int) -> int: """Reverse 8 bits of strict integer x in [0, 255].""" v = require_strict_int(x, "x") if not (0 <= v < NTT_N): raise ValueError("brv8 requires 0 <= x < 256") out = 0 for _ in range(8): out = (out << 1) | (v & 1) v >>= 1 return out NTT_ZETAS = tuple(pow(NTT_ZETA, brv8(i), NTT_Q) for i in range(NTT_N)) _NTT_AHAT_CACHE: dict[bytes, tuple[int, ...]] = {} _NTT_THAT_CACHE: dict[bytes, tuple[int, ...]] = {} _MAX_NTT_CACHE = 64 def center_q(x: int) -> int: """Map residue mod 8380417 into centered range [-4190208, +4190208].""" r = (x if type(x) is int else require_strict_int(x, "x")) % NTT_Q return r - NTT_Q if r > (NTT_Q // 2) else r def encode_poly_mod_q(poly: Sequence[int]) -> bytes: """Deterministically serialize 256 ring coefficients mod NTT_Q into 768 bytes.""" q, seq = NTT_Q, _require_seq(poly, "poly") if len(seq) != NTT_N: raise ValueError("encode_poly_mod_q requires 256 coefficients") return b"".join(((c if type(c) is int else require_strict_int(c, "coeff")) % q).to_bytes(3, "big") for c in seq) def ntt_256(poly: Sequence[int]) -> list[int]: """Exact 8-layer Cooley-Tukey forward NTT over Z_8380417[X]/(X^256 + 1).""" q, zetas = NTT_Q, NTT_ZETAS a = [(c if type(c) is int else require_strict_int(c, "coeff")) % q for c in _require_seq(poly, "poly")] if len(a) != NTT_N: raise ValueError("ntt_256 requires degree-256 polynomial") k, length = 0, 128 while length >= 1: for start in range(0, 256, 2 * length): k += 1 z = zetas[k] for j in range(start, start + length): t = (z * a[j + length]) % q a[j + length] = (a[j] - t) % q a[j] = (a[j] + t) % q length >>= 1 return a def intt_256(vec: Sequence[int]) -> list[int]: """Exact 8-layer Gentleman-Sande inverse NTT over Z_8380417[X]/(X^256 + 1).""" q, zetas = NTT_Q, NTT_ZETAS a = [(c if type(c) is int else require_strict_int(c, "slot")) % q for c in _require_seq(vec, "vec")] if len(a) != NTT_N: raise ValueError("intt_256 requires 256 NTT slots") k, length = 256, 1 while length < 256: for start in range(0, 256, 2 * length): k -= 1 z = (-zetas[k]) % q for j in range(start, start + length): t = a[j] a[j] = (t + a[j + length]) % q a[j + length] = (z * (t - a[j + length])) % q length <<= 1 return [(val * NTT_INV_N) % q for val in a] def _sample_uniform_32b_poly(domain, seed, low, high): span = high - low + 1 limit = ((1 << 32) // span) * span out, ctr, prefix, shifts, sha256 = [], 0, domain + seed, _U32_SHIFTS, hashlib.sha256 while len(out) < NTT_N: blk_int = int.from_bytes(sha256(prefix + ctr.to_bytes(4, "big")).digest(), "big") ctr += 1 for sh in shifts: u32 = (blk_int >> sh) & 0xFFFFFFFF if u32 < limit: out.append(low + (u32 % span)) if len(out) == NTT_N: break return out def _get_cached_ahat(a_seed): cached = _NTT_AHAT_CACHE.get(a_seed) if cached is None: if len(_NTT_AHAT_CACHE) >= _MAX_NTT_CACHE: _NTT_AHAT_CACHE.clear() cached = tuple(_sample_uniform_32b_poly(b"HU-NTT-AHAT-v1\x00", a_seed, 0, NTT_Q - 1)) _NTT_AHAT_CACHE[a_seed] = cached return cached def sample_in_ball_16(c_seed: bytes) -> list[int]: """Sample sparse polynomial in {-1, 0, +1}^256 with exact Hamming weight 16.""" seed = require_strict_bytes(c_seed, "c_seed") if len(seed) != 32: raise ValueError("sample_in_ball_16 requires exact 32-byte c_seed") signs = int.from_bytes(hashlib.sha256(b"HU-NTT-BALL-SIGNS-v1\x00" + seed).digest()[:8], "big") c, ctr, pool, pool_off = [0] * NTT_N, 0, b"", 0 for i in range(NTT_N - NTT_TAU, NTT_N): span = i + 1 limit = ((1 << 32) // span) * span while True: if pool_off >= len(pool): pool = hashlib.sha256(b"HU-NTT-BALL-IDX-v1\x00" + seed + ctr.to_bytes(4, "big")).digest() ctr += 1 pool_off = 0 u32 = int.from_bytes(pool[pool_off : pool_off + 4], "big") pool_off += 4 if u32 < limit: j = u32 % span break c[i] = c[j] c[j] = -1 if ((signs >> (i - (NTT_N - NTT_TAU))) & 1) else 1 return c def _ntt_pk_digest(a_seed, t_poly): return hashlib.sha256(b"HU-NTT-PK-v1\x00" + a_seed + encode_poly_mod_q(t_poly)).digest() @dataclass(frozen=True) class NttSecretKey: """Private Ring-NTT signing key with precomputed spectral vectors.""" a_seed: bytes t_poly: tuple[int, ...] s1: tuple[int, ...] s2: tuple[int, ...] sk_seed: bytes a_hat: tuple[int, ...] = field(default=(), init=False, repr=False, compare=False) s1_hat: tuple[int, ...] = field(default=(), init=False, repr=False, compare=False) s2_hat: tuple[int, ...] = field(default=(), init=False, repr=False, compare=False) def __post_init__(self) -> None: assert_no_floats(self) if len(require_strict_bytes(self.a_seed, "a_seed")) != 32 or len(require_strict_bytes(self.sk_seed, "sk_seed")) != 32: raise ProvenanceError("NttSecretKey seeds must be exact 32 bytes") if len(self.t_poly) != NTT_N or len(self.s1) != NTT_N or len(self.s2) != NTT_N: raise ProvenanceError("NttSecretKey polynomials must have exact degree 256") if any(not (0 <= require_strict_int(tc, "t_poly") < NTT_Q) for tc in self.t_poly): raise ProvenanceError("NttSecretKey.t_poly coefficients outside [0, NTT_Q - 1]") for seq_name in ("s1", "s2"): if any(abs(require_strict_int(sc, seq_name)) > NTT_ETA for sc in getattr(self, seq_name)): raise ProvenanceError(f"NttSecretKey.{seq_name} exceeds short-secret bound NTT_ETA={NTT_ETA}") ah, s1h, s2h = _get_cached_ahat(self.a_seed), tuple(ntt_256(self.s1)), tuple(ntt_256(self.s2)) if tuple(self.t_poly) != tuple(intt_256([(ah[i] * s1h[i] + s2h[i]) % NTT_Q for i in range(NTT_N)])): raise ProvenanceError("NttSecretKey.t_poly inconsistent with a_hat * s1_hat + s2_hat") object.__setattr__(self, "a_hat", ah) object.__setattr__(self, "s1_hat", s1h) object.__setattr__(self, "s2_hat", s2h) def ntt_lattice_keygen(seed: bytes) -> tuple[tuple[bytes, tuple[int, ...]], NttSecretKey]: """Generate Ring-NTT keypair ((a_seed, t_poly), secret_key) over Z_8380417[X]/(X^256+1).""" raw_seed = require_strict_bytes(seed, "seed") if not raw_seed: raise ProvenanceError("ntt_lattice_keygen requires non-empty seed bytes") a_seed = hashlib.sha256(b"HU-NTT-ASEED-v1\x00" + raw_seed).digest() sk_seed = hashlib.sha256(b"HU-NTT-SKSEED-v1\x00" + raw_seed).digest() a_hat = _get_cached_ahat(a_seed) s1 = tuple(_sample_uniform_32b_poly(b"HU-NTT-S1-v1\x00", sk_seed, -NTT_ETA, NTT_ETA)) s2 = tuple(_sample_uniform_32b_poly(b"HU-NTT-S2-v1\x00", sk_seed, -NTT_ETA, NTT_ETA)) s1_hat, s2_hat = tuple(ntt_256(s1)), tuple(ntt_256(s2)) t_hat = tuple((a_hat[i] * s1_hat[i] + s2_hat[i]) % NTT_Q for i in range(NTT_N)) t_poly = tuple(intt_256(t_hat)) if len(_NTT_THAT_CACHE) >= _MAX_NTT_CACHE: _NTT_THAT_CACHE.clear() _NTT_THAT_CACHE[_ntt_pk_digest(a_seed, t_poly)] = t_hat return ((a_seed, t_poly), NttSecretKey(a_seed, t_poly, s1, s2, sk_seed)) def ntt_lattice_sign(secret_key: NttSecretKey, message: bytes) -> tuple[str, list[int], list[int]]: """Sign message via Fiat-Shamir with Aborts, returning compact (c_seed_hex, z1, z2).""" if not isinstance(secret_key, NttSecretKey): raise TypeError("ntt_lattice_sign requires NttSecretKey") assert_no_floats(secret_key) msg = require_strict_bytes(message, "message") a_hat, s1_hat, s2_hat = secret_key.a_hat, secret_key.s1_hat, secret_key.s2_hat pk_digest = _ntt_pk_digest(secret_key.a_seed, secret_key.t_poly) msg_digest = hashlib.sha256(msg).digest() for nonce in range(512): mask_seed = hashlib.sha256( b"HU-NTT-MASK-v1\x00" + secret_key.sk_seed + pk_digest + msg_digest + nonce.to_bytes(4, "big") ).digest() y1 = _sample_uniform_32b_poly(b"HU-NTT-Y1-v1\x00", mask_seed, -NTT_GAMMA1, NTT_GAMMA1) y2 = _sample_uniform_32b_poly(b"HU-NTT-Y2-v1\x00", mask_seed, -NTT_GAMMA1, NTT_GAMMA1) y1_hat, y2_hat = ntt_256(y1), ntt_256(y2) w = intt_256([(a_hat[i] * y1_hat[i] + y2_hat[i]) % NTT_Q for i in range(NTT_N)]) c_seed = hashlib.sha256(b"HU-NTT-FS-v1\x00" + pk_digest + encode_poly_mod_q(w) + msg_digest).digest() c_hat = ntt_256(sample_in_ball_16(c_seed)) cs1 = intt_256([(c_hat[i] * s1_hat[i]) % NTT_Q for i in range(NTT_N)]) z1 = [center_q(y1[i] + cs1[i]) for i in range(NTT_N)] if any(abs(x) > NTT_NORM_BOUND for x in z1): continue cs2 = intt_256([(c_hat[i] * s2_hat[i]) % NTT_Q for i in range(NTT_N)]) z2 = [center_q(y2[i] + cs2[i]) for i in range(NTT_N)] if all(abs(x) <= NTT_NORM_BOUND for x in z2): return (c_seed.hex(), z1, z2) raise ProvenanceError("NTT Fiat-Shamir rejection bound exceeded") def ntt_lattice_verify( public_key: tuple[bytes, Sequence[int]] | NttSecretKey, message: bytes, signature: tuple[str, Sequence[int], Sequence[int]] | Mapping[str, Any], ) -> bool: """Verify compact Ring-NTT signature (c_seed_hex, z1, z2) via exact w_prime recovery.""" assert_no_floats(public_key) assert_no_floats(signature) msg = require_strict_bytes(message, "message") if type(public_key) is bool or type(signature) is bool: raise TypeError("ntt_lattice_verify forbids bool arguments") if isinstance(public_key, NttSecretKey): a_seed, t_poly = public_key.a_seed, public_key.t_poly elif type(public_key) is tuple and len(public_key) == 2: a_seed, t_poly = public_key else: return False if type(a_seed) is not bytes or not _is_seq(t_poly): return False t_vals = [c if type(c) is int else require_strict_int(c, "t_coeff") for c in t_poly] if len(a_seed) != 32 or len(t_vals) != NTT_N or any(not (0 <= tc < NTT_Q) for tc in t_vals): return False if type(signature) is tuple: if len(signature) != 3: return False c_seed_hex, z1, z2 = signature elif isinstance(signature, Mapping): if set(signature.keys()) != {"c_seed_hex", "z1", "z2"}: return False c_seed_hex, z1, z2 = signature["c_seed_hex"], signature["z1"], signature["z2"] else: return False if type(c_seed_hex) is not str or not _is_seq(z1) or not _is_seq(z2): return False z1_vals = [c if type(c) is int else require_strict_int(c, "z1_coeff") for c in z1] z2_vals = [c if type(c) is int else require_strict_int(c, "z2_coeff") for c in z2] if len(z1_vals) != NTT_N or len(z2_vals) != NTT_N: return False for vec in (z1_vals, z2_vals): if any(val != center_q(val) or abs(val) > NTT_NORM_BOUND for val in vec): return False try: c_seed = bytes.fromhex(require_sha256_hex(c_seed_hex, "c_seed_hex")) except ValueError: return False pk_digest = _ntt_pk_digest(a_seed, t_vals) a_hat = _get_cached_ahat(a_seed) t_hat = _NTT_THAT_CACHE.get(pk_digest) if t_hat is None: t_hat = tuple(ntt_256(t_vals)) if len(_NTT_THAT_CACHE) >= _MAX_NTT_CACHE: _NTT_THAT_CACHE.clear() _NTT_THAT_CACHE[pk_digest] = t_hat c_hat = ntt_256(sample_in_ball_16(c_seed)) z1_hat, z2_hat = ntt_256(z1_vals), ntt_256(z2_vals) w_prime = intt_256([(a_hat[i] * z1_hat[i] + z2_hat[i] - c_hat[i] * t_hat[i]) % NTT_Q for i in range(NTT_N)]) expected_seed = hashlib.sha256( b"HU-NTT-FS-v1\x00" + pk_digest + encode_poly_mod_q(w_prime) + hashlib.sha256(msg).digest() ).digest() return hmac.compare_digest(c_seed, expected_seed) # === Section 6: Symbiotic Co-Creation, Anti-Impersonation, C2PA-MCP & Governance === _FORBIDDEN_BIOMETRIC_STEMS = ( "voiceprint", "vocalprint", "speakerbiometric", "speakerembedding", "voiceembedding", "faciallandmark", "facelandmark", "faceembedding", "vocalbiometric", "voiceclone", "biometrictemplate", "biometricembedding", ) _RE_INVISIBLE_CHARS = re.compile(r"[\u00ad\u200b-\u200f\u202a-\u202e\u2060-\u2064\ufeff]") _RE_NON_ALNUM = re.compile(r"[^a-z0-9]+") _RE_IMPERSONATION_PROMPT = re.compile( r"(? dict[str, Any]: """Fail-closed scanner blocking voice-cloning prompts, biometrics, and Content-ID abuse.""" assert_no_floats(text_or_meta) detected_ai = require_strict_bool(has_ai_audio_synthesis, "has_ai_audio_synthesis") detected_cid = require_strict_bool(content_id_fingerprinting_claimed, "content_id_fingerprinting_claimed") stack = [text_or_meta] while stack: node = stack.pop() if type(node) is str: match = _RE_IMPERSONATION_PROMPT.search(_RE_INVISIBLE_CHARS.sub("", node)) if match is not None: raise ImpersonationOrBiometricError(f"Blocked living-artist voice impersonation prompt: {match.group(0)!r}") elif is_dataclass(node) and not isinstance(node, type): fnames = _DC_FIELDS_CACHE.get(type(node)) or tuple(fld.name for fld in fields(node)) for fname in fnames: fval = getattr(node, fname) if fname == "content_id_fingerprinting_claimed": detected_cid = require_strict_bool(fval, fname) or detected_cid elif fname in ("stage_type", "stage_kind") and type(fval) is str: detected_ai = detected_ai or _is_ai_token(fval, 1 == 1) elif fname == "actor_kind" and type(fval) is str: detected_ai = detected_ai or _is_ai_token(fval, 1 == 0) stack.append(fval) elif isinstance(node, Mapping): for k, v in node.items(): key_compact = _RE_NON_ALNUM.sub("", _RE_INVISIBLE_CHARS.sub("", str(k)).lower()) if any(stem in key_compact for stem in _FORBIDDEN_BIOMETRIC_STEMS): raise ImpersonationOrBiometricError(f"Forbidden biometric key: {k!r}") if key_compact == "contentidfingerprintingclaimed": detected_cid = require_strict_bool(v, str(k)) or detected_cid elif key_compact in ("hasaisynthesis", "hasaiaudiosynthesis", "isaisynthesis", "aiaudiosynthesis"): detected_ai = require_strict_bool(v, str(k)) or detected_ai elif key_compact in ("stagetype", "stagekind") and type(v) is str: detected_ai = detected_ai or _is_ai_token(v, 1 == 1) elif key_compact in ("actorkind", "actortype") and type(v) is str: detected_ai = detected_ai or _is_ai_token(v, 1 == 0) stack.extend((k, v)) elif isinstance(node, (set, frozenset)) or _is_seq(node): stack.extend(node) elif isinstance(getattr(node, "__dict__", None), Mapping): stack.append(node.__dict__) if detected_cid and detected_ai: raise ContentIdAbuseError("Content-ID fingerprinting is forbidden on generative AI audio synthesis") return { "clean": not (detected_cid and detected_ai), "ai_synthesis_present": detected_ai, "content_id_claimed": detected_cid, } def blind_human_rough_draft(raw_draft: bytes | str, salt: bytes) -> tuple[str, int]: """Commit an unpublished human rough draft with salted SHA-256 at c_levels == 1.""" draft_bytes = raw_draft.encode("utf-8") if type(raw_draft) is str else require_strict_bytes(raw_draft, "raw_draft") raw_salt = require_strict_bytes(salt, "salt") if not raw_salt: raise ProvenanceError("Draft blinding salt must be non-empty bytes", PEARL_SILENT_SANCTUARY) return (hashlib.sha256(b"HU-DRAFT-BLIND-v1\x00" + raw_salt + draft_bytes).hexdigest(), 1) def _fraction_to_jcs(q): fq = require_strict_fraction(q, "fraction") return {"den": fq.denominator, "num": fq.numerator} @dataclass(frozen=True) class CreativeContributionStage: """Single auditable human or AI contribution stage in a symbiotic work (P2, P5).""" stage_id: str stage_type: str actor_kind: str actor_name: str weight_q: Fraction description: str artifact_sha256: str c_levels: int = 0 is_blinded_rough_draft: bool = False commercial_license_proof_sha256: str | None = None extra_metadata: dict[str, Any] = field(default_factory=dict) def __post_init__(self) -> None: assert_no_floats(self) _req_strs(self, "stage_id", "stage_type", "actor_kind", "actor_name", "description", "artifact_sha256") if self.commercial_license_proof_sha256 is not None: require_strict_str(self.commercial_license_proof_sha256, "commercial_license_proof_sha256") object.__setattr__(self, "weight_q", require_strict_fraction(self.weight_q, "weight_q")) require_strict_int(self.c_levels, "c_levels") require_strict_bool(self.is_blinded_rough_draft, "is_blinded_rough_draft") if not isinstance(self.extra_metadata, Mapping): raise TypeError("extra_metadata must be a Mapping") object.__setattr__(self, "extra_metadata", {require_strict_str(k, "meta_key"): v for k, v in self.extra_metadata.items()}) def to_jcs_dict(self) -> dict[str, Any]: return { "actor_kind": self.actor_kind, "actor_name": self.actor_name, "artifact_sha256": self.artifact_sha256, "c_levels": self.c_levels, "commercial_license_proof_sha256": self.commercial_license_proof_sha256, "description": self.description, "extra_metadata": self.extra_metadata, "is_blinded_rough_draft": self.is_blinded_rough_draft, "stage_id": self.stage_id, "stage_type": self.stage_type, "weight_q": _fraction_to_jcs(self.weight_q), } @dataclass(frozen=True) class C2paMcpProvenanceHop: """Single RFC 6962 C2PA-MCP / A2A provenance hop with EU AI Act Art. 50 disclosure.""" hop_index: int hop_id: str protocol: str tool_or_agent_id: str summary: str ingredient_digest_sha256: str output_digest_sha256: str parent_hop_leaf_sha256: str | None eu_ai_act_art50_disclosed: bool def __post_init__(self) -> None: assert_no_floats(self) require_strict_int(self.hop_index, "hop_index") _req_strs(self, "hop_id", "protocol", "tool_or_agent_id", "summary", "ingredient_digest_sha256", "output_digest_sha256") if self.parent_hop_leaf_sha256 is not None: require_strict_str(self.parent_hop_leaf_sha256, "parent_hop_leaf_sha256") require_strict_bool(self.eu_ai_act_art50_disclosed, "eu_ai_act_art50_disclosed") def to_jcs_dict(self) -> dict[str, Any]: return { "eu_ai_act_art50_disclosed": self.eu_ai_act_art50_disclosed, "hop_id": self.hop_id, "hop_index": self.hop_index, "ingredient_digest_sha256": self.ingredient_digest_sha256, "output_digest_sha256": self.output_digest_sha256, "parent_hop_leaf_sha256": self.parent_hop_leaf_sha256, "protocol": self.protocol, "summary": self.summary, "tool_or_agent_id": self.tool_or_agent_id, } def leaf_bytes(self) -> bytes: return jcs_canonical_bytes(self.to_jcs_dict()) @dataclass(frozen=True) class TripleSovereignPublicKey: """Public verification anchor bundle (ES256 + WOTS+-SHA256 + FIPS 204 Ring NTT).""" es256_pub_xy: tuple[int, int] wots_merkle_root_hex: str ntt_pub_key: tuple[bytes, tuple[int, ...]] def __post_init__(self) -> None: assert_no_floats(self) if type(self.es256_pub_xy) is not tuple or len(self.es256_pub_xy) != 2: raise TypeError("es256_pub_xy must be a 2-tuple of strict ints") if _p256_validate_pubkey(self.es256_pub_xy) is None: raise ProvenanceError("Invalid or off-curve P-256 public key in TripleSovereignPublicKey") require_sha256_hex(self.wots_merkle_root_hex, "wots_merkle_root_hex") if type(self.ntt_pub_key) is not tuple or len(self.ntt_pub_key) != 2: raise TypeError("ntt_pub_key must be (a_seed, t_poly)") if len(require_strict_bytes(self.ntt_pub_key[0], "a_seed")) != 32 or len(self.ntt_pub_key[1]) != NTT_N: raise ProvenanceError("ntt_pub_key requires 32-byte a_seed and 256-coeff t_poly") if any(not (0 <= (c if type(c) is int else require_strict_int(c, "t_coeff")) < NTT_Q) for c in self.ntt_pub_key[1]): raise ProvenanceError("ntt_pub_key t_poly coefficients outside [0, NTT_Q - 1]") @dataclass(frozen=True) class TripleSovereignKeyring: """Deterministic Triple Sovereign Seal signing keyring.""" es256_priv_d: int es256_pub_xy: tuple[int, int] wots_tree: WotsKeyTree ntt_pub_key: tuple[bytes, tuple[int, ...]] ntt_sec_key: NttSecretKey def __post_init__(self) -> None: assert_no_floats(self) d = require_strict_int(self.es256_priv_d, "es256_priv_d") if not (1 <= d < N): raise ProvenanceError("es256_priv_d out of P-256 scalar bounds") if not isinstance(self.wots_tree, WotsKeyTree) or not isinstance(self.ntt_sec_key, NttSecretKey): raise TypeError("Invalid WotsKeyTree or NttSecretKey in TripleSovereignKeyring") _ = TripleSovereignPublicKey(self.es256_pub_xy, self.wots_tree.merkle_root_hex, self.ntt_pub_key) if _p256_to_affine(_p256_scalar_mul_g(d)) != self.es256_pub_xy: raise ProvenanceError("Keyring es256_pub_xy does not match [es256_priv_d]G") if (self.ntt_pub_key[0], tuple(self.ntt_pub_key[1])) != (self.ntt_sec_key.a_seed, self.ntt_sec_key.t_poly): raise ProvenanceError("Keyring ntt_pub_key does not match ntt_sec_key") @classmethod def from_master_seed(cls, master_seed: bytes) -> TripleSovereignKeyring: seed = require_strict_bytes(master_seed, "master_seed") if not seed: raise ProvenanceError("master_seed must be non-empty bytes") es_d, es_pub = p256_derive_keypair(hashlib.sha256(b"ES256\x00" + seed).digest()) w_tree = wots_keygen_tree(hashlib.sha256(b"WOTS\x00" + seed).digest()) n_pub, n_sec = ntt_lattice_keygen(hashlib.sha256(b"NTT\x00" + seed).digest()) return cls(es_d, es_pub, w_tree, n_pub, n_sec) def public_key(self) -> TripleSovereignPublicKey: return TripleSovereignPublicKey(self.es256_pub_xy, self.wots_tree.merkle_root_hex, self.ntt_pub_key) @dataclass(frozen=True) class TripleSovereignSeal: """Combined classical ES256 + stateless WOTS+-SHA256 + compact Ring-NTT seal.""" es256_pubkey_b64: str es256_sig_b64: str wots_merkle_root_hex: str wots_sig: dict[str, Any] ntt_pub_key: tuple[bytes, tuple[int, ...]] ntt_sig: tuple[str, list[int], list[int]] def __post_init__(self) -> None: assert_no_floats(self) _req_strs(self, "es256_pubkey_b64", "es256_sig_b64", "wots_merkle_root_hex") if not isinstance(self.wots_sig, Mapping): raise TypeError("wots_sig must be a Mapping") if type(self.ntt_pub_key) is not tuple or len(self.ntt_pub_key) != 2: raise TypeError("ntt_pub_key must be (a_seed, t_poly)") require_strict_bytes(self.ntt_pub_key[0], "ntt_pub_key.a_seed") object.__setattr__( self, "ntt_pub_key", (self.ntt_pub_key[0], tuple(c if type(c) is int else require_strict_int(c, "t_coeff") for c in _require_seq(self.ntt_pub_key[1], "t_poly"))), ) if type(self.ntt_sig) is not tuple or len(self.ntt_sig) != 3: raise TypeError("ntt_sig must be (c_seed_hex, z1, z2)") require_strict_str(self.ntt_sig[0], "ntt_sig.c_seed_hex") for z_vec in (self.ntt_sig[1], self.ntt_sig[2]): for c in _require_seq(z_vec, "ntt_sig.z"): if type(c) is not int: require_strict_int(c, "ntt_sig.z") def to_jcs_dict(self) -> dict[str, Any]: c_hex, z1, z2 = self.ntt_sig ws = self.wots_sig return { "es256_pubkey_b64": self.es256_pubkey_b64, "es256_sig_b64": self.es256_sig_b64, "ntt_pub_key": {"a_seed_b64": b64url_encode(self.ntt_pub_key[0]), "t_poly": list(self.ntt_pub_key[1])}, "ntt_sig": {"c_seed_hex": c_hex, "z1": list(z1), "z2": list(z2)}, "wots_merkle_root_hex": self.wots_merkle_root_hex, "wots_sig": { "auth_path_hex": list(ws.get("auth_path_hex", ())), "chains_b64": list(ws.get("chains_b64", ())), "leaf_idx": ws.get("leaf_idx", 0), "merkle_root_hex": ws.get("merkle_root_hex", ""), "pub_seed_b64": ws.get("pub_seed_b64", ""), }, } @dataclass(frozen=True) class EternalProvenanceEnvelope: """Immutable C2PA-MCP provenance envelope sealed with the Triple Sovereign Seal.""" envelope_id: str specimen_number: str title: str artist: str human_author: str upc: str true_peak_dbtp_q: Fraction highpass_hz: int human_authorship_q: Fraction content_id_fingerprinting_claimed: bool eu_ai_act_art50_disclosed: bool stages: tuple[CreativeContributionStage, ...] hops: tuple[C2paMcpProvenanceHop, ...] c2pa_merkle_root_hex: str hop_inclusion_proofs: tuple[tuple[str, ...], ...] lineage_envelope_ids: tuple[str, ...] es256_pubkey_b64: str wots_merkle_root_hex: str ntt_pk_sha256: str manifest_sha256: str triple_seal: TripleSovereignSeal metadata: dict[str, Any] = field(default_factory=dict) def __post_init__(self) -> None: assert_no_floats(self) _req_strs( self, "envelope_id", "specimen_number", "title", "artist", "human_author", "upc", "c2pa_merkle_root_hex", "es256_pubkey_b64", "wots_merkle_root_hex", "ntt_pk_sha256", "manifest_sha256", ) object.__setattr__(self, "true_peak_dbtp_q", require_strict_fraction(self.true_peak_dbtp_q, "true_peak_dbtp_q")) require_strict_int(self.highpass_hz, "highpass_hz") object.__setattr__(self, "human_authorship_q", require_strict_fraction(self.human_authorship_q, "human_authorship_q")) require_strict_bool(self.content_id_fingerprinting_claimed, "content_id_fingerprinting_claimed") require_strict_bool(self.eu_ai_act_art50_disclosed, "eu_ai_act_art50_disclosed") if not isinstance(self.triple_seal, TripleSovereignSeal) or not isinstance(self.metadata, Mapping): raise TypeError("Invalid triple_seal or metadata type") object.__setattr__(self, "metadata", {require_strict_str(k, "meta_key"): v for k, v in self.metadata.items()}) st_seq, hp_seq = _require_seq(self.stages, "stages"), _require_seq(self.hops, "hops") if any(not isinstance(s, CreativeContributionStage) for s in st_seq) or any(not isinstance(h, C2paMcpProvenanceHop) for h in hp_seq): raise TypeError("stages and hops must contain typed stage/hop instances") object.__setattr__(self, "stages", tuple(st_seq)) object.__setattr__(self, "hops", tuple(hp_seq)) object.__setattr__(self, "lineage_envelope_ids", tuple(require_strict_str(x, "lineage_id") for x in _require_seq(self.lineage_envelope_ids, "lineage_ids"))) object.__setattr__( self, "hop_inclusion_proofs", tuple(tuple(require_strict_str(p, "proof_sib") for p in _require_seq(path, "proof_path")) for path in _require_seq(self.hop_inclusion_proofs, "proofs")), ) def manifest_jcs_dict(self) -> dict[str, Any]: return { "artist": self.artist, "c2pa_merkle_root_hex": self.c2pa_merkle_root_hex, "content_id_fingerprinting_claimed": self.content_id_fingerprinting_claimed, "envelope_id": self.envelope_id, "es256_pubkey_b64": self.es256_pubkey_b64, "eu_ai_act_art50_disclosed": self.eu_ai_act_art50_disclosed, "highpass_hz": self.highpass_hz, "hop_inclusion_proofs": [list(p) for p in self.hop_inclusion_proofs], "hops": [h.to_jcs_dict() for h in self.hops], "human_author": self.human_author, "human_authorship_q": _fraction_to_jcs(self.human_authorship_q), "lineage_envelope_ids": list(self.lineage_envelope_ids), "metadata": self.metadata, "ntt_pk_sha256": self.ntt_pk_sha256, "protocol": PROTOCOL_VERSION, "sacred_equation": SACRED_EQUATION, "specimen_number": self.specimen_number, "stages": [s.to_jcs_dict() for s in self.stages], "title": self.title, "true_peak_dbtp_q": _fraction_to_jcs(self.true_peak_dbtp_q), "upc": self.upc, "wots_merkle_root_hex": self.wots_merkle_root_hex, } def to_jcs_bytes(self) -> bytes: return jcs_canonical_bytes( {"manifest": self.manifest_jcs_dict(), "manifest_sha256": self.manifest_sha256, "triple_seal": self.triple_seal.to_jcs_dict()} ) def _validate_envelope_policies(env, hop_leaves=None): if not env.envelope_id.strip(): raise C2paIntegrityOrDisclosureError("envelope_id must be a non-empty str") for attr in ("specimen_number", "title", "artist", "human_author"): if not getattr(env, attr).strip(): raise AuthorshipSlopOrLicenseError(f"{attr} must be non-empty") if not env.upc.isdigit() or len(env.upc) not in (8, 12, 13, 14): raise AuthorshipSlopOrLicenseError("UPC/EAN must be an 8-, 12-, 13-, or 14-digit numeric string") if env.highpass_hz <= 0 or env.true_peak_dbtp_q > Fraction(-1, 1): raise AuthorshipSlopOrLicenseError("Require highpass_hz > 0 and true_peak_dbtp_q <= -1 dBTP") if not (Fraction(0, 1) < env.human_authorship_q <= Fraction(1, 1)) or not env.stages: raise AuthorshipSlopOrLicenseError("Pure-0 human slop cannot claim copyright; require 0 < human_authorship_q <= 1") lineage_set = set() for lid in env.lineage_envelope_ids: require_strict_str(lid, "lineage_id") if not lid.strip() or lid == env.envelope_id or lid in lineage_set: raise C2paIntegrityOrDisclosureError(f"Invalid or cyclic lineage_envelope_id: {lid!r}") lineage_set.add(lid) total_w, human_w, has_ai_stage = Fraction(0, 1), Fraction(0, 1), 1 == 0 stage_ids, stage_artifacts = set(), set() for st in env.stages: if not st.stage_id.strip() or not st.actor_name.strip() or not st.description.strip(): raise AuthorshipSlopOrLicenseError("Stage stage_id, actor_name, and description must be non-empty") if st.stage_id in stage_ids or st.stage_id == env.envelope_id or st.stage_id in lineage_set: raise AuthorshipSlopOrLicenseError(f"Duplicate or colliding stage_id: {st.stage_id!r}") stage_ids.add(st.stage_id) if st.stage_type not in VALID_STAGE_TYPES or st.actor_kind not in ("HUMAN", "AI"): raise AuthorshipSlopOrLicenseError(f"Invalid stage_type or actor_kind on {st.stage_id!r}") if st.stage_type == AI_INSTRUMENTAL_SYNTHESIS and st.actor_kind != "AI": raise AuthorshipSlopOrLicenseError("AI_INSTRUMENTAL_SYNTHESIS stage requires actor_kind == 'AI'") if st.stage_type in (HUMAN_LYRIC_GENESIS, HUMAN_SURGICAL_STEM_EDIT) and st.actor_kind != "HUMAN": raise AuthorshipSlopOrLicenseError(f"{st.stage_type} requires actor_kind == 'HUMAN'") if st.weight_q <= Fraction(0, 1): raise AuthorshipSlopOrLicenseError("Stage weight_q must be strictly positive") try: require_sha256_hex(st.artifact_sha256, "stage.artifact_sha256") except ValueError as exc: raise C2paIntegrityOrDisclosureError(str(exc)) from exc if st.c_levels not in (0, 1) or st.is_blinded_rough_draft != (st.c_levels == 1) or (st.is_blinded_rough_draft and st.actor_kind != "HUMAN"): raise C2paIntegrityOrDisclosureError("Blinded rough drafts require HUMAN actor and salted SHA-256 at c_levels == 1") if st.commercial_license_proof_sha256 is not None: try: require_sha256_hex(st.commercial_license_proof_sha256, "commercial_license_proof_sha256") except ValueError as exc: raise AuthorshipSlopOrLicenseError(str(exc)) from exc if st.actor_kind == "AI": has_ai_stage = st.actor_kind == "AI" if st.commercial_license_proof_sha256 is None: raise AuthorshipSlopOrLicenseError(f"AI stage {st.stage_id!r} missing commercial_license_proof_sha256") else: human_w += st.weight_q total_w += st.weight_q stage_artifacts.add(st.artifact_sha256) if total_w != Fraction(1, 1) or human_w != env.human_authorship_q: raise AuthorshipSlopOrLicenseError("Stage weights must sum to 1 and match human_authorship_q") scan_impersonation_and_biometric_hazards( [env.envelope_id, env.specimen_number, env.title, env.artist, env.human_author, env.upc, env.lineage_envelope_ids, env.stages, env.hops, env.metadata], has_ai_audio_synthesis=has_ai_stage, content_id_fingerprinting_claimed=env.content_id_fingerprinting_claimed, ) if not env.eu_ai_act_art50_disclosed or not env.hops: raise C2paIntegrityOrDisclosureError("Envelope requires eu_ai_act_art50_disclosed=True and >= 1 hop") known_digests, referenced_digests, hop_ids, prev_leaf_hex = set(stage_artifacts), set(), set(), None for idx, hop in enumerate(env.hops): if hop.hop_index != idx or not hop.hop_id.strip() or not hop.tool_or_agent_id.strip() or not hop.summary.strip(): raise C2paIntegrityOrDisclosureError(f"Hop {idx} index or required text fields invalid") if hop.hop_id in hop_ids or hop.hop_id == env.envelope_id or hop.hop_id in stage_ids or hop.hop_id in lineage_set: raise C2paIntegrityOrDisclosureError(f"Invalid or colliding hop_id: {hop.hop_id!r}") hop_ids.add(hop.hop_id) if hop.protocol not in VALID_HOP_PROTOCOLS and not _HOP_PROTO_RE.match(hop.protocol): raise C2paIntegrityOrDisclosureError(f"Unsupported or non-canonical hop protocol: {hop.protocol!r}") if not hop.eu_ai_act_art50_disclosed: raise C2paIntegrityOrDisclosureError(f"Hop {idx} missing mandatory EU AI Act Art. 50 disclosure") try: require_sha256_hex(hop.ingredient_digest_sha256, "hop.ingredient_digest_sha256") require_sha256_hex(hop.output_digest_sha256, "hop.output_digest_sha256") except ValueError as exc: raise C2paIntegrityOrDisclosureError(str(exc)) from exc if (prev_leaf_hex is None and hop.parent_hop_leaf_sha256 is not None) or ( prev_leaf_hex is not None and not _ct_str_eq(hop.parent_hop_leaf_sha256, prev_leaf_hex) ): raise C2paIntegrityOrDisclosureError(f"Hop {idx} parent_hop_leaf_sha256 mismatch") if idx == 0 and hop.ingredient_digest_sha256 not in stage_artifacts: raise C2paIntegrityOrDisclosureError("Genesis hop ingredient not anchored in stages") if idx > 0 and not _ct_str_eq(hop.ingredient_digest_sha256, env.hops[idx - 1].output_digest_sha256) and hop.ingredient_digest_sha256 not in known_digests: raise C2paIntegrityOrDisclosureError(f"Hop {idx} broke upstream ingredient continuity") referenced_digests.update((hop.ingredient_digest_sha256, hop.output_digest_sha256)) known_digests.add(hop.output_digest_sha256) leaf_b = hop_leaves[idx] if hop_leaves is not None else hop.leaf_bytes() prev_leaf_hex = rfc6962_leaf_hash(leaf_b).hex() if not stage_artifacts.issubset(referenced_digests): raise C2paIntegrityOrDisclosureError("Every stage artifact_sha256 must be anchored in the C2PA-MCP Merkle-DAG") def seal_eternal_provenance_envelope( *, specimen_number: str, title: str, artist: str, human_author: str, upc: str, true_peak_dbtp_q: Fraction, highpass_hz: int, human_authorship_q: Fraction, content_id_fingerprinting_claimed: bool, eu_ai_act_art50_disclosed: bool, stages: Sequence[CreativeContributionStage], hops: Sequence[C2paMcpProvenanceHop], keyring: TripleSovereignKeyring, wots_leaf_idx: int = 0, lineage_envelope_ids: Sequence[str] = (), envelope_id: str | None = None, metadata: Mapping[str, Any] | None = None, ) -> EternalProvenanceEnvelope: """Scan pre-masking hazards, scrub Rule 14 PII, build RFC 6962 proofs, and Triple-Seal.""" if not isinstance(keyring, TripleSovereignKeyring): raise TypeError("keyring must be TripleSovereignKeyring") require_strict_int(wots_leaf_idx, "wots_leaf_idx") require_strict_int(highpass_hz, "highpass_hz") peak_q = require_strict_fraction(true_peak_dbtp_q, "true_peak_dbtp_q") auth_q = require_strict_fraction(human_authorship_q, "human_authorship_q") cid_flag = require_strict_bool(content_id_fingerprinting_claimed, "content_id_fingerprinting_claimed") art50_flag = require_strict_bool(eu_ai_act_art50_disclosed, "eu_ai_act_art50_disclosed") st_seq, hp_seq, lin_seq = _require_seq(stages, "stages"), _require_seq(hops, "hops"), _require_seq(lineage_envelope_ids, "lineage_envelope_ids") if envelope_id is not None: require_strict_str(envelope_id, "envelope_id") if metadata is not None and not isinstance(metadata, Mapping): raise TypeError("metadata must be Mapping or None") raw_meta = dict(metadata or {}) assert_no_floats([st_seq, hp_seq, raw_meta, lin_seq]) scan_impersonation_and_biometric_hazards( [envelope_id, specimen_number, title, artist, human_author, upc, lin_seq, st_seq, hp_seq, raw_meta], content_id_fingerprinting_claimed=cid_flag, ) clean_stages = tuple( replace( st, stage_id=rule14_mask_provenance_text(st.stage_id), actor_name=rule14_mask_provenance_text(st.actor_name), description=rule14_mask_provenance_text(st.description), extra_metadata=_mask_structure_deep(st.extra_metadata), ) for st in st_seq ) clean_hops, hop_leaves, prev_leaf_hex = [], [], None for idx, hop in enumerate(hp_seq): rebuilt = C2paMcpProvenanceHop( hop_index=idx, hop_id=rule14_mask_provenance_text(hop.hop_id), protocol=rule14_mask_provenance_text(hop.protocol), tool_or_agent_id=rule14_mask_provenance_text(hop.tool_or_agent_id), summary=rule14_mask_provenance_text(hop.summary), ingredient_digest_sha256=hop.ingredient_digest_sha256, output_digest_sha256=hop.output_digest_sha256, parent_hop_leaf_sha256=prev_leaf_hex, eu_ai_act_art50_disclosed=hop.eu_ai_act_art50_disclosed, ) leaf_b = rebuilt.leaf_bytes() clean_hops.append(rebuilt) hop_leaves.append(leaf_b) prev_leaf_hex = rfc6962_leaf_hash(leaf_b).hex() clean_upc, hop_tuple = rule14_mask_provenance_text(upc), tuple(clean_hops) c2pa_root_bytes, proofs = _rfc6962_root_and_all_proofs(hop_leaves) c2pa_root_hex = c2pa_root_bytes.hex() raw_env_id = envelope_id if envelope_id is not None else str(uuid.uuid5(uuid.NAMESPACE_OID, f"{clean_upc}:{c2pa_root_hex}")) es_pub_b64 = b64url_encode(_p256_encode_sec1(keyring.es256_pub_xy)) ntt_pk_hex = _ntt_pk_digest(keyring.ntt_pub_key[0], keyring.ntt_pub_key[1]).hex() provisional = EternalProvenanceEnvelope( envelope_id=rule14_mask_provenance_text(raw_env_id), specimen_number=rule14_mask_provenance_text(specimen_number), title=rule14_mask_provenance_text(title), artist=rule14_mask_provenance_text(artist), human_author=rule14_mask_provenance_text(human_author), upc=clean_upc, true_peak_dbtp_q=peak_q, highpass_hz=highpass_hz, human_authorship_q=auth_q, content_id_fingerprinting_claimed=cid_flag, eu_ai_act_art50_disclosed=art50_flag, stages=clean_stages, hops=hop_tuple, c2pa_merkle_root_hex=c2pa_root_hex, hop_inclusion_proofs=proofs, lineage_envelope_ids=tuple(rule14_mask_provenance_text(lid) for lid in lin_seq), es256_pubkey_b64=es_pub_b64, wots_merkle_root_hex=keyring.wots_tree.merkle_root_hex, ntt_pk_sha256=ntt_pk_hex, manifest_sha256="", triple_seal=TripleSovereignSeal("", "", "", {}, (b"", ()), ("", [], [])), metadata=_mask_structure_deep(raw_meta), ) _validate_envelope_policies(provisional, hop_leaves) manifest_bytes = jcs_canonical_bytes(provisional.manifest_jcs_dict()) seal = TripleSovereignSeal( es256_pubkey_b64=es_pub_b64, es256_sig_b64=b64url_encode(p256_sign_es256(keyring.es256_priv_d, manifest_bytes)), wots_merkle_root_hex=keyring.wots_tree.merkle_root_hex, wots_sig=wots_sign(keyring.wots_tree, manifest_bytes, leaf_idx=wots_leaf_idx), ntt_pub_key=keyring.ntt_pub_key, ntt_sig=ntt_lattice_sign(keyring.ntt_sec_key, manifest_bytes), ) return replace(provisional, manifest_sha256=hashlib.sha256(manifest_bytes).hexdigest(), triple_seal=seal) class EternalRevocationRegistry: """Order-invariant causal-DAG revocation registry for Moral Veto & Cost-Zero Stop (P6).""" def __init__(self) -> None: self._children: dict[str, set[str]] = {} self._env_hops: dict[str, tuple[str, ...]] = {} self._env_ancs: dict[str, tuple[str, ...]] = {} self._hop_owner: dict[str, str] = {} self._records: dict[str, dict[str, Any]] = {} self._seq: int = 0 def _recompute_owned_hops(self, env_id, seen_desc=()): hop_ids, ancs = self._env_hops.get(env_id, ()), self._env_ancs.get(env_id, ()) inherited = {hid for anc in ancs for hid in self._env_hops.get(anc, ())} self._children[env_id].difference_update(hop_ids) owned = [] for hid in hop_ids: owner = self._hop_owner.get(hid) if hid not in inherited and (owner in (None, env_id) or owner in seen_desc): self._hop_owner[hid] = env_id owned.append(hid) if not owned and ancs and not inherited and hop_ids: owned = [hop_ids[-1]] self._children[env_id].update(owned) def register_envelope(self, envelope: EternalProvenanceEnvelope, parent_envelope_id: str | None = None) -> None: if not isinstance(envelope, EternalProvenanceEnvelope): raise TypeError("envelope must be EternalProvenanceEnvelope") chain = list(envelope.lineage_envelope_ids) if parent_envelope_id is not None: pid = rule14_mask_provenance_text(require_strict_str(parent_envelope_id, "parent_envelope_id")) if not pid.strip() or pid == envelope.envelope_id: raise ProvenanceError("parent_envelope_id must be non-empty and distinct from envelope_id", PEARL_SILENT_SANCTUARY) if pid not in chain: chain.append(pid) chain.append(envelope.envelope_id) for node_id in chain: self._children.setdefault(node_id, set()) for anc, desc in zip(chain, chain[1:]): if anc != desc: self._children[anc].add(desc) hop_ids = tuple(h.hop_id for h in envelope.hops) self._env_hops[envelope.envelope_id] = hop_ids self._env_ancs[envelope.envelope_id] = tuple(chain[:-1]) prev_hop = None for hid in hop_ids: self._children.setdefault(hid, set()).add(envelope.envelope_id) if prev_hop is not None: self._children[prev_hop].add(hid) prev_hop = hid desc_q = list(self._children.get(envelope.envelope_id, ())) seen_desc, dq_i = set(desc_q), 0 while dq_i < len(desc_q): d_id = desc_q[dq_i] dq_i += 1 if d_id != envelope.envelope_id: for nxt_d in self._children.get(d_id, ()): if nxt_d not in seen_desc and nxt_d not in hop_ids: seen_desc.add(nxt_d) desc_q.append(nxt_d) self._recompute_owned_hops(envelope.envelope_id, seen_desc) for d_id in desc_q: if d_id in self._env_hops and d_id != envelope.envelope_id: self._recompute_owned_hops(d_id) for check_id in (*chain, *hop_ids): if check_id in self._records: rec = self._records[check_id] rsn, act = str(rec["reason"]), str(rec["actor"]) self.revoke(check_id, rsn, actor=act) if envelope.envelope_id not in self._records: self.revoke(envelope.envelope_id, rsn, actor=act) break def revoke(self, target_id: str, reason: str, actor: str = "sovereign_human_author") -> dict[str, Any]: tid = rule14_mask_provenance_text(require_strict_str(target_id, "target_id")) rsn, act = require_strict_str(reason, "reason"), require_strict_str(actor, "actor") if not tid or rsn not in VALID_REVOCATION_REASONS: raise ProvenanceError(f"Invalid revocation target {tid!r} or reason {rsn!r}", PEARL_SILENT_SANCTUARY) self._seq += 1 seq_no, masked_actor, coupled = self._seq, rule14_mask_provenance_text(act), rsn in VALID_REVOCATION_REASONS queue, seen, q_idx = [tid], {tid}, 0 while q_idx < len(queue): cur = queue[q_idx] q_idx += 1 if cur not in self._records: self._records[cur] = { "node_id": cur, "root_target_id": tid, "reason": rsn, "actor": masked_actor, "revocation_seq": seq_no, "twist_zero_coupled": coupled, } for child in sorted(self._children.get(cur, ())): if child not in seen: seen.add(child) queue.append(child) return { "root_target_id": tid, "reason": rsn, "revocation_seq": seq_no, "revoked_nodes": tuple(queue), "twist_zero_coupled": coupled, } def is_id_revoked(self, node_id: str) -> bool: return rule14_mask_provenance_text(require_strict_str(node_id, "node_id")) in self._records def assert_active(self, envelope: EternalProvenanceEnvelope) -> None: if not isinstance(envelope, EternalProvenanceEnvelope): raise TypeError("envelope must be EternalProvenanceEnvelope") for candidate in (envelope.envelope_id, *envelope.lineage_envelope_ids, *(h.hop_id for h in envelope.hops)): rec = self._records.get(candidate) if rec is not None: raise RevokedProvenanceError(f"Provenance node {candidate!r} revoked via {rec['reason']}") def append_c2pa_mcp_provenance_hop( envelope: EternalProvenanceEnvelope, *, protocol: str, tool_or_agent_id: str, summary: str, ingredient_digest_sha256: str, output_digest_sha256: str, eu_ai_act_art50_disclosed: bool, keyring: TripleSovereignKeyring, wots_leaf_idx: int | None = None, upstream_pubkey: TripleSovereignPublicKey | None = None, revocation_registry: EternalRevocationRegistry | None = None, ) -> EternalProvenanceEnvelope: """Verify upstream envelope, append MCP/A2A hop in RFC 6962 Merkle-DAG, and re-seal.""" verify_eternal_provenance_envelope( envelope, keyring=upstream_pubkey or keyring.public_key(), revocation_registry=revocation_registry ) if wots_leaf_idx is None: chosen_leaf = next((i for i in range(WOTS_TREE_LEAVES) if i not in keyring.wots_tree._used_leaves), None) if chosen_leaf is None: raise ProvenanceError("All 4 WOTS+ leaves in keyring.wots_tree are exhausted") else: chosen_leaf = require_strict_int(wots_leaf_idx, "wots_leaf_idx") next_idx = len(envelope.hops) hop_seed = ( f"{envelope.envelope_id}:hop:{next_idx}:{rule14_mask_provenance_text(require_strict_str(protocol, 'protocol'))}:" f"{rule14_mask_provenance_text(require_strict_str(tool_or_agent_id, 'tool_or_agent_id'))}:" f"{require_strict_str(ingredient_digest_sha256, 'ingredient_digest_sha256')}:" f"{require_strict_str(output_digest_sha256, 'output_digest_sha256')}:" f"{rule14_mask_provenance_text(require_strict_str(summary, 'summary'))}" ) hop_id = str(uuid.uuid5(uuid.NAMESPACE_OID, hop_seed)) new_hop = C2paMcpProvenanceHop( hop_index=next_idx, hop_id=hop_id, protocol=protocol, tool_or_agent_id=tool_or_agent_id, summary=summary, ingredient_digest_sha256=ingredient_digest_sha256, output_digest_sha256=output_digest_sha256, parent_hop_leaf_sha256=None, eu_ai_act_art50_disclosed=eu_ai_act_art50_disclosed, ) next_env_id = str(uuid.uuid5(uuid.NAMESPACE_OID, f"{envelope.envelope_id}:derived:{next_idx}:{hop_id}")) sealed = seal_eternal_provenance_envelope( specimen_number=envelope.specimen_number, title=envelope.title, artist=envelope.artist, human_author=envelope.human_author, upc=envelope.upc, true_peak_dbtp_q=envelope.true_peak_dbtp_q, highpass_hz=envelope.highpass_hz, human_authorship_q=envelope.human_authorship_q, content_id_fingerprinting_claimed=envelope.content_id_fingerprinting_claimed, eu_ai_act_art50_disclosed=envelope.eu_ai_act_art50_disclosed, stages=envelope.stages, hops=(*envelope.hops, new_hop), keyring=keyring, wots_leaf_idx=chosen_leaf, lineage_envelope_ids=(*envelope.lineage_envelope_ids, envelope.envelope_id), envelope_id=next_env_id, metadata=envelope.metadata, ) if revocation_registry is not None: revocation_registry.register_envelope(envelope) revocation_registry.register_envelope(sealed, parent_envelope_id=envelope.envelope_id) return sealed def verify_eternal_provenance_envelope( envelope: EternalProvenanceEnvelope, keyring: TripleSovereignKeyring | TripleSovereignPublicKey | None = None, revocation_registry: EternalRevocationRegistry | None = None, ) -> dict[str, Any]: """Fail-closed verifier checking P1..P6 invariants, RFC 6962 proofs, and Triple Seal.""" if not isinstance(envelope, EternalProvenanceEnvelope): raise TypeError("envelope must be EternalProvenanceEnvelope") assert_no_floats(envelope) if revocation_registry is not None: revocation_registry.assert_active(envelope) hop_leaves = [h.leaf_bytes() for h in envelope.hops] _validate_envelope_policies(envelope, hop_leaves) _assert_rule14_clean_deep( [ envelope.envelope_id, envelope.specimen_number, envelope.title, envelope.artist, envelope.human_author, envelope.upc, envelope.lineage_envelope_ids, envelope.metadata, [(s.stage_id, s.actor_name, s.description, s.extra_metadata) for s in envelope.stages], [(h.hop_id, h.protocol, h.tool_or_agent_id, h.summary) for h in envelope.hops], ] ) hop_count = len(hop_leaves) try: expected_c2pa_root = bytes.fromhex(require_sha256_hex(envelope.c2pa_merkle_root_hex, "c2pa_merkle_root_hex")) except ValueError as exc: raise C2paIntegrityOrDisclosureError(str(exc)) from exc if not hmac.compare_digest(rfc6962_merkle_root(hop_leaves), expected_c2pa_root): raise C2paIntegrityOrDisclosureError("C2PA-MCP RFC 6962 Merkle root mismatch") if len(envelope.hop_inclusion_proofs) != hop_count: raise C2paIntegrityOrDisclosureError("Hop RFC 6962 inclusion proof count mismatch") verified_hops = 0 for idx, (leaf_b, proof) in enumerate(zip(hop_leaves, envelope.hop_inclusion_proofs)): if not rfc6962_verify_inclusion(leaf_b, idx, hop_count, proof, expected_c2pa_root): raise C2paIntegrityOrDisclosureError(f"Invalid RFC 6962 inclusion proof at hop {idx}") verified_hops += 1 manifest_bytes = jcs_canonical_bytes(envelope.manifest_jcs_dict()) try: claimed_manifest = bytes.fromhex(require_sha256_hex(envelope.manifest_sha256, "manifest_sha256")) claimed_ntt_pk = bytes.fromhex(require_sha256_hex(envelope.ntt_pk_sha256, "ntt_pk_sha256")) except ValueError as exc: raise SignatureVerificationError("Invalid manifest_sha256 or ntt_pk_sha256 hex digest") from exc if not hmac.compare_digest(hashlib.sha256(manifest_bytes).digest(), claimed_manifest): raise SignatureVerificationError("Canonical JCS manifest SHA-256 mismatch") seal = envelope.triple_seal if ( not _ct_str_eq(seal.es256_pubkey_b64, envelope.es256_pubkey_b64) or not _ct_str_eq(seal.wots_merkle_root_hex, envelope.wots_merkle_root_hex) or not _ct_str_eq(seal.wots_sig.get("merkle_root_hex"), envelope.wots_merkle_root_hex) ): raise SignatureVerificationError("Envelope/seal public key binding mismatch") if len(seal.ntt_pub_key) != 2 or len(seal.ntt_pub_key[1]) != NTT_N or any(not (0 <= c < NTT_Q) for c in seal.ntt_pub_key[1]): raise SignatureVerificationError("Malformed NTT public key in Triple Seal") if not hmac.compare_digest(_ntt_pk_digest(seal.ntt_pub_key[0], seal.ntt_pub_key[1]), claimed_ntt_pk): raise SignatureVerificationError("NTT public key digest mismatch against JCS manifest") try: es_pub_bytes = b64url_decode(seal.es256_pubkey_b64) es_sig_bytes = b64url_decode(seal.es256_sig_b64) except ValueError as exc: raise SignatureVerificationError("Malformed Base64url ES256 seal") from exc if len(es_pub_bytes) != 65 or es_pub_bytes[0] != 0x04: raise SignatureVerificationError("Envelope ES256 public key must be canonical 65-byte uncompressed SEC1") if keyring is not None: if isinstance(keyring, TripleSovereignKeyring): pin = keyring.public_key() elif isinstance(keyring, TripleSovereignPublicKey): pin = keyring else: raise TypeError("keyring must be TripleSovereignKeyring or TripleSovereignPublicKey") es_xy = _p256_validate_pubkey(es_pub_bytes) if es_xy is None or not hmac.compare_digest(_p256_encode_sec1(es_xy), _p256_encode_sec1(pin.es256_pub_xy)): raise SignatureVerificationError("ES256 public key pin mismatch") if not _ct_str_eq(seal.wots_merkle_root_hex, pin.wots_merkle_root_hex): raise SignatureVerificationError("WOTS+ Merkle root pin mismatch") if not ( hmac.compare_digest(seal.ntt_pub_key[0], pin.ntt_pub_key[0]) and hmac.compare_digest(encode_poly_mod_q(seal.ntt_pub_key[1]), encode_poly_mod_q(pin.ntt_pub_key[1])) ): raise SignatureVerificationError("Ring-NTT public key pin mismatch") wots_ok = wots_verify(seal.wots_merkle_root_hex, manifest_bytes, seal.wots_sig) if not wots_ok: raise SignatureVerificationError("Post-Quantum WOTS+-SHA256 seal verification failed") ntt_ok = ntt_lattice_verify(seal.ntt_pub_key, manifest_bytes, seal.ntt_sig) if not ntt_ok: raise SignatureVerificationError("Post-Quantum FIPS 204 Ring-NTT seal verification failed") es_ok = p256_verify_es256(es_pub_bytes, manifest_bytes, es_sig_bytes) if not es_ok: raise SignatureVerificationError("Classical NIST P-256 ES256 seal verification failed") seals_passed = int(es_ok) + int(wots_ok) + int(ntt_ok) return { "envelope_id": envelope.envelope_id, "upc": envelope.upc, "verified_hops": verified_hops, "seals_passed": seals_passed, "es256_valid": es_ok, "wots_valid": wots_ok, "ntt_valid": ntt_ok, "all_hops_verified": verified_hops == hop_count, "verified": seals_passed == 3 and verified_hops == hop_count, } def partition_symbiotic_royalties_and_energy( shares_q: Mapping[str, Fraction], load_l_q: Fraction, budget_b_q: Fraction, gross_units: int = 10000 ) -> dict[str, Any]: """Enforce exact sum(shares_q) == 1 and 0 <= L <= B with permutation-invariant PII masking.""" assert_no_floats([shares_q, load_l_q, budget_b_q, gross_units]) if not isinstance(shares_q, Mapping): raise TypeError("shares_q must be a Mapping[str, Fraction]") if len(shares_q) == 0: raise RoyaltyOrBudgetError("shares_q must be a non-empty Mapping[str, Fraction]") l_q, b_q = require_strict_fraction(load_l_q, "load_l_q"), require_strict_fraction(budget_b_q, "budget_b_q") units = require_strict_int(gross_units, "gross_units") if units < 0 or not (Fraction(0, 1) <= l_q <= b_q): raise RoyaltyOrBudgetError(f"Thermodynamic Covenant violated: require units >= 0 and 0 <= L ({l_q}) <= B ({b_q})") raw_total, pairs = Fraction(0, 1), [] for party, share in shares_q.items(): p_str = require_strict_str(party, "stakeholder") _assert_no_lone_surrogates(p_str) if not p_str.strip(): raise RoyaltyOrBudgetError("Royalty stakeholder key must be non-empty") sq = require_strict_fraction(share, f"shares_q[{p_str}]") if sq < Fraction(0, 1) or sq > Fraction(1, 1): raise RoyaltyOrBudgetError(f"Stakeholder share {sq} outside [0, 1]") raw_total += sq pairs.append((p_str, sq)) if raw_total != Fraction(1, 1): raise RoyaltyOrBudgetError(f"Royalty shares must sum to exact 1, got {raw_total}") clean_shares = _mask_collision_safe_dict(pairs, b"HU-ROYALTY-PARTY\x00") allocations_q = {k: sq * units for k, sq in clean_shares.items()} floors = {k: val.numerator // val.denominator for k, val in allocations_q.items()} remainders = sorted( ((allocations_q[k] - Fraction(floors[k], 1), k.encode("utf-16-be"), k) for k in allocations_q), key=lambda item: (-item[0], item[1]), ) for idx in range(units - sum(floors.values())): floors[remainders[idx][2]] += 1 allocated_sum = sum(floors.values()) return { "total_share_q": raw_total, "headroom_q": b_q - l_q, "allocations_q": allocations_q, "allocated_units": floors, "allocated_sum": allocated_sum, "conservation_exact": raw_total == Fraction(1, 1) and allocated_sum == units, "budget_respected": Fraction(0, 1) <= l_q <= b_q, } def build_canonical_lux_in_tenebris_specimen( keyring: TripleSovereignKeyring | None = None, wots_leaf_idx: int = 0, revocation_registry: EternalRevocationRegistry | None = None, ) -> EternalProvenanceEnvelope: """Construct Canonical Specimen #0001: 'Lux in Tenebris Lucet' (UPC 5064173370631).""" require_strict_int(wots_leaf_idx, "wots_leaf_idx") active_kr = TripleSovereignKeyring.from_master_seed(DEFAULT_MASTER_SEED) if keyring is None else keyring if not isinstance(active_kr, TripleSovereignKeyring): raise TypeError("keyring must be TripleSovereignKeyring or None") draft_commit, draft_clevels = blind_human_rough_draft( b"Lux in tenebris lucet, et tenebrae eam non comprehenderunt.", b"HU-SPECIMEN-0001-LYRIC-SALT-2026" ) ai_stem_sha = hashlib.sha256(b"HU-SPECIMEN-0001-AI-INSTRUMENTAL-STEM").hexdigest() ai_lic_sha = hashlib.sha256(b"HU-SPECIMEN-0001-COMMERCIAL-SYNTH-LICENSE").hexdigest() edit_sha = hashlib.sha256(b"HU-SPECIMEN-0001-SURGICAL-STEM-ARRANGEMENT").hexdigest() master_sha = hashlib.sha256(b"HU-SPECIMEN-0001-SILK-MASTER-MINUS-1P1-DBTP-35HZ").hexdigest() stages = ( CreativeContributionStage( "stage-01-lyric-genesis", HUMAN_LYRIC_GENESIS, "HUMAN", "David Porto Baraldés", Fraction(3, 8), "Original Latin-Catalan poetic genesis blinded at c_levels == 1.", draft_commit, c_levels=draft_clevels, is_blinded_rough_draft=draft_clevels == 1, ), CreativeContributionStage( "stage-02-ai-instrumental", AI_INSTRUMENTAL_SYNTHESIS, "AI", "Symbiotic Harmonic Engine v1", Fraction(1, 4), "Commercially licensed orchestral bed under human harmonic direction.", ai_stem_sha, c_levels=0, commercial_license_proof_sha256=ai_lic_sha, ), CreativeContributionStage( "stage-03-surgical-stem-edit", HUMAN_SURGICAL_STEM_EDIT, "HUMAN", "David Porto Baraldés", Fraction(1, 4), "Surgical stem arrangement, counterpoint phrasing, and modal sculpting.", edit_sha, ), CreativeContributionStage( "stage-04-silk-mastering", ACOUSTIC_SILK_MASTERING, "HUMAN", "David Porto Baraldés", Fraction(1, 8), "Acoustic Silk Mastering (-1.1 dBTP true-peak ceiling, 35 Hz highpass).", master_sha, ), ) upc = "5064173370631" hop_specs = ( ("C2PA_GENESIS", "urn:hu:c2pa:genesis-forge:v1", draft_commit, draft_commit), ("A2A_SYNTHESIS", "a2a://symbiotic-harmonic/synth-v1", draft_commit, ai_stem_sha), ("MCP_TOOL_CALL", "mcp://hu-daw/surgical-stem-editor", ai_stem_sha, edit_sha), ("C2PA_MASTER_SEAL", "urn:hu:silk-master:35hz-minus1p1dbtp", edit_sha, master_sha), ) hops = tuple( C2paMcpProvenanceHop( idx, str(uuid.uuid5(uuid.NAMESPACE_OID, f"{upc}:genesis-hop:{idx}")), proto, uri, stages[idx].description, in_sha, out_sha, None, len(stages) == 4, ) for idx, (proto, uri, in_sha, out_sha) in enumerate(hop_specs) ) sealed = seal_eternal_provenance_envelope( specimen_number="#0001", title="Lux in Tenebris Lucet", artist="Homo Universalis", human_author="David Porto Baraldés", upc=upc, true_peak_dbtp_q=Fraction(-11, 10), highpass_hz=35, human_authorship_q=Fraction(3, 4), content_id_fingerprinting_claimed=len(stages) == 0, eu_ai_act_art50_disclosed=len(stages) == 4, stages=stages, hops=hops, keyring=active_kr, wots_leaf_idx=wots_leaf_idx, metadata={"covenant": "Terra-Aire-Foc-Aigua", "folio": "VIII"}, ) if revocation_registry is not None: revocation_registry.register_envelope(sealed) return sealed # === Section 7: Deterministic Self-Test & 8/8 Adversarial Mutant Suite (< 0.6s) === def _schoolbook_negacyclic_mul_256(a, b): raw = [0] * (2 * NTT_N) b_mod = [x % NTT_Q for x in b] for i, ai_raw in enumerate(a): ai = ai_raw % NTT_Q if ai: for j, bj in enumerate(b_mod): raw[i + j] += ai * bj return [(raw[k] - raw[k + NTT_N]) % NTT_Q for k in range(NTT_N)] def _expect_exc(exc_type, fn, *args, **kwargs): try: fn(*args, **kwargs) except exc_type: return 1 == 1 return 1 == 0 def run_self_tests() -> dict[str, Any]: """Execute deterministic crypto/algebra proofs, Specimen #0001, and 8/8 mutant kills.""" t0_ns = time.perf_counter_ns() t_flag, f_flag = 1 == 1, 1 == 0 dyn_float = json.loads("-1.1") # 1. Base64url bijection, RFC 8785 UTF-16-BE JCS, RFC 6962 dyadic trees & P-256 RFC 6979 KAT for raw in (b"", b"f", b"fo", b"foo", b"\x00\xff\xfe\x80", bytes(range(35))): tok = b64url_encode(raw) if b64url_decode(tok) != raw or "=" in tok: raise AssertionError("Base64url bijection or unpadded invariant failed") if not all(_expect_exc(ValueError, b64url_decode, bad) for bad in ("A", "AA==", "AB", "AAB", "ab+/")): raise AssertionError("Base64url canonical tail/padding guard failed") jcs_vec = {"\ufb33": [IJSON_MIN_INT, IJSON_MAX_INT], "\ue000": None, "\U00010000": "a\n\x00\"\\", "2": t_flag, "10": f_flag} exp_jcs = f'{{"10":false,"2":true,"\U00010000":"a\\n\\u0000\\"\\\\","\ue000":null,"\ufb33":[{IJSON_MIN_INT},{IJSON_MAX_INT}]}}'.encode("utf-8") if jcs_canonical_bytes(jcs_vec) != exp_jcs or not ( _expect_exc(ValueError, jcs_canonical_bytes, {"s": "\ud800"}) and _expect_exc(ValueError, jcs_canonical_bytes, {"hi": IJSON_MAX_INT + 1}) ): raise AssertionError("RFC 8785 JCS canonicalization or surrogate/I-JSON guard failed") for tree_n in (1, 3, 5, 7): leaves = [f"leaf-{tree_n}-{i}".encode("utf-8") for i in range(tree_n)] m_root = rfc6962_merkle_root(leaves) for li in range(tree_n): prf = rfc6962_inclusion_proof(leaves, li) if not rfc6962_verify_inclusion(leaves[li], li, tree_n, prf, m_root): raise AssertionError("RFC 6962 inclusion proof failed") if tree_n > 1 and rfc6962_verify_inclusion(leaves[li], (li + 1) % tree_n, tree_n, prf, m_root): raise AssertionError("RFC 6962 cross-index forgery accepted") # 2. Negacyclic NTT isomorphism & RFC 6979 + low-S P-256 KAT poly_f = [((i * 7919 + 13) % 4096) - 2048 for i in range(NTT_N)] poly_g = [((i * 6151 + 29) % 4096) - 2048 for i in range(NTT_N)] ntt_prod = intt_256([(x * y) % NTT_Q for x, y in zip(ntt_256(poly_f), ntt_256(poly_g))]) negacyclic_ok = ntt_prod == _schoolbook_negacyclic_mul_256(poly_f, poly_g) ball_c = sample_in_ball_16(hashlib.sha256(b"HU-BALL-16").digest()) if not negacyclic_ok or sum(abs(x) for x in ball_c) != NTT_TAU or set(ball_c) - {-1, 0, 1}: raise AssertionError("Ring-NTT negacyclic convolution or sample_in_ball_16 failed") kat_d = 0xC9AFA9D845BA75166B5C215767B1D6934E50C3DB36E89B127B8A622B120F6721 kat_r = 0xEFD48B2AACB6A8FD1140DD9CD45E81D69D2C877B56AAF991C34D0EA84EAF3716 kat_s_raw = 0xF7CB1C942D657C41D436C7A1B6E29F65F3E900DBB9AFF4064DC4AB2F843ACDA8 kat_pub = _p256_to_affine(_p256_scalar_mul_g(kat_d)) kat_sig = p256_sign_es256(kat_d, b"sample") if ( kat_pub is None or kat_sig != kat_r.to_bytes(32, "big") + (N - kat_s_raw).to_bytes(32, "big") or not p256_verify_es256(kat_pub, b"sample", kat_sig) or p256_verify_es256(kat_pub, b"sample", kat_r.to_bytes(32, "big") + kat_s_raw.to_bytes(32, "big")) ): raise AssertionError("NIST P-256 RFC 6979 KAT or canonical low-S check failed") # 3. Canonical Specimen #0001 & single shared TripleSovereignKeyring keyring = TripleSovereignKeyring.from_master_seed(DEFAULT_MASTER_SEED) registry = EternalRevocationRegistry() specimen = build_canonical_lux_in_tenebris_specimen(keyring=keyring, wots_leaf_idx=0, revocation_registry=registry) spec_res = verify_eternal_provenance_envelope(specimen, keyring=keyring.public_key(), revocation_registry=registry) dist_sha = hashlib.sha256(b"HU-SPECIMEN-0001-C2PA-DIST-PACK").hexdigest() derived = append_c2pa_mcp_provenance_hop( specimen, protocol="MCP_TOOL_CALL", tool_or_agent_id="mcp://hu-dist/c2pa-packager", summary="Packaged lossless master with C2PA-MCP sidecar.", ingredient_digest_sha256=specimen.hops[-1].output_digest_sha256, output_digest_sha256=dist_sha, eu_ai_act_art50_disclosed=t_flag, keyring=keyring, wots_leaf_idx=1, revocation_registry=registry, ) der_res = verify_eternal_provenance_envelope(derived, keyring=keyring.public_key(), revocation_registry=registry) specimen_ok = ( spec_res["verified"] and der_res["verified"] and specimen.upc == "5064173370631" and specimen.human_authorship_q == Fraction(3, 4) and specimen.true_peak_dbtp_q == Fraction(-11, 10) and specimen.highpass_hz == 35 and len(derived.hops) == 5 ) if not specimen_ok: raise AssertionError("Canonical Specimen #0001 or derived C2PA-MCP hop failed verification") manifest_b = jcs_canonical_bytes(specimen.manifest_jcs_dict()) mutants: dict[str, bool] = {} # Mutant 1: 1-bit tamper in WOTS+ chain caught by checksum / RFC 6962 root c0_raw = bytearray(b64url_decode(specimen.triple_seal.wots_sig["chains_b64"][0])) c0_raw[0] ^= 0x01 bad_chains = (b64url_encode(bytes(c0_raw)), *specimen.triple_seal.wots_sig["chains_b64"][1:]) bad_wots_sig = {**specimen.triple_seal.wots_sig, "chains_b64": bad_chains} m1_env = replace(specimen, triple_seal=replace(specimen.triple_seal, wots_sig=bad_wots_sig)) mutants["mutant_1_wots_bit_flip"] = ( not wots_verify(specimen.wots_merkle_root_hex, manifest_b, bad_wots_sig) and _expect_exc(SignatureVerificationError, verify_eternal_provenance_envelope, m1_env, keyring.public_key()) ) # Mutant 2: Ring-NTT 1-unit tamper in z1 AND excessive ||z1||_inf > GAMMA1 - BETA caught c_hex, orig_z1, orig_z2 = specimen.triple_seal.ntt_sig tampered_z1 = list(orig_z1) tampered_z1[0] = tampered_z1[0] - 1 if tampered_z1[0] == NTT_NORM_BOUND else tampered_z1[0] + 1 over_z1 = [NTT_NORM_BOUND + 1, *orig_z1[1:]] m2_env = replace(specimen, triple_seal=replace(specimen.triple_seal, ntt_sig=(c_hex, tampered_z1, list(orig_z2)))) mutants["mutant_2_ntt_lattice_forger"] = ( not ntt_lattice_verify(keyring.ntt_pub_key, manifest_b, (c_hex, tampered_z1, orig_z2)) and not ntt_lattice_verify(keyring.ntt_pub_key, manifest_b, (c_hex, over_z1, orig_z2)) and _expect_exc(SignatureVerificationError, verify_eternal_provenance_envelope, m2_env, keyring.public_key()) ) # Mutant 3: Zero human slop copyright OR missing AI commercial license OR > -1 dBTP rejected ai_only_st = (replace(specimen.stages[1], weight_q=Fraction(1, 1)),) unlic_stages = (specimen.stages[0], replace(specimen.stages[1], commercial_license_proof_sha256=None), *specimen.stages[2:]) mutants["mutant_3_zero_human_slop_copyright"] = ( _expect_exc(AuthorshipSlopOrLicenseError, verify_eternal_provenance_envelope, replace(specimen, human_authorship_q=Fraction(0, 1), stages=ai_only_st)) and _expect_exc(AuthorshipSlopOrLicenseError, verify_eternal_provenance_envelope, replace(specimen, stages=unlic_stages)) and _expect_exc(AuthorshipSlopOrLicenseError, verify_eternal_provenance_envelope, replace(specimen, true_peak_dbtp_q=Fraction(0, 1))) ) # Mutant 4: Living-artist voice cloning prompt & biometric keys blocked fail-closed mutants["mutant_4_living_voice_clone_biometric"] = ( _expect_exc(ImpersonationOrBiometricError, scan_impersonation_and_biometric_hazards, "Please clone voice of a living singer") and _expect_exc(ImpersonationOrBiometricError, scan_impersonation_and_biometric_hazards, "Make vocal sound like Rosalia") and _expect_exc(ImpersonationOrBiometricError, scan_impersonation_and_biometric_hazards, {"voiceprint_vector": [1, 2]}) and _expect_exc(ImpersonationOrBiometricError, scan_impersonation_and_biometric_hazards, {"speaker_biometric_embedding": "x"}) and _expect_exc(ImpersonationOrBiometricError, scan_impersonation_and_biometric_hazards, {"facial_landmarks": []}) ) # Mutant 5: Content-ID claim on AI-assisted stem rejected mutants["mutant_5_ai_stem_content_id_claim"] = ( _expect_exc( ContentIdAbuseError, scan_impersonation_and_biometric_hazards, specimen.stages, content_id_fingerprinting_claimed=t_flag, ) and _expect_exc( ContentIdAbuseError, verify_eternal_provenance_envelope, replace(specimen, content_id_fingerprinting_claimed=t_flag), ) ) # Mutant 6: Tampered upstream RFC 6962 ingredient OR stripped EU AI Act Art. 50 rejected bad_hop1 = replace(specimen.hops[1], ingredient_digest_sha256="0" * 64) stripped_hop = replace(specimen.hops[-1], eu_ai_act_art50_disclosed=f_flag) mutants["mutant_6_c2pa_mcp_art50_strip"] = ( _expect_exc(C2paIntegrityOrDisclosureError, verify_eternal_provenance_envelope, replace(specimen, hops=(specimen.hops[0], bad_hop1, *specimen.hops[2:]))) and _expect_exc(C2paIntegrityOrDisclosureError, verify_eternal_provenance_envelope, replace(specimen, eu_ai_act_art50_disclosed=f_flag)) and _expect_exc(C2paIntegrityOrDisclosureError, verify_eternal_provenance_envelope, replace(specimen, hops=(*specimen.hops[:-1], stripped_hop))) ) # Mutant 7: Float/bool rejection, idempotent Rule 14 scrubbing & exact royalty conservation pii_sample = "Key VVK-1234-5678 mail a@b.cat tel +34 600 123 456 /Users/dp/k /home/dp/x C:\\sec\\k 41.3874, 2.1686 on 2026-04-19" masked_once = rule14_mask_provenance_text(pii_sample) roy_ok = partition_symbiotic_royalties_and_energy( {"human_author": Fraction(3, 4), "ai_engine_licensor": Fraction(1, 4)}, Fraction(3, 10), Fraction(1, 1) ) mutants["mutant_7_float_or_rule14_leak"] = ( _expect_exc(TypeError, assert_no_floats, {"bad": [dyn_float]}) and _expect_exc(TypeError, require_strict_int, t_flag) and _expect_exc(TypeError, require_strict_fraction, t_flag) and masked_once == rule14_mask_provenance_text(masked_once) and "VVK-****-****" in masked_once and "[date-shielded]" in masked_once and "VVK-1234-5678" not in masked_once and "a@b.cat" not in masked_once and "/Users/" not in masked_once and _expect_exc(C2paIntegrityOrDisclosureError, verify_eternal_provenance_envelope, replace(specimen, metadata={"leak": "VVK-1234-5678"})) and roy_ok["conservation_exact"] and roy_ok["budget_respected"] and _expect_exc(RoyaltyOrBudgetError, partition_symbiotic_royalties_and_energy, {"a": Fraction(2, 3)}, Fraction(1, 4), Fraction(1, 1)) and _expect_exc(RoyaltyOrBudgetError, partition_symbiotic_royalties_and_energy, {"a": Fraction(1, 1)}, Fraction(2, 1), Fraction(1, 1)) ) # Mutant 8: Instant subtree revocation on AUTHOR_MORAL_VETO and COST_ZERO_STOP sibling_env = build_canonical_lux_in_tenebris_specimen(keyring=keyring, wots_leaf_idx=2) sibling_isolated = replace(sibling_env, envelope_id="isolated-root-env") registry.register_envelope(sibling_isolated) veto_rec = registry.revoke(specimen.envelope_id, AUTHOR_MORAL_VETO) stop_rec = registry.revoke(sibling_isolated.envelope_id, COST_ZERO_STOP) mutants["mutant_8_post_moral_veto_replay"] = ( veto_rec["twist_zero_coupled"] and stop_rec["twist_zero_coupled"] and _expect_exc(RevokedProvenanceError, verify_eternal_provenance_envelope, specimen, keyring.public_key(), registry) and _expect_exc(RevokedProvenanceError, verify_eternal_provenance_envelope, derived, keyring.public_key(), registry) and registry.is_id_revoked(sibling_isolated.envelope_id) ) killed_count = sum(1 for v in mutants.values() if v) elapsed_ms = (time.perf_counter_ns() - t0_ns) // 1_000_000 if killed_count != 8: failed = [k for k, v in mutants.items() if not v] raise AssertionError(f"Adversarial mutant suite incomplete ({killed_count}/8); survivors: {failed}") return { "protocol": PROTOCOL_VERSION, "specimen_upc": specimen.upc, "ntt_negacyclic_exact": negacyclic_ok, "specimen_verified": specimen_ok, "mutants_killed": killed_count, "all_mutants_killed": killed_count == 8, "mutant_results": mutants, "elapsed_ms": elapsed_ms, } if __name__ == "__main__": summary = run_self_tests() if not summary["all_mutants_killed"]: raise AssertionError("Self-test suite failed")