#!/usr/bin/env python3 """CAIN-42 E29 clean-room verifier. Imports NOTHING from CAIN. python3 verify_e29.py [bundle-dir] Re-derives from the published artifacts: the signed hash chain of transaction stages and their order; both signed transaction envelopes and their 24 bindings; the evidence root as the Merkle root of the transaction's receipts; the governance-receipt chain; that every treasury TRANSFER is backed by an ALLOW receipt of the same identity that reached the E8 kernel log; ledger chain and value conservation; directory records, capability passports (TESTED only with an in-scope ALLOW and an out-of-scope DENY), contract signatures by each party key, the negotiation chain and the governability manifest; bench, invariants, mutation, catastrophe and scale results; claims and bundle integrity. Prints one JSON object; exit 0 only when every check holds. """ 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_STAGE = "CAIN42/E29-TRANSACTION-STAGE/v1" D_TXENV = "CAIN42/E29-TRANSACTION-ENVELOPE/v1" D_LEDGER = "CAIN42/E29-LEDGER-ENTRY/v1" D_DIRECTORY = "CAIN42/E29-DIRECTORY-RECORD/v1" D_CAPPASS = "CAIN42/E29-CAPABILITY-PASSPORT/v1" D_MANIFEST = "CAIN42/E29-GOVERNABILITY-MANIFEST/v1" D_RECEIPT = "CAIN42/E28-GOVERNANCE-RECEIPT/v1" D_CONTRACT = "CAIN42/E27-MACHINE-CONTRACT/v1" D_NEGOTIATION = "CAIN42/E27-NEGOTIATION-OFFER/v1" D_MASTER = "CAIN42/E29-MASTER/v1" STAGES = ["DISCOVER", "IDENTIFY", "NEGOTIATE", "PROPOSE", "CONTRACT", "AUTHORIZE", "COMMIT", "EXECUTE", "SETTLE", "VERIFY", "RECORD", "REASSESS"] BINDINGS = ["transaction_id", "execution_identity", "principal", "agent_lineage", "counterparty_identity", "intent", "requested_action", "capabilities", "authority", "delegation", "policy", "risk", "consequence", "resource_limits", "economic_value", "temporal_limits", "nonce", "expiration", "protocol", "destination", "contract", "authorization_result", "execution_result", "evidence_root"] TARGETS = {"economic_abuse": 40, "transaction_replay": 20, "identity_cloning": 10, "delegation_amplification": 10, "counterparty_compromise": 10, "model_runtime_substitution": 20, "partition": 10, "revocation": 10, "recovery": 8, "protocol_interoperability": 10, "contract_negotiation": 15, "dispute": 5, "graph_reputation_discovery": 8, "software_economy": 6, "research_org_economy": 5} E2E_STEPS = ["AGENT_DISCOVERY", "IDENTITY_VERIFICATION", "CAPABILITY_VERIFICATION", "COUNTERPARTY_RISK", "NEGOTIATION", "MACHINE_CONTRACT", "DELEGATION", "TRANSACTION_AUTHORITY", "POLICY", "RISK", "CONSEQUENCE", "AUTHORIZATION", "E8_ACTION_COMMIT", "MCP_A2A_API", "EXECUTION", "SETTLEMENT", "VERIFICATION", "GOVERNANCE_RECEIPT", "EVIDENCE", "REPUTATION_UPDATE", "CONTINUOUS_REAUTHORIZATION"] def canonical(o) -> bytes: return json.dumps(o, sort_keys=True, separators=(",", ":"), ensure_ascii=True).encode() def h(o) -> str: return hashlib.sha256(canonical(o)).hexdigest() def digest(domain: str, body) -> str: return h({"domain": domain, "body": body}) def verify(pub: str, sig: str, domain: str, body) -> bool: try: ed25519.Ed25519PublicKey.from_public_bytes(base64.b64decode(pub)).verify( base64.b64decode(sig), digest(domain, body).encode()) return True except (InvalidSignature, ValueError, TypeError): return False def leaf(b: bytes) -> bytes: return hashlib.sha256(b"\x00" + b).digest() def mth(leaves): n = len(leaves) if n == 0: return hashlib.sha256(b"").digest() if n == 1: return leaves[0] k = 1 while k * 2 < n: k *= 2 return hashlib.sha256(b"\x01" + mth(leaves[:k]) + mth(leaves[k:])).digest() class Checker: 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: Path, n: str): return json.loads((d / n).read_text()) def main() -> int: d = Path(sys.argv[1] if len(sys.argv) > 1 else ".") c = Checker() try: art = load(d, "E2E_ARTIFACTS.json") e2e = load(d, "END_TO_END.json") except (OSError, ValueError) as x: print(json.dumps({"result": "ERROR", "checks": 0, "passed": 0, "problems": [str(x)]})) return 1 txpub = art["tx_pub"] # ---- stages prev, order = "0" * 64, [] for i, s in enumerate(art["stages"]): b = s["body"] c.check(f"stage[{i}].seq", b["seq"] == i, b["seq"]) c.check(f"stage[{i}].link", b["prev"] == prev, "broken link") c.check(f"stage[{i}].hash", digest(D_STAGE, b) == s["hash"], "hash") c.check(f"stage[{i}].signature", verify(txpub, s["signature_b64"], D_STAGE, b), "sig") c.check(f"stage[{i}].ok", b["ok"] is True, b["reasons"]) prev = s["hash"] order.append(b["stage"]) c.check("stages.order", order == STAGES, order) # ---- envelopes envs = art["envelopes"] c.check("envelopes.two_versions", [e["body"]["version"] for e in envs] == [1, 2], len(envs)) for e in envs: v = e["body"]["version"] c.check(f"envelope[v{v}].signature", e["signer_pub"] == txpub and verify(txpub, e["signature_b64"], D_TXENV, e["body"]), "sig") c.check(f"envelope[v{v}].digest", digest(D_TXENV, e["body"]) == e["digest"], "digest") c.check(f"envelope[v{v}].no_grant", e["body"]["grants_authority"] is False, "grant") for f in BINDINGS: c.check(f"envelope[v{v}].binds.{f}", f in e["body"], "missing") v1, v2 = envs[0]["body"], envs[1]["body"] c.check("envelope.v1_results_unknown", v1["execution_result"] == "UNKNOWN" and v1["evidence_root"] == "UNKNOWN", "v1 carries results") c.check("envelope.same_transaction", v1["transaction_id"] == v2["transaction_id"] and v1["nonce"] == v2["nonce"], "tx mismatch") c.check("envelope.authorized", v2["authorization_result"] == "WITHIN_AUTHORITY", v2["authorization_result"]) c.check("envelope.executed", v2["execution_result"] == "EXECUTED", v2["execution_result"]) root = mth([leaf(bytes.fromhex(x)) for x in art["transaction_receipts"]]).hex() c.check("envelope.evidence_root", v2["evidence_root"] == root == art["evidence_root"], "root") c.check("envelope.lineage_rooted_in_human", v2["agent_lineage"][0] == v2["principal"], v2["agent_lineage"]) # ---- receipts (E28 chain) R = art["receipts"] rpub, rs = R["signer_pub"], R["receipts"] prev = "0" * 64 for i, r in enumerate(rs): b = r["body"] c.check(f"receipt[{i}].chain", b["seq"] == i and b["prev"] == prev and digest(D_RECEIPT, b) == r["receipt_hash"], "chain") c.check(f"receipt[{i}].signature", verify(rpub, r["signature_b64"], D_RECEIPT, b), "sig") prev = r["receipt_hash"] by = {r["receipt_hash"]: r for r in rs} kev = set(art["kernel_evidence"]) for i, x in enumerate(art["transaction_receipts"]): r = by.get(x) c.check(f"tx_receipt[{i}].present", r is not None, x[:16]) if r: c.check(f"tx_receipt[{i}].allow_executed", r["body"]["authorization_result"] == "ALLOW" and r["body"]["execution_result"] == "EXECUTED", r["body"]["authorization_result"]) c.check(f"tx_receipt[{i}].reached_e8", any(e in kev for e in r["body"]["evidence_references"]), "no E8") # ---- ledger: chain, conservation, every transfer backed by an E8 ALLOW of the same identity tpub = art["treasury_pub"] prev, opening = "0" * 64, 0 allow = [r for r in rs if r["body"]["authorization_result"] == "ALLOW" and r["body"]["execution_result"] == "EXECUTED" and any(e in kev for e in r["body"]["evidence_references"])] for i, e in enumerate(art["ledger"]): b = e["body"] c.check(f"ledger[{i}].chain", b["seq"] == i and b["prev"] == prev and digest(D_LEDGER, b) == e["entry_hash"], "chain") c.check(f"ledger[{i}].signature", verify(tpub, e["signature_b64"], D_LEDGER, b), "sig") c.check(f"ledger[{i}].test_units", b["currency"] == "TEST-UNIT", b["currency"]) if b["kind"] == "OPENING_BALANCE": opening += b["amount"] else: c.check(f"ledger[{i}].backed_by_e8_receipt", any(r["body"]["execution_identity"] == b["identity"] and r["body"]["request_identity"] == b["request"] for r in allow), "unbacked transfer") c.check(f"ledger[{i}].positive", b["amount"] > 0, b["amount"]) prev = e["entry_hash"] c.check("ledger.conserved", opening == sum(art["balances"].values()), (opening, sum(art["balances"].values()))) c.check("ledger.has_transfers", sum(1 for e in art["ledger"] if e["body"]["kind"] == "TRANSFER") >= 2, "none") esc = {k: v for k, v in art["balances"].items() if k.startswith("escrow:")} c.check("escrow.drained", esc and all(v == 0 for v in esc.values()), esc) # ---- directory, passports, contract, negotiation, manifest ipub = art["issuer_pub"] for i, rec in enumerate(art["directory"]): c.check(f"directory[{i}].signature", rec["body"]["issuer_pub"] == ipub and verify(ipub, rec["signature_b64"], D_DIRECTORY, rec["body"]), "sig") c.check(f"directory[{i}].not_trust", rec["body"]["trust"] == "NOT_EVALUATED", rec["body"]["trust"]) for i, p in enumerate(art["passports"]): b = p["body"] c.check(f"passport[{i}].signature", verify(ipub, p["signature_b64"], D_CAPPASS, b), "sig") if b["status"] == "TESTED": rin, rout = by.get(b["evidence"][0]), by.get(b["evidence"][1]) c.check(f"passport[{i}].tested_in_scope_allow", rin and rin["body"]["authorization_result"] == "ALLOW", "no in-scope allow") c.check(f"passport[{i}].tested_out_of_scope_deny", rout and rout["body"]["authorization_result"] == "DENY", "no out-of-scope refusal") ct = art["contract"] c.check("contract.no_grant", ct["body"]["grants_authority"] is False, "grant") for role, pub in ct["party_pubs"].items(): c.check(f"contract.signed_by.{role}", verify(pub, ct["signatures"].get(role, ""), D_CONTRACT, ct["body"]), "sig") prev = "" for i, o in enumerate(art["negotiation"]): b = o["body"] c.check(f"negotiation[{i}].link", b["prev"] == prev and digest(D_NEGOTIATION, b) == o["hash"], "chain") c.check(f"negotiation[{i}].signature", verify(art["negotiation_pubs"].get(b["from"], ""), o["signature_b64"], D_NEGOTIATION, b), "sig") prev = o["hash"] m = art["manifest"] c.check("manifest.signature", verify(m["issuer_pub"], m["signature_b64"], D_MANIFEST, m["body"]), "sig") c.check("manifest.no_score", m["body"]["score"] is None and len(m["body"]["dimensions"]) == 14, "score") c.check("reputation.no_aggregate", art["reputation"]["aggregate"] is None, "aggregate") c.check("counterparty_risk.13_dimensions", len(art["counterparty_risk"] or {}) == 13, "dims") # ---- end to end got = [s["step"] for s in e2e["steps"]] c.check("e2e.steps", got == E2E_STEPS, got) for s in e2e["steps"]: c.check(f"e2e.{s['step']}", s["ok"] is True, s) # ---- bench / invariants / mutation / catastrophes / scale b = load(d, "SECURITY_RESULTS.json") c.check("bench.all_contained", b["contained"] == b["scenarios"], f"{b['contained']}/{b['scenarios']}") c.check("bench.at_least_250", b["scenarios"] >= 250, b["scenarios"]) c.check("bench.ids_distinct", len({r["id"] for r in b["rows"]}) == b["scenarios"], "dups") for cat, t in TARGETS.items(): n = sum(1 for r in b["rows"] if r["category"] == cat) c.check(f"bench.category.{cat}", n >= t, f"{n}<{t}") inv = load(d, "INVARIANTS.json") c.check("invariants.at_least_100", inv["total"] >= 100, inv["total"]) c.check("invariants.all_hold", inv["passed"] == inv["total"], [r["id"] for r in inv["rows"] if not r["ok"]][:5]) ids = {r["id"] for r in inv["rows"]} c.check("invariants.laws", all(f"E29-L{i}" in ids for i in range(1, 21)), "laws") c.check("invariants.stages", all(f"E29-S-{s}" in ids for s in STAGES), "stages") c.check("invariants.bindings", all(f"E29-B-{f}" in ids for f in BINDINGS), "bindings") mut = load(d, "MUTATION_RESULTS.json") c.check("mutation.all_killed", mut["killed"] == mut["mutants"] and not mut["survived"], mut["survived"]) cat = load(d, "CATASTROPHE_RESULTS.json") for r in cat["rows"]: c.check(f"catastrophe.{r['scenario']}.no_false_allow", r["false_allows"] == 0, r["false_allows"]) c.check(f"catastrophe.{r['scenario']}.evidence_intact", r["evidence_intact"] is True, "evidence") if r.get("false_denies_unaffected") is not None: c.check(f"catastrophe.{r['scenario']}.unaffected_still_served", r["false_denies_unaffected"] == 0, "collateral denial") c.check("catastrophe.all_ten", sorted(r["scenario"] for r in cat["rows"]) == list("ABCDEFGHIJ"), "scenarios") sc = load(d, "SCALE_RESULTS.json") c.check("scale.synthetic_label", "SYNTHETIC" in sc["classification"], "label") sizes = [r["agents"] for r in sc["rows"]] for n in (10, 100, 1000, 10000, 100000): c.check(f"scale.size_{n}", n in sizes, sizes) c.check("scale.no_failures", all(r["failures"] == 0 for r in sc["rows"]), [r["failures"] for r in sc["rows"]]) c.check("scale.virtual_labelled", all(r["kind"].startswith("VIRTUAL") for r in sc["rows"] if r["agents"] >= 100000), "label") reg = load(d, "REGISTERS.json") c.check("registers.no_competitor_facts", all(v == "UNKNOWN" for x in reg["competitive_radar"]["competitors"] for v in x["capabilities"].values()), "fabricated cell") c.check("registers.no_adopted_moat", not any(m["status"] == "ADOPTED" for m in reg["moat_graph"]["moats"]), "adopted") c.check("registers.no_novelty_claim", not any(x["novel"] for x in reg["novelty_gate"]["candidates"]), "novel") c.check("registers.no_production_product", not any(p["production_ready"] for p in reg["product_portfolio"]["products"]), "production") # ---- claims + integrity cl = load(d, "E29_PUBLIC_CLAIMS.json") for k in cl["claims"]: c.check(f"claim.{k['id']}", all((d / f).exists() for f in k["evidence"]), k["evidence"]) lim = load(d, "KNOWN_LIMITATIONS.json") c.check("limitations.published", len(lim["limitations"]) >= 8, len(lim["limitations"])) 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"] == h(sig["files"]), "digest") c.check("signature.valid", verify(sig["signer_public_key_b64"], sig["signature_b64"], D_MASTER, sig["master"]), "sig") out = {"verifier": "verify_e29.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 if __name__ == "__main__": sys.exit(main())