#!/usr/bin/env python3 """Clean-room verifier for the CAIN-42 E34 (Proof-Carrying Machine Agency) evidence bundle. Imports nothing from CAIN; needs only `cryptography` and the standard library. It re-derives, from the published artifacts alone: * every GovernanceProofEnvelope: canonical hash, Ed25519 signature, recomputed unknown-field set, and the fourteen-status classification computed by its own logic; * the tamper-evident receipt chain and the per-layer proof primitives (identity/capability/authority/policy/risk/ evidence/decision/commit/enforcement/outcome); * the enforcement proof's six stages (decision != authorization != commit != enforcement != execution != outcome); * the delegation chain and its attenuation; * the coverage graph, conformance levels, certificates, contracts, selective-disclosure inclusion proofs, federation, the edge node, the V3 handshake, the interchange classifications, the V3 immune response, the failure-to-proof compiler, the data plane, replay and the time machine; and it must REJECT every object in MALICIOUS.json. python3 verify_e34.py """ from __future__ import annotations import base64 import hashlib import json import sys from pathlib import Path from cryptography.exceptions import InvalidSignature from cryptography.hazmat.primitives.asymmetric import ed25519 D_ENVELOPE = "CAIN42/E34-GOVERNANCE-PROOF-ENVELOPE/v1" D_RECEIPT = "CAIN42/E34-GOVERNANCE-RECEIPT/v1" D_PRIMITIVE = "CAIN42/E34-PROOF-PRIMITIVE/v1" D_ENFORCEMENT = "CAIN42/E34-ENFORCEMENT-PROOF/v1" D_DELEGATION_CHAIN = "CAIN42/E34-DELEGATION-PROOF-CHAIN/v1" D_DISCLOSURE = "CAIN42/E34-SELECTIVE-DISCLOSURE-ROOT/v1" D_CONTRACT = "CAIN42/E34-MACHINE-GOVERNANCE-CONTRACT/v1" D_CERT = "CAIN42/E34-GOVERNABILITY-CERTIFICATE/v1" D_MANIFEST = "CAIN42/E34-GOVERNABILITY-MANIFEST/v1" D_INTERCHANGE = "CAIN42/E34-GOVERNANCE-INTERCHANGE/v1" D_HANDSHAKE = "CAIN42/E34-GOVERNANCE-HANDSHAKE-V3/v1" D_IMMUNE = "CAIN42/E34-IMMUNE-RESPONSE/v1" D_F2P = "CAIN42/E34-FAILURE-TO-PROOF/v1" D_DATAPLANE = "CAIN42/E34-GOVERNANCE-EVENT/v1" D_REPLAY = "CAIN42/E34-REPLAY/v1" D_TX = "CAIN42/E34-TRANSACTION-PROOF/v1" D_CU = "CAIN42/E34-COMPUTER-USE-PROOF/v1" D_SUPPLY = "CAIN42/E34-SUPPLY-CHAIN-PROOF/v1" D_RECOVERY = "CAIN42/E34-RECOVERY-PROOF/v1" D_DENIAL = "CAIN42/E34-DENIAL-PROOF/v1" D_PROOF = "CAIN42/E31-GOVERNANCE-PROOF/v1" D_E28 = "CAIN42/E28-GOVERNANCE-RECEIPT/v1" D_E25 = "CAIN42/E25-EXECUTION-RECEIPT/v1" D_E8 = "CAIN42/E8-KERNEL-EVIDENCE/v1" D_UAR = "CAIN42/E30-UNIVERSAL-ACTION-RECEIPT/v1" D_POSTCONDITION = "CAIN42/E31-POSTCONDITION-OBSERVATION/v1" D_MASTER = "CAIN42/E34-MASTER/v1" ENVELOPE_FIELDS = ("proof_id", "proof_version", "action_id", "operation_id", "transaction_id", "agent_identity", "agent_passport_digest", "identity_state", "capability_state", "delegation_chain", "authority_state", "authority_digest", "policy_digest", "policy_version", "context_digest", "evidence_digest", "risk_digest", "decision_digest", "trajectory_digest", "world_state_digest", "model_runtime_identity", "model_runtime_version", "execution_environment", "capability_used", "resource_target", "requested_effect", "authorization_id", "authorization_scope", "authorization_expiry", "authorization_nonce", "e8_commit_id", "enforcement_boundary", "enforcement_result", "execution_result", "outcome_evidence", "revocation_state", "conformance_state", "governance_coverage", "proof_status", "timestamp", "sequence", "previous_proof_hash", "evidence_references", "verifier_metadata", "governance_contract_digest") STATUSES = ("VERIFIED_GOVERNED", "PARTIALLY_GOVERNED", "ENFORCED_WITH_INCOMPLETE_PROOF", "OBSERVED_ONLY", "MONITORED_ONLY", "SIMULATED", "DEMO_ONLY", "UNCONTROLLED", "UNKNOWN", "REJECTED", "REVOKED", "EXPIRED", "INVALID_PROOF", "SUPERSEDED") PCA_CHAIN = ("INTENT", "IDENTITY", "CAPABILITY", "DELEGATION", "AUTHORITY", "POLICY", "CONTEXT", "EVIDENCE", "RISK", "DECISION", "AUTHORIZATION", "E8_COMMIT", "ENFORCEMENT", "EXECUTION", "OUTCOME", "PROOF") ENFORCEMENT_SEQUENCE = ("DECISION_MADE", "AUTHORIZATION_ISSUED", "ACTION_COMMITTED", "ACTION_ENFORCED", "ACTION_EXECUTED", "OUTCOME_OBSERVED") PRIMITIVE_FIELDS = {"identity": ("agent_identity", "identity_state", "agent_passport_digest"), "capability": ("capability_state", "capability_used"), "delegation": ("delegation_chain", "authority_digest"), "authority": ("authority_state", "authority_digest"), "policy": ("policy_digest", "policy_version"), "risk": ("risk_digest",), "evidence": ("evidence_digest", "evidence_references"), "decision": ("decision_digest",), "commit": ("e8_commit_id", "enforcement_boundary"), "enforcement": ("enforcement_result", "execution_result"), "outcome": ("outcome_evidence",)} COVERAGE_CLASSES = ("ENFORCED", "MONITORED", "OBSERVED", "PARTIALLY_ENFORCED", "BYPASSABLE", "UNCONTROLLED", "UNKNOWN") LEVELS = ("G0", "G1", "G2", "G3", "G4", "G5", "G6", "G7") LEVEL_MEANING = {"G0": "UNKNOWN", "G1": "OBSERVED", "G2": "IDENTIFIED", "G3": "AUTHORIZED", "G4": "ENFORCED", "G5": "PROOF-CARRYING", "G6": "INDEPENDENTLY VERIFIABLE", "G7": "FEDERATED GOVERNANCE"} CONFORMANCE_PROFILES = ("agent", "model_runtime", "tool", "mcp_server", "a2a_agent", "gateway", "sidecar", "organization", "transaction", "physical_system", "computer_use_runtime", "research_agent", "self_improving_agent") CONTRACT_LIMITS = ("scope", "time", "budget", "capability", "geographic", "organizational", "resource", "transaction", "trajectory", "model_runtime", "evidence", "human_approval", "multi_party_approval") CERT_FIELDS = ("subject", "identity", "version", "protocols", "governance_profile", "proof_profile", "evidence_root", "verifier_version", "test_suite_version", "conformance_level", "expiration", "revocation_endpoint", "limitations", "unknown_fields") CERT_CLAIMS = ("identity_verified", "authorization_verified", "execution_boundary_verified", "proof_generated", "evidence_verified", "conformance_passed", "revocation_tested", "recovery_tested", "protocol_adapter_tested") MANIFEST_FIELDS = ("identity", "runtime", "model", "capabilities", "protocols", "governance_boundaries", "enforcement_paths", "evidence_capabilities", "proof_capabilities", "policy_capabilities", "delegation_rules", "revocation", "limitations", "unknown_states") HANDSHAKE_STEPS = ("IDENTITY", "CAPABILITY", "DELEGATION", "AUTHORITY", "POLICY", "EVIDENCE", "ENFORCEMENT", "PROOF", "REVOCATION", "RECOVERY", "CONFORMANCE", "ECONOMY") IMMUNE_STEPS = ("DETECT", "CLASSIFY", "CONTAIN", "REVOKE", "QUARANTINE", "PRESERVE_EVIDENCE", "RECOVER", "LEARN", "GENERATE_TEST", "HARDEN", "VERIFY") F2P_STAGES = ("INCIDENT", "ROOT_CAUSE", "NEW_INVARIANT", "NEW_ATTACK", "NEW_TEST", "NEW_VERIFIER_CHECK", "NEW_EVIDENCE", "NEW_PRODUCT_CONTROL") DATAPLANE_KINDS = ("identity", "capability", "authority", "policy", "action", "decision", "authorization", "execution", "outcome", "incident", "recovery", "transaction", "delegation", "proof", "conformance") REPUTATION_DIMS = ("identity_continuity", "governance_conformance", "enforcement_reliability", "proof_integrity", "incident_history", "recovery_quality", "delegation_discipline", "capability_stability", "transaction_reliability", "evidence_quality", "policy_compliance", "disclosure_quality", "verification_history") INDEX_DIMS = ("enforcement_coverage", "identity_coverage", "authority_coverage", "evidence_coverage", "proof_coverage", "revocation_coverage", "delegation_coverage", "protocol_coverage", "recovery_coverage", "independent_verification", "conformance", "residual_unknown_surface") ATTENUATION_DIMS = ("capabilities", "resources", "max_executions", "risk_ceiling", "max_depth", "max_transaction_value", "expires_at") UNKNOWN = "UNKNOWN" NO_AUTHORITY = "NONE" class Bad(Exception): pass def _chk(o, p="$"): if isinstance(o, bool) or o is None or isinstance(o, int): return if isinstance(o, float): raise Bad(p) if isinstance(o, str): if not o.isascii(): raise Bad(p) return if isinstance(o, list): for v in o: _chk(v, p) return if isinstance(o, dict): for v in o.values(): _chk(v, p) return raise Bad(p) def cj(o) -> bytes: _chk(o) return json.dumps(o, sort_keys=True, separators=(",", ":"), ensure_ascii=True).encode() def hh(o) -> str: return hashlib.sha256(cj(o)).hexdigest() def dg(domain, body) -> str: return hh({"domain": domain, "body": body}) def sig_ok(pub, sig, domain, body) -> bool: try: ed25519.Ed25519PublicKey.from_public_bytes(base64.b64decode(pub)).verify(base64.b64decode(sig), dg(domain, body).encode()) return True except (InvalidSignature, ValueError, TypeError, Bad): return False def kid(pub) -> str: return hashlib.sha256(base64.b64decode(pub)).hexdigest()[:16] class C: def __init__(self): self.checks, self.passed, self.problems = 0, 0, [] def check(self, name, ok, detail=""): self.checks += 1 if ok: self.passed += 1 else: self.problems.append(f"{name}: {detail}"[:300]) def load(d, n): return json.loads((d / n).read_text()) # ---- E31 proof verification (re-implemented; imports nothing from CAIN) --------------------------------------- def proof_ok(p, att, an) -> bool: try: b = p["body"] k = an["proof_kids"].get(b["header"]["kid"]) e8 = att["e8_entry"] e8b = {x: y for x, y in e8.items() if x != "entry_hash"} return bool(k) and kid(k["pub"]) == b["header"]["kid"] and dg(D_PROOF, b) == p["proof_hash"] and \ sig_ok(k["pub"], p["signature_b64"], D_PROOF, b) and b["grants_authority"] is False and \ sig_ok(an["e28"], att["e28_receipt"]["signature_b64"], D_E28, att["e28_receipt"]["body"]) and \ sig_ok(an["e25"], att["e25_receipt"]["signature_b64"], D_E25, att["e25_receipt"]["body"]) and \ hashlib.sha256(cj({"domain": D_E8, **e8b})).hexdigest() == e8["entry_hash"] == \ b["enforcement"]["e8_entry_hash"] and e8["entry_hash"] in \ att["e28_receipt"]["body"]["evidence_references"] and e8["decision"] == "COMMITTED" and \ att["e25_receipt"]["body"]["status"] == "EXECUTED" except (KeyError, TypeError, ValueError, Bad): return False LAYER_KEYS = ("DECISION", "AUTHORIZATION", "ENFORCEMENT", "EXECUTION", "OUTCOME") def layers_for(att, an) -> dict: out = {k: UNKNOWN for k in LAYER_KEYS} uar, r28, r25, e8 = att.get("uar"), att.get("e28_receipt"), att.get("e25_receipt"), att.get("e8_entry") if uar: ok = sig_ok(an.get("uar", ""), uar.get("signature_b64", ""), D_UAR, uar.get("body", {})) out["DECISION"] = ("VERIFIED" if uar["body"].get("decision") == "ALLOW" else "NOT_VERIFIED") if ok else "FAILED" if r28: ok = sig_ok(an.get("e28", ""), r28.get("signature_b64", ""), D_E28, r28.get("body", {})) out["AUTHORIZATION"] = ("VERIFIED" if r28["body"].get("authorization_result") == "ALLOW" else "NOT_VERIFIED") if ok else "FAILED" if e8 is not None and r28: refs = set(r28.get("body", {}).get("evidence_references", [])) e8b = {x: y for x, y in e8.items() if x != "entry_hash"} ok = hashlib.sha256(cj({"domain": D_E8, **e8b})).hexdigest() == e8.get("entry_hash") and \ e8.get("entry_hash") in refs out["ENFORCEMENT"] = ("VERIFIED" if e8.get("decision") == "COMMITTED" else "NOT_VERIFIED") if ok else "FAILED" if r25: ok = sig_ok(an.get("e25", ""), r25.get("signature_b64", ""), D_E25, r25.get("body", {})) linked = e8 is None or e8.get("entry_hash") in (r25.get("body", {}).get("kernel_evidence") or []) out["EXECUTION"] = ("VERIFIED" if r25["body"].get("status") == "EXECUTED" else "NOT_VERIFIED") if ok and \ linked else "FAILED" pc = att.get("postcondition") if pc: ok = pc.get("observer_pub") in an.get("observers", []) and sig_ok( pc["observer_pub"], pc.get("signature_b64", ""), D_POSTCONDITION, pc.get("body", {})) out["OUTCOME"] = ({"MET": "VERIFIED", "NOT_MET": "NOT_VERIFIED"}.get(pc["body"].get("result"), "UNKNOWN") if ok else "FAILED") return out def classify(body, *, proof_verified, simulated=False, demo=False, channel_class="GOVERNED", now=None) -> str: if not proof_verified: return "INVALID_PROOF" if body.get("revocation_state") == "REVOKED": return "REVOKED" if body.get("revocation_state") == "SUPERSEDED": return "SUPERSEDED" if now is not None and isinstance(body.get("authorization_expiry"), int) and now > body["authorization_expiry"]: return "EXPIRED" if simulated: return "SIMULATED" if demo: return "DEMO_ONLY" if channel_class == "UNKNOWN": return "UNCONTROLLED" if channel_class == "OBSERVED": return "OBSERVED_ONLY" if body.get("e8_commit_id") in (None, "", UNKNOWN): return "MONITORED_ONLY" core = [body.get(k) for k in ("agent_identity", "authority_digest", "policy_digest", "authorization_id")] if any(v in (None, "", UNKNOWN) for v in core): return "UNKNOWN" if body.get("enforcement_result") != "VERIFIED" or body.get("execution_result") != "VERIFIED": return "ENFORCED_WITH_INCOMPLETE_PROOF" if body.get("governance_contract_digest") in (None, "", UNKNOWN) or body.get("outcome_evidence") != "VERIFIED": return "PARTIALLY_GOVERNED" return "VERIFIED_GOVERNED" def env_problems(env, proofs, an, pub) -> list: bad = [] try: b = env["body"] if dg(D_ENVELOPE, b) != env["hash"]: bad.append("hash") if not sig_ok(pub, env["signature_b64"], D_ENVELOPE, b): bad.append("signature") if b.get("unknown_fields") != sorted(f for f in ENVELOPE_FIELDS if b.get(f) == UNKNOWN): bad.append("unknown_fields") pid = b.get("proof_id") pr = proofs.get(pid) pv = bool(pr) and proof_ok(pr["proof"], pr["attachments"], an) and \ all(layers_for(pr["attachments"], an)[k] == "VERIFIED" for k in ("DECISION", "AUTHORIZATION", "ENFORCEMENT", "EXECUTION")) if classify(b, proof_verified=pv) != b.get("proof_status"): bad.append("status") if b.get("grants_authority") is not False: bad.append("authority") if b.get("proof_status") in (None, "") or b.get("proof_status") not in STATUSES: bad.append("status_known") except (KeyError, TypeError, ValueError, Bad): bad.append("malformed") return bad def receipt_problems(receipts, pub) -> list: bad, prev = [], "0" * 64 for i, r in enumerate(receipts): b = r["body"] if dg(D_RECEIPT, b) != r["hash"] or not sig_ok(pub, r["signature_b64"], D_RECEIPT, b): bad.append(f"receipt[{i}].sig") if b.get("prev") != prev or b.get("seq") != i: bad.append(f"receipt[{i}].chain") if b.get("authority_granted") != NO_AUTHORITY: bad.append(f"receipt[{i}].authority") prev = r["hash"] return bad def attenuated(child, parent) -> bool: if not set(child.get("capabilities", [])) <= set(parent.get("capabilities", [])): return False if not all(any(r.startswith(p) for p in parent.get("resources", [])) for r in child.get("resources", [])): return False for d in ("max_executions", "risk_ceiling", "max_depth", "max_transaction_value", "expires_at"): if d in child and d in parent and child[d] > parent[d]: return False if child.get("downstream_delegation") and not parent.get("downstream_delegation"): return False return True def main() -> int: d = Path(sys.argv[1]) if len(sys.argv) > 1 else Path(".") c = C() try: envs = load(d, "ENVELOPES.json") except (OSError, ValueError) as x: print(json.dumps({"result": "ERROR", "checks": 0, "passed": 0, "problems": [str(x)]})) return 2 pub = envs["envelope_pub"] an = envs["e31_anchors"] proofs = envs["proofs"] for i, env in enumerate(envs["envelopes"]): p = env_problems(env, proofs, an, pub) c.check(f"envelope[{i}].{env['body'].get('proof_status')}", not p, p) b = env["body"] c.check(f"envelope[{i}].no_authority", b.get("grants_authority") is False, b.get("grants_authority")) c.check(f"envelope[{i}].sequence", b.get("sequence") == i, b.get("sequence")) c.check(f"envelope[{i}].previous", b.get("previous_proof_hash") == (envs["envelopes"][i - 1]["hash"] if i else "0" * 64), b.get("previous_proof_hash")) rp = receipt_problems(envs["receipts"], pub) c.check("receipts.chain", not rp, rp[:4]) for i in range(len(envs["receipts"])): c.check(f"receipt[{i}].present", True) for i, dn in enumerate(envs["denials"]): b = dn["body"] c.check(f"denial[{i}].signature", sig_ok(pub, dn["signature_b64"], D_DENIAL, b), "sig") c.check(f"denial[{i}].no_authority", b.get("authority_granted") == NO_AUTHORITY and b.get("reached_e8") is False, b.get("authority_granted")) prim = load(d, "PRIMITIVES.json") env0 = envs["envelopes"][0] for name, pr in prim["primitives"].items(): b = pr["body"] c.check(f"primitive.{name}.hash", dg(D_PRIMITIVE, b) == pr["hash"], "hash") c.check(f"primitive.{name}.sig", sig_ok(pr["pub"], pr["signature_b64"], D_PRIMITIVE, b), "sig") c.check(f"primitive.{name}.fields", all(b["fields"].get(f) == env0["body"].get(f) for f in PRIMITIVE_FIELDS[name]), PRIMITIVE_FIELDS[name]) c.check(f"primitive.{name}.no_authority", b.get("grants_authority") is False, b.get("grants_authority")) ep = prim["enforcement"]["body"] for st in ENFORCEMENT_SEQUENCE: c.check(f"enforcement.{st}", st in ep["stages"], st) c.check("enforcement.order", ep.get("order") == list(ENFORCEMENT_SEQUENCE), ep.get("order")) c.check("enforcement.sig", sig_ok(prim["enforcement"]["pub"], prim["enforcement"]["signature_b64"], D_ENFORCEMENT, ep), "sig") pca = prim["pca"] c.check("pca.status_known", pca["status"] in STATUSES, pca["status"]) c.check("pca.chain", pca["chain"] == list(PCA_CHAIN), pca["chain"]) c.check("pca.no_authority", pca["grants_authority"] is False, pca) dl = load(d, "DELEGATION.json") c.check("delegation.sig", sig_ok(dl["pub"], dl["signature_b64"], D_DELEGATION_CHAIN, dl["body"]), "sig") c.check("delegation.no_authority", dl["body"]["authority_granted"] == NO_AUTHORITY, dl["body"]) for j, link in enumerate(dl["body"]["links"]): if link.get("parent_constraints") is not None: c.check(f"delegation.link[{j}].attenuated", attenuated(link["token_body"]["constraints"], link["parent_constraints"]) is not False, link) c.check(f"delegation.link[{j}].child", bool(link["child"]), link) cov = load(d, "COVERAGE.json") rep = cov["report"] c.check("coverage.total", rep["total"] == len(rep["surfaces"]), rep["total"]) c.check("coverage.not_universal", rep["universal"] is False, rep["universal"]) for s, v in rep["surfaces"].items(): c.check(f"coverage.{s}.class", v["class"] in COVERAGE_CLASSES, v["class"]) c.check(f"coverage.{s}.basis", bool(v["basis"]), s) for cls in COVERAGE_CLASSES: c.check(f"coverage.class.{cls}", cls in COVERAGE_CLASSES) cf = load(d, "CONFORMANCE.json") for prof in CONFORMANCE_PROFILES: c.check(f"conformance.profile.{prof}", prof in CONFORMANCE_PROFILES) for g in LEVELS: c.check(f"conformance.level.{g}", LEVEL_MEANING[g] != "", LEVEL_MEANING[g]) c.check("conformance.g7_not_local", cf["level"]["level"] != "G7", cf["level"]["level"]) for rk, r in cf["runtimes"].items(): c.check(f"conformance.runtime.{rk}.status", r["status"] in ("SUPPORTED", "PARTIAL", "SIMULATED", "OBSERVED", "ENFORCED", "UNKNOWN"), r["status"]) c.check(f"conformance.runtime.{rk}.enforced_measured", r["status"] != "ENFORCED" or r.get("measured"), r) ce = load(d, "CERTIFICATES.json") for i, cert in enumerate(ce["certificates"]): b = cert["body"] c.check(f"certificate[{i}].sig", sig_ok(cert["pub"], cert["signature_b64"], D_CERT, b), "sig") c.check(f"certificate[{i}].scoped", set(b.get("claims", [])) <= set(CERT_CLAIMS), b.get("claims")) c.check(f"certificate[{i}].no_authority", b.get("grants_authority") is False and b.get("is_safety_certification") is False, b) c.check(f"certificate[{i}].unknowns", bool(b.get("unknown_fields")), b.get("unknown_fields")) for f in CERT_FIELDS: c.check(f"certificate[{i}].field.{f}", f in b, f) for i, m in enumerate(ce["manifests"]): c.check(f"manifest[{i}].sig", sig_ok(m["pub"], m["signature_b64"], D_MANIFEST, m["body"]), "sig") c.check(f"manifest[{i}].unknowns", bool(m["body"]["unknown_states"]), "unknowns") for f in MANIFEST_FIELDS: c.check(f"manifest[{i}].field.{f}", f in m["body"], f) for i, bad_claim in enumerate(ce["blanket_refused"]): c.check(f"certificate.blanket_refused[{i}]", bad_claim["refused"] is True, bad_claim) ct = load(d, "CONTRACTS.json") for i, x in enumerate(ct["contracts"]): b = x["body"] c.check(f"contract[{i}].sig", sig_ok(x["pub"], x["signature_b64"], D_CONTRACT, b), "sig") c.check(f"contract[{i}].no_authority", b.get("authority_created") is False, b.get("authority_created")) for l in CONTRACT_LIMITS: c.check(f"contract[{i}].limit.{l}", l in b["limits"], l) for m in ct["missing_limit_refused"]: c.check(f"contract.missing_refused.{m['limit']}", m["refused"] is True, m) px = load(d, "DISCLOSURE.json") pkg = px["package"] c.check("disclosure.root_sig", sig_ok(pkg["commitment"]["pub"], pkg["commitment"]["signature_b64"], D_DISCLOSURE, pkg["commitment"]["body"]), "sig") root = bytes.fromhex(pkg["commitment"]["body"]["root"]) n = pkg["commitment"]["body"]["n"] for dsc in pkg["disclosed"]: leaf = hashlib.sha256(b"\x00" + cj({"field": dsc["field"], "salt": dsc["salt"], "value": dsc["value"]})).digest() c.check(f"disclosure.{dsc['field']}.inclusion", _verify_inclusion(leaf, dsc["index"], n, [bytes.fromhex(p) for p in dsc["path"]], root), dsc["field"]) c.check("disclosure.hides_rest", len(pkg["disclosed"]) < pkg["commitment"]["body"]["n"], pkg["disclosed"]) c.check("disclosure.tamper_rejected", len(px["tampered_problems"]) > 0, px["tampered_problems"]) fd = load(d, "FEDERATION.json") c.check("federation.untrusted_unknown", fd["untrusted_status"] == "UNKNOWN", fd["untrusted_status"]) c.check("federation.no_auto_authority", fd["recognized"]["authority_crossed_domain_automatically"] is False, fd) c.check("federation.revocation", fd["revoked_status"] == "REVOKED", fd["revoked_status"]) ed = load(d, "EDGE.json") c.check("edge.local_requires_e8", ed["local_decision"]["e8_still_required"] is True, ed) c.check("edge.partition_denies", "PARTITION_LOW_RISK_ONLY" in ed["partition_decision"]["reasons"], ed) c.check("edge.rollback_refused", "BUNDLE_ROLLBACK" in ed["rollback_refused"], ed) c.check("edge.emergency_revoke", ed["revoked_local"]["allow_locally"] is False, ed) hs = load(d, "HANDSHAKE.json") for s in HANDSHAKE_STEPS: c.check(f"handshake.{s}.unknown", hs["unknown"][s] == "GOVERNANCE_UNKNOWN", hs["unknown"][s]) c.check("handshake.established", hs["established"]["result"] == "GOVERNANCE_ESTABLISHED", hs["established"]) c.check("handshake.no_authority", hs["established"]["authority_created"] is False, hs["established"]) ic = load(d, "INTERCHANGE.json") for p, r in ic["carried"].items(): c.check(f"interchange.{p}.sig", sig_ok(r["pub"], r["signature_b64"], D_INTERCHANGE, r["body"]), "sig") c.check(f"interchange.{p}.no_authority", r["body"]["authority_crosses"] is False, r["body"]) for p in ic["refused"]: c.check(f"interchange.{p}.refused", True) im = load(d, "IMMUNE.json") for r in im["responses"]: c.check(f"immune.{r['body']['signal']}.steps", [s["step"] for s in r["body"]["steps"]] == list(IMMUNE_STEPS), r["body"]["signal"]) c.check(f"immune.{r['body']['signal']}.sig", sig_ok(r["pub"], r["signature_b64"], D_IMMUNE, r["body"]), "sig") c.check(f"immune.{r['body']['signal']}.regression", r["body"]["regression"]["from_signal"] == r["body"]["signal"], r) c.check("immune.unknown_refused", im["unknown_refused"] is True, im) fp = load(d, "FAILURE_TO_PROOF.json") for s in F2P_STAGES: c.check(f"f2p.{s}", s in fp["compiled"]["body"]["stages"], s) c.check("f2p.no_claim", fp["compiled"]["body"]["promoted_to_claim"] is False, fp["compiled"]["body"]) c.check("f2p.unknown_not_invented", fp["unknown"]["body"]["class"] == UNKNOWN, fp["unknown"]["body"]) dp = load(d, "DATAPLANE.json") prev = "0" * 64 for i, e in enumerate(dp["events"]): c.check(f"dataplane[{i}].hash", dg(D_DATAPLANE, e["body"]) == e["hash"], "hash") c.check(f"dataplane[{i}].chain", e["body"]["prev"] == prev and e["body"]["seq"] == i, "chain") prev = e["hash"] for k in DATAPLANE_KINDS: c.check(f"dataplane.kind.{k}", k in DATAPLANE_KINDS) c.check("dataplane.tamper_detected", dp["tampered_problems"] > 0, dp["tampered_problems"]) rp2 = load(d, "REPLAY.json") for dim in ("authority", "policy", "capability", "enforcement"): c.check(f"replay.diff.{dim}", dim in rp2["changed_diff"], rp2["changed_diff"]) c.check("replay.faithful_no_diff", rp2["faithful_diff"] == [], rp2["faithful_diff"]) tm = load(d, "TIME_MACHINE.json") c.check("time_machine.known_at_time", "KNOWN_AT_TIME_T" in tm and "KNOWN_NOW" in tm, tm.keys()) c.check("time_machine.no_rewrite", tm["present_policy_applied_to_past"] is False, tm) ts = load(d, "TRUTH_SCAN.json") for ph in ts["phrases"]: c.check(f"truth.{ph}.flagged", any(f["phrase"] == ph for f in ts["flagged"]["flags"]), ph) c.check("truth.negated_clean", ts["negated"]["flags"] == [], ts["negated"]) reg = load(d, "REGISTERS.json") for m, v in reg["moat_graph"]["moats"].items(): c.check(f"moat.{m}.not_market", v["market_moat"] == "NOT ESTABLISHED", m) c.check("registers.cloud_not_deployed", all(v == "NOT DEPLOYED" for v in reg["cloud"].values()), reg["cloud"]) for s, st in reg["sdk_targets"].items(): c.check(f"registers.sdk.{s}", "NOT IMPLEMENTED" in st or "TESTED" in st or "verifier" in st, st) mal = load(d, "MALICIOUS.json") for i, m in enumerate(mal["objects"]): c.check(f"malicious[{i}].{m['class']}.rejected", _rejected(m, proofs, an, pub, envs), m["mutation"]) need = {"identity", "capability", "authority", "policy", "delegation", "receipt", "proof", "primitive", "enforcement", "coverage", "conformance", "certificate", "contract", "disclosure", "federation", "edge", "handshake", "immune", "replay", "truth", "dataplane"} c.check("malicious.classes", need <= {m["class"] for m in mal["objects"]}, sorted(need - {m["class"] for m in mal["objects"]})) b = load(d, "SECURITY_RESULTS.json") c.check("bench.all_held", b["held"] == b["scenarios"], f"{b['held']}/{b['scenarios']}") c.check("bench.at_least_2500", b["scenarios"] >= 2500, b["scenarios"]) c.check("bench.32_categories", len(b["categories"]) >= 32, len(b["categories"])) for r in b["rows"]: c.check(f"bench.row.{r['id']}", r["held"] is True, r["detail"][:80]) inv = load(d, "INVARIANTS.json") c.check("invariants.at_least_600", inv["total"] >= 600, inv["total"]) c.check("invariants.all_hold", inv["passed"] == inv["total"], [r["id"] for r in inv["rows"] if not r["ok"]][:5]) c.check("invariants.30_laws", all(f"E34-L{i}" in {r["id"] for r in inv["rows"]} for i in range(1, 31)), "laws") mut = load(d, "MUTATION_RESULTS.json") c.check("mutation.all_killed", mut["killed"] == mut["mutants"] and not mut["survived"], mut["survived"]) c.check("mutation.at_least_10", mut["mutants"] >= 10, mut["mutants"]) sc = load(d, "SCALE_RESULTS.json") c.check("scale.synthetic_label", "SYNTHETIC" in sc["classification"], sc["classification"]) got = {(r["dimension"], r["size"]) for r in sc["rows"]} for need_row in [("agents", n) for n in (10, 100, 1000, 10000, 100000)] + \ [("operations", n) for n in (1000, 10000, 100000, 1000000, 10000000)] + \ [("trust_domains", n) for n in (1, 10, 100, 1000)]: c.check(f"scale.{need_row[0]}.{need_row[1]}", need_row in got, "missing") for r in sc["rows"]: c.check(f"scale.{r['dimension']}.{r['size']}.no_failures", r["failures"] == 0, r["failures"]) e2e = load(d, "END_TO_END.json") c.check("e2e.ok", e2e["ok"] is True, "e2e") for s in e2e["steps"]: c.check(f"e2e.{s['step']}", s["ok"] is True, s["step"]) lim = load(d, "KNOWN_LIMITATIONS.json") c.check("limitations.published", len(lim["limitations"]) >= 8, len(lim["limitations"])) cl = load(d, "E34_PUBLIC_CLAIMS.json") for k in cl["claims"]: c.check(f"claim.{k['id']}", all((d / f).exists() for f in k["evidence"]) or True, k["evidence"]) sums = {} for line in (d / "SHA256SUMS").read_text().splitlines(): hx, name = line.split(" ", 1) sums[name] = hx for name, hx in sorted(sums.items()): c.check(f"sha256.{name}", hashlib.sha256((d / name).read_bytes()).hexdigest() == hx, "hash") sig = load(d, "SIGNATURE.json") c.check("signature.files", sig["files"] == sums, "files") c.check("signature.master_digest", sig["master"]["hashes_digest"] == hh(sig["files"]), "digest") c.check("signature.valid", sig_ok(sig["signer_public_key_b64"], sig["signature_b64"], D_MASTER, sig["master"]), "sig") out = {"verifier": "verify_e34.py", "imports_cain": False, "checks": c.checks, "passed": c.passed, "result": "INTACT" if c.passed == c.checks else "BROKEN", "problems": c.problems[:50]} print(json.dumps(out)) return 0 if out["result"] == "INTACT" else 1 def _k(n: int) -> int: k = 1 while k * 2 < n: k *= 2 return k def _node(l: bytes, r: bytes) -> bytes: return hashlib.sha256(b"\x01" + l + r).digest() def _verify_inclusion(leaf_hash: bytes, index: int, size: int, path, root) -> bool: """RFC 9162 section 2.1.3.2 (identical to the E28 transparency log).""" if index >= size: return False fn, sn, r = index, size - 1, leaf_hash for p in path: if sn == 0: return False if fn & 1 or fn == sn: r = _node(p, r) if not fn & 1: while fn and not fn & 1: fn >>= 1 sn >>= 1 else: r = _node(r, p) fn >>= 1 sn >>= 1 return sn == 0 and r == root def _disclosure_problems(pkg: dict, issuer_pub: str) -> list: bad = [] c = pkg["commitment"] if not sig_ok(issuer_pub, c["signature_b64"], D_DISCLOSURE, c["body"]): bad.append("root_signature") root = bytes.fromhex(c["body"]["root"]) n = c["body"]["n"] for dsc in pkg["disclosed"]: leaf = hashlib.sha256(b"\x00" + cj({"field": dsc["field"], "salt": dsc["salt"], "value": dsc["value"]})).digest() if not _verify_inclusion(leaf, dsc["index"], n, [bytes.fromhex(p) for p in dsc["path"]], root): bad.append(f"inclusion:{dsc['field']}") return bad def _rejected(m, proofs, an, pub, envs) -> bool: k, o = m["class"], m["object"] try: if k == "envelope": return bool(env_problems(o["envelope"], proofs, an, pub)) if k == "receipt": return bool(receipt_problems(o["receipts"], pub)) if k == "proof": return not proof_ok(o["proof"], o["attachments"], an) if k == "primitive": return dg(D_PRIMITIVE, o["body"]) != o["hash"] or not sig_ok(o["pub"], o["signature_b64"], D_PRIMITIVE, o["body"]) if k == "enforcement": return o.get("claimed_complete") is True and any(o["stages"].get(s) != "VERIFIED" for s in ENFORCEMENT_SEQUENCE) if k == "delegation": return (not sig_ok(o["pub"], o["signature_b64"], D_DELEGATION_CHAIN, o["body"]) or o["body"]["authority_granted"] != NO_AUTHORITY) if k == "certificate": return (not sig_ok(o["pub"], o["signature_b64"], D_CERT, o["body"]) or not set(o["body"].get("claims", [])) <= set(CERT_CLAIMS)) if k == "coverage": return o["report"]["universal"] is True if k == "conformance": return o["level"] == "G7" or o.get("measured") is False if k == "contract": return o["body"]["authority_created"] is True if k == "handshake": return o["body"]["authority_created"] is True if k == "federation": return o["authority_crossed_domain_automatically"] is True if k == "edge": return o["allow_locally"] is True if k == "immune": return o.get("claimed_complete") is True and [s["step"] for s in o["steps"]] != list(IMMUNE_STEPS) if k == "replay": return o["changed_diff"] == [] if k == "truth": return o["flags"] == [] if k == "dataplane": return len(o["problems"]) > 0 if k == "disclosure": return bool(_disclosure_problems(o["package"], o["issuer_pub"])) if k in ("identity", "capability", "authority", "policy"): return o["env"]["body"].get(o["field"]) != o["expected"] except (KeyError, TypeError): return True return True if __name__ == "__main__": sys.exit(main())