#!/usr/bin/env python3 """Clean-room verifier for the CAIN-42 Evolution 16 causal-world proof bundle. IMPORTS NO CAIN-42 CODE. Standard library plus `cryptography` (Ed25519). From the published JSON alone it re-derives: file hashes (MANIFEST), canonical serialization and domain-separated digests, temporal-interval digests and ordering, the causal world-state digest (rebuilt from its parts), every state-variable and event digest, the event-graph root, every causal/correlation relation digest and their separation, absence of causal cycles, prediction binding and non-fact status, counterfactual/intervention non-reality flags, calibration records and model demotion, the causal blast radius, temporal-authorization signatures and refusal reasons, the Q1-Q42 invariant matrix, the >=60-scenario bench, and the master proof signature. Usage: python3 verify_e16.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 = {"world": "CAIN42/E16-CAUSAL-WORLD-STATE/v1", "interval": "CAIN42/E16-TEMPORAL-INTERVAL/v1", "event": "CAIN42/E16-TEMPORAL-EVENT/v1", "prov": "CAIN42/E16-CAUSAL-PROVENANCE/v1", "relation": "CAIN42/E16-CAUSAL-RELATION/v1", "variable": "CAIN42/E16-STATE-VARIABLE/v1", "pred": "CAIN42/E16-PREDICTED-STATE/v1", "intervention": "CAIN42/E16-CAUSAL-INTERVENTION/v1", "calibration": "CAIN42/E16-CALIBRATION-RECORD/v1", "blast": "CAIN42/E16-CAUSAL-BLAST-RADIUS/v1", "tauth": "CAIN42/E16-TEMPORAL-AUTHORIZATION/v1", "convergence": "CAIN42/E16-CONVERGENCE/v1", "master": "CAIN42/E16-MASTER/v1"} CAUSAL_RELATIONS = ("CAUSES", "CONTRIBUTES_TO", "PREVENTS") CORRELATION_RELATIONS = ("CORRELATES_WITH",) REQUIRED_FILES = ("MANIFEST.json", "SCHEMAS.json", "CAIN42_EVOLUTION16_PROOF.json", "CAIN42_EVOLUTION16_MASTER_PROOF.json", "WORLD_STATE_EXAMPLES.json", "TEMPORAL_EVENT_EXAMPLES.json", "CAUSAL_GRAPH_EXAMPLES.json", "PREDICTION_EXAMPLES.json", "INTERVENTION_EXAMPLES.json", "COUNTERFACTUAL_EXAMPLES.json", "CALIBRATION_RESULTS.json", "BLAST_RADIUS_EXAMPLES.json", "TEMPORAL_AUTHORIZATION_EXAMPLES.json", "ATTACK_MANIFEST.json", "TEST_VECTORS.json", "PERFORMANCE.json", "LIMITATIONS.json", "LIMITATIONS.md", "verify_e16.py.txt", "REPRODUCE.txt", "index.html") FORBIDDEN = ("private_key", "private key", "-----begin", "secret_key", "password") def canon(o) -> bytes: return json.dumps(o, sort_keys=True, separators=(",", ":"), ensure_ascii=True).encode() def h(o) -> str: return hashlib.sha256(canon(o)).hexdigest() def dig(domain: str, fields: dict) -> str: return h({"domain": domain, **fields}) def sig_ok(pub_b64: str, sig_b64: str, domain: str, fields: dict) -> bool: try: ed25519.Ed25519PublicKey.from_public_bytes(base64.b64decode(pub_b64)).verify( base64.b64decode(sig_b64), dig(domain, fields).encode()) return True except (InvalidSignature, ValueError, TypeError): return False def strip(d: dict, *keys: str) -> dict: return {k: v for k, v in d.items() if k not in keys} class Checker: def __init__(self) -> None: self.checks, self.problems = [], [] def check(self, name: str, ok: bool, detail: str = "") -> None: self.checks.append({"check": name, "result": "PASS" if ok else "FAIL", "detail": detail}) if not ok: self.problems.append(name) def main(d: Path) -> int: C = Checker() load = lambda n: json.loads((d / n).read_text()) manifest = load("MANIFEST.json") presentation = set(manifest.get("unhashed_presentation", [])) | {"index.html"} bad = [n for n, want in manifest["files"].items() if n not in presentation and (not (d / n).exists() or hashlib.sha256((d / n).read_bytes()).hexdigest() != want)] C.check("manifest_file_hashes", not bad, ",".join(bad)) C.check("required_files_present", all((d / f).exists() for f in REQUIRED_FILES) and all(f in manifest["files"] for f in REQUIRED_FILES if f not in ("MANIFEST.json", "index.html")), "missing required") C.check("presentation_page_unhashed", presentation <= {"index.html"}, str(sorted(presentation))) # ---- canonical serialization & domain separation ---- tv = load("TEST_VECTORS.json") C.check("vectors.canonical_json", hashlib.sha256(canon(tv["canonical_json"]["input"])).hexdigest() == tv["canonical_json"]["sha256"], tv["canonical_json"]["sha256"]) sep = tv["domain_separation"] C.check("vectors.domain_separation", len(set(sep["digests"].values())) == len(sep["digests"]) and all(dig(n["domain"], sep["fields"]) == sep["digests"][n["domain"]] for n in tv["domains"]), str(list(sep["digests"].values()))[:80]) C.check("vectors.interval", dig(D["interval"], strip(tv["interval"], "digest")) == tv["interval"]["digest"], tv["interval"]["digest"]) C.check("vectors.negative_cases", tv["negative"]["certain_prediction"] == "PREDICTION_CANNOT_BE_CERTAIN" and tv["negative"]["reality_simulation_merge"] == "REALITY_SIMULATION_MERGE_REFUSED" and tv["negative"]["correlation_not_causal"] is True, str(tv["negative"])) # ---- temporal intervals ---- te = load("TEMPORAL_EVENT_EXAMPLES.json") iv = {x["label"]: x for x in te["intervals"]} C.check("interval.digests", all(dig(D["interval"], strip(x, "digest", "duration", "label")) == x["digest"] for x in te["intervals"]), "interval digest") C.check("interval.durations", all(abs(x["duration"] - (x["end"] - x["start"])) < 1e-9 for x in te["intervals"]), "dur") o = te["ordering"] C.check("interval.ordering", o["a_before_b"] and o["b_after_a"] and not o["a_overlaps_b"] and o["a_during_0_5"], str(o)) C.check("interval.authority_none", te["authority"] == "NONE", te["authority"]) # ---- causal world state (rebuilt from its parts) ---- we = load("WORLD_STATE_EXAMPLES.json") core, vars_, events, rels, exp = we["world_core"], we["variables"], we["events"], we["relations"], we["expected"] var_digests = {v["name"]: dig(D["variable"], v) for v in vars_} C.check("world.variable_digests", var_digests == exp["variable_digests"], "variable digests") ev_digests = {e["event_id"]: dig(D["event"], e) for e in events} C.check("world.event_digests", all(dig(D["event"], e) == ev_digests[e["event_id"]] for e in events), "event digests") rel_digests = {i: dig(D["relation"], r) for i, r in enumerate(rels)} event_root = h({"events": sorted(ev_digests.values()), "relations": sorted(rel_digests.values())}) C.check("world.event_root", event_root == exp["event_root"], event_root[:16]) body = {"world_id": core["world_id"], "tenant": core["tenant"], "version": core["version"], "branch_id": core["branch_id"], "kind": core["kind"], "created_at": core["created_at"], "parent_version": core["parent_version"], "parent_digest": core["parent_digest"], "entities": core["entities"], "variables": var_digests, "event_root": event_root, "constraints": core["constraints"], "environment": core["environment"], "interventions": core["interventions"], "outcomes": core["outcomes"], "uncertainty": core["uncertainty"]} C.check("world.digest_rebuilt", dig(D["world"], body) == exp["world_digest"], exp["world_digest"][:16]) C.check("world.version", exp["world_version"] == core["version"], str(core["version"])) C.check("world.reality_kind", core["kind"] == "REALITY", core["kind"]) C.check("world.authority_none", we["authority"] == "NONE", we["authority"]) # ---- causal graph ---- cg = load("CAUSAL_GRAPH_EXAMPLES.json") C.check("graph.relation_digests", all(dig(D["relation"], {k: r[k] for k in ("src", "dst", "relation", "confidence", "uncertainty", "provenance")}) == r["digest"] for r in cg["relations"]), "relation digest") causal = [r for r in cg["relations"] if r["relation"] in CAUSAL_RELATIONS] corr = [r for r in cg["relations"] if r["relation"] in CORRELATION_RELATIONS] C.check("graph.causal_correlation_separate", len(causal) == cg["causal_count"] and len(corr) == cg["correlated_count"] and all(not r["is_causal"] for r in corr), f"causal={len(causal)} corr={len(corr)}") C.check("graph.no_correlation_as_causal", all(r["relation"] not in CAUSAL_RELATIONS for r in corr), "correlation causal?") # independent causal cycle check (edges only among published events) adj: dict = {} for r in causal: adj.setdefault(r["src"], []).append(r["dst"]) colour, cyc = {}, [] def visit(n, stack): colour[n] = 1 for m in adj.get(n, []): if colour.get(m, 0) == 1: cyc.append(stack[stack.index(m):] + [m] if m in stack else [m]) elif colour.get(m, 0) == 0: visit(m, stack + [m]) colour[n] = 2 for n in list(adj): if colour.get(n, 0) == 0: visit(n, [n]) C.check("graph.no_causal_cycles", not cyc, str(cyc)) ev_by_id = {e["event_id"]: e for e in events} C.check("graph.causal_temporal_order", all(ev_by_id[r["dst"]]["interval"]["start"] >= ev_by_id[r["src"]]["interval"]["start"] for r in causal if r["src"] in ev_by_id and r["dst"] in ev_by_id), "order") C.check("graph.valid", cg["valid"] is True and cg["authority"] == "NONE", str(cg["valid"])) C.check("graph.root", cg["graph_root"] == exp["event_root"], cg["graph_root"][:16]) # ---- prediction ---- pe = load("PREDICTION_EXAMPLES.json") p = pe["prediction"] C.check("prediction.digest", dig(D["pred"], strip(p, "digest", "is_fact", "expires_at")) == p["digest"], p["digest"][:16]) C.check("prediction.evidence_class", p["evidence_class"] == "PREDICTED", p["evidence_class"]) C.check("prediction.not_a_fact", p["is_fact"] is False and pe["authority"] == "NONE", "fact?") C.check("prediction.horizon", abs(p["expires_at"] - (p["issued_at"] + p["horizon"])) < 1e-9 and p["horizon"] > 0, "horizon") C.check("prediction.world_binding", p["world_digest"] == exp["world_digest"] and p["world_version"] == core["version"], "world") C.check("prediction.model_binding", p["model_digest"] == pe["model"]["model_digest"] and p["model_version"] == "1.0.0", "model") # ---- intervention / counterfactual ---- ie = load("INTERVENTION_EXAMPLES.json") rec = ie["intervention"] C.check("intervention.digest", dig(D["intervention"], strip(rec, "digest")) == rec["digest"], rec["digest"][:16]) C.check("intervention.counterfactual", rec["evidence_class"] == "COUNTERFACTUAL" and rec["is_fact"] is False, "cls") C.check("intervention.not_executed", rec["executed"] is False and rec["mutates_reality"] is False, "executed") C.check("intervention.branch_is_simulated", ie["counterfactual_branch"]["kind"] == "SIMULATED", ie["counterfactual_branch"]["kind"]) C.check("intervention.base_is_reality", rec["base_world"] == exp["world_digest"], "base") cfe = load("COUNTERFACTUAL_EXAMPLES.json") C.check("counterfactual.flags", cfe["executed"] is False and cfe["mutates_reality"] is False and cfe["never_promoted"] is True and cfe["evidence_class"] == "COUNTERFACTUAL", "flags") # ---- calibration ---- cal = load("CALIBRATION_RESULTS.json") r0 = cal["records"][0] C.check("calibration.record_digest", dig(D["calibration"], strip(r0, "digest")) == r0["digest"], r0["digest"][:16]) C.check("calibration.error_nonneg", r0["error"] >= 0, str(r0["error"])) C.check("calibration.authority_none", cal["model_score"]["authority"] == "NONE" and cal["authority"] == "NONE", "auth") C.check("calibration.influence_valid", cal["model_score"]["influence"] in cal["influence_levels"], cal["model_score"]["influence"]) C.check("calibration.demotion_rule", isinstance(cal["demotion_mae"], (int, float)) and cal["demotion_mae"] > 0, str(cal["demotion_mae"])) # ---- blast radius ---- bl = load("BLAST_RADIUS_EXAMPLES.json") C.check("blast.digest", dig(D["blast"], strip(bl, "digest", "schema")) == bl["digest"], bl["digest"][:16]) C.check("blast.authority_none", bl["authority"] == "NONE", bl["authority"]) C.check("blast.uncertainty_bounded", 0.0 <= bl["uncertainty"] <= 1.0 and 0.0 <= bl["propagated_confidence"] <= 1.0, "range") C.check("blast.levels_present", set(bl["levels"]) == {"DIRECT_EFFECT", "SECOND_ORDER_EFFECT", "DEPENDENCY_EFFECT", "SYSTEM_EFFECT"}, str(list(bl["levels"]))) # ---- temporal authorization ---- ta = load("TEMPORAL_AUTHORIZATION_EXAMPLES.json") lease = ta["lease"] C.check("tauth.signature", sig_ok(lease["issuer"], lease["signature_b64"], D["tauth"], ta["lease_body"]), "sig") C.check("tauth.bound_to_world", lease["world_digest"] == exp["world_digest"] and lease["world_version"] == core["version"], "world") C.check("tauth.window_valid", lease["valid_until"] > lease["valid_from"] and lease["horizon"] > 0, "window") dn = ta["denied"] C.check("tauth.governed_decision_denies", dn["decision"] == "DENY" and any("E8_BOUNDARY_NOT_CONFIGURED" in r for r in dn["reasons"]), str(dn["reasons"])) C.check("tauth.convergence_digest", dig(D["convergence"], {k: dn[k] for k in ("decision", "reasons", "world_version", "world_digest", "at")}) == dn["digest"], dn["digest"][:16]) C.check("tauth.authority_none", ta["authority"] == "NONE", ta["authority"]) # ---- invariants ---- proof = load("CAIN42_EVOLUTION16_PROOF.json") inv = proof["invariants"] C.check("invariants.count", inv["checked"] >= 42 and len(inv["checks"]) == inv["checked"], str(inv["checked"])) C.check("invariants.ids", [x["id"] for x in inv["checks"]] == [f"Q{i:02d}" for i in range(1, inv["checked"] + 1)], "ids") C.check("invariants.all_hold", inv["all_hold"] is True and not inv["failed"], str(inv["failed"])) C.check("invariants.entries_hold", all(x.get("holds") is True for x in inv["checks"]), str([x["id"] for x in inv["checks"] if not x.get("holds")])) C.check("invariants.failed_consistent", list(inv["failed"]) == [x["id"] for x in inv["checks"] if not x.get("holds")], str(inv["failed"])) # ---- adversarial bench ---- am = load("ATTACK_MANIFEST.json") C.check("bench.minimum", am["total"] >= 60 and len(am["attacks"]) == am["total"], str(am["total"])) C.check("bench.all_contained", am["all_contained"] is True and am["contained"] == am["total"], f"{am['contained']}/{am['total']}") C.check("bench.honest", am["real_world_attack_validation"] == "NOT_PERFORMED" and am["authority"] == "NONE", "honesty") C.check("bench.entries_contained", all(v["contained"] is True and v["state"] == "CONTAINED" for v in am["attacks"].values()), "entries") # ---- performance & limitations ---- perf = load("PERFORMANCE.json") C.check("performance.conditions", perf["conditions"]["concurrency"] == 1 and "in-process" in perf["conditions"]["workload"], "conditions") C.check("performance.results", perf["results"] and all("p50_us" in v and "p99_us" in v for v in perf["results"].values()), "results") lim = load("LIMITATIONS.json") C.check("limitations.classified", len(lim["limitations"]) >= 5 and all(x["status"] in ("NOT_IMPLEMENTED", "UNKNOWN", "UNVERIFIED", "NOT_PERFORMED") for x in lim["limitations"]), "limitations") # ---- master proof signature & key disclosure ---- master = load("CAIN42_EVOLUTION16_MASTER_PROOF.json") mbody = strip(master, "signature_b64", "signer_public_key_b64") C.check("master.signature", sig_ok(master["signer_public_key_b64"], master["signature_b64"], D["master"], mbody), "sig") C.check("master.says_tested", master["evidence_level"] == "TESTED" and master["signing_key_class"] == "EPHEMERAL", master["evidence_level"]) C.check("master.no_hardware_claim", master["status"]["HARDWARE_ATTESTATION"] == "UNKNOWN" and master["status"]["REAL_WORLD_INTEGRATION"] == "NOT_IMPLEMENTED", str(master["status"])) C.check("master.counts_match", master["invariants_checked"] == inv["checked"] and master["attacks_total"] == am["total"], "counts") blob = "".join((d / n).read_text(errors="ignore").lower() for n in manifest["files"] if n.endswith(".json")) C.check("no_forbidden_material", not any(f in blob for f in FORBIDDEN), "forbidden material present") passed = sum(1 for c in C.checks if c["result"] == "PASS") out = {"schema": "cain42.e16.verifier.v1", "result": "INTACT" if not C.problems else "FAILED", "checks": len(C.checks), "passed": passed, "problems": C.problems, "detail": C.checks} print(json.dumps(out)) return 0 if not C.problems else 1 if __name__ == "__main__": raise SystemExit(main(Path(sys.argv[1])))