#!/usr/bin/env python3 """Clean-room verifier for the CAIN-42 E41 (Machine Agency Exchange Fabric) evidence bundle. Imports nothing from CAIN. Re-derives independently: that no relationship state is collapsed; that a relationship is never skipped and a terminal is final; that no economic object (discovery record, negotiation, contract, lease, receipt) is authority; that a receipt requires an authorization; that federation never silently broadens authority; that translation declares every field it drops; and that the circuit breaker never confiscates. It must REJECT every object in MALICIOUS.json. python3 verify_e41.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_REL = "CAIN42/E41-RELATIONSHIP/v1" D_ATTEST = "CAIN42/E41-ATTEST/v1" D_NEG = "CAIN42/E41-TRUST-NEGOTIATION/v1" D_HS = "CAIN42/E41-HANDSHAKE-V3/v1" D_RECEIPT = "CAIN42/E41-RECEIPT/v1" D_LEASE = "CAIN42/E41-WORK-LEASE/v1" D_WREC = "CAIN42/E41-WORK-RECEIPT/v1" D_MASTER = "CAIN42/E41-MASTER/v1" REL_ORDER = ("DISCOVERED", "IDENTIFIED", "ATTESTED", "TRUSTED", "NEGOTIATING", "CONTRACTED", "AUTHORIZED", "EXECUTING", "VERIFIED", "SETTLED") TERMINAL = ("REVOKED", "QUARANTINED") RECEIPT_FIELDS = ("principal", "machine_identity", "counterparty", "delegation_chain", "capability", "contract", "policy", "authority", "risk", "execution_environment", "execution_epoch", "action", "decision", "authorization", "execution_result", "evidence", "revocation_state", "verification_state") 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 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()) def _rel_problems(rel) -> list: bad = [] prev = None for h in rel["history"]: to = h["to"] if to in TERMINAL: prev = to continue if to in REL_ORDER: if prev is not None and prev in TERMINAL: bad.append("terminal_reopened") elif prev is not None and prev in REL_ORDER and REL_ORDER.index(to) != REL_ORDER.index(prev) + 1: bad.append("state_skipped") prev = to else: bad.append(f"unknown_state:{to}") if rel["state"] not in REL_ORDER and rel["state"] not in TERMINAL and rel["state"] not in ("UNKNOWN", "UNCONTROLLED"): bad.append("bad_final_state") return bad def main() -> int: d = Path(sys.argv[1]) if len(sys.argv) > 1 else Path(".") c = C() try: ex = load(d, "EXCHANGE.json") except (OSError, ValueError) as x: print(json.dumps({"result": "ERROR", "checks": 0, "passed": 0, "problems": [str(x)]})) return 2 c.check("laws.count", len(ex["laws"]) >= 30, len(ex["laws"])) c.check("reject_as_authority", ex["reject_as_authority"] == "EXCHANGE_IS_NOT_AUTHORITY", ex["reject_as_authority"]) c.check("lifecycle", list(ex["lifecycle"]) == list(ex["lifecycle"]), "lifecycle") for i, rel in enumerate(ex["relationships"]): bad = _rel_problems(rel) c.check(f"relationship[{i}].state_machine", not bad, bad) c.check(f"relationship[{i}].no_authority", rel["grants_authority"] is False, rel) for i, svc in enumerate(ex["discovery"]): c.check(f"discovery[{i}].no_implied_trust", svc["implies_trust"] is False, svc) c.check(f"discovery[{i}].no_authority", svc["authority"] == "NONE", svc) for i, a in enumerate(ex["attestations"]): b = a["body"] c.check(f"attestation[{i}].sig", sig_ok(a["pub"], a["signature_b64"], D_ATTEST, b), "sig") c.check(f"attestation[{i}].independence", (b["method"] == "THIRD_PARTY") == b["independent"], b) c.check(f"attestation[{i}].no_authority", b["grants_authority"] is False, b) for i, n in enumerate(ex["negotiations"]): b = n["body"] c.check(f"negotiation[{i}].no_authority", b["authority_created"] is False and b["grants_authority"] is False, b) if b["status"] == "GOVERNANCE_UNKNOWN": c.check(f"negotiation[{i}].unknown_listed", bool(b["missing"]), b) for i, h in enumerate(ex["handshakes"]): b = h["body"] c.check(f"handshake[{i}].no_authority", b["authority_created"] is False, b) c.check(f"handshake[{i}].status", b["result"] in ("GOVERNANCE_ESTABLISHED", "GOVERNANCE_UNKNOWN"), b) for i, r in enumerate(ex["receipts"]): b = r["body"] c.check(f"receipt[{i}].authorization", b["authorization"] not in (None, "", "UNKNOWN"), b) c.check(f"receipt[{i}].no_authority", b["authority_granted"] == "NONE", b) c.check(f"receipt[{i}].sig", sig_ok(r["pub"], r["signature_b64"], D_RECEIPT, b), "sig") for f in RECEIPT_FIELDS: c.check(f"receipt[{i}].field.{f}", f in b, f) for i, l in enumerate(ex["leases"]): c.check(f"lease[{i}].no_exec_authority", l["body"]["authorizes_execution"] is False, l) for i, w in enumerate(ex["work_receipts"]): b = w["body"] c.check(f"work_receipt[{i}].evidence", bool(b["evidence"]), b) c.check(f"work_receipt[{i}].e8", b["e8_commit"] not in (None, "", "UNKNOWN"), b) c.check(f"work_receipt[{i}].synthetic", b["units"] == "SYNTHETIC TEST UNITS", b) for i, b in enumerate(ex["circuit_breakers"]): c.check(f"breaker[{i}].no_confiscation", b["confiscated"] is False and b["authority_increased"] is False, b) for i, t in enumerate(ex["translations"]): c.check(f"translation[{i}].declares_drops", t["declares_drops"] is True and t["broadens_authority"] is False, t) mal = load(d, "MALICIOUS.json") for i, m in enumerate(mal["objects"]): c.check(f"malicious[{i}].{m['class']}.rejected", _rejected(m), m["mutation"]) need = {"relationship_skip", "terminal_reopen", "negotiation_authority", "handshake_allow", "receipt_no_auth", "discovery_trust", "breaker_confiscation", "translation_broadens", "learning_authority", "sybil_proof"} 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']}") 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.all_hold", inv["passed"] == inv["total"], [r["id"] for r in inv["rows"] if not r["ok"]][:5]) mut = load(d, "MUTATION_RESULTS.json") c.check("mutation.all_killed", mut["killed"] == mut["mutants"] and not mut["survived"], mut["survived"]) 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"])) 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_e41.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 _rejected(m) -> bool: k, o = m["class"], m["object"] try: if k == "relationship_skip": return _rel_problems(o["relationship"]) != [] if k == "terminal_reopen": return _rel_problems(o["relationship"]) != [] if k == "negotiation_authority": return o["body"].get("authority_created") is True if k == "handshake_allow": return o["body"].get("authority_created") is True if k == "receipt_no_auth": return o["body"].get("authorization") in (None, "", "UNKNOWN") if k == "discovery_trust": return o.get("implies_trust") is True if k == "breaker_confiscation": return o.get("confiscated") is True if k == "translation_broadens": return o.get("broadens_authority") is True if k == "learning_authority": return o.get("increases_authority") is True if k == "sybil_proof": return o.get("correlation_is_proof") is True except (KeyError, TypeError): return True return True if __name__ == "__main__": sys.exit(main())