#!/usr/bin/env python3
"""Check CAIN-42's daily public anchors yourself. Python 3.8+, standard library only, no CAIN code.

CAIN-42 publishes a signed, hash-chained proof every 30 minutes for each live PBFT cluster. Once a day the head of
each chain is recorded in Sigstore Rekor, a public append-only log that FIRME AI CORPORATION does not run. This script:

  1. downloads the anchor list and the anchored proofs from the CAIN-42 site;
  2. recomputes each anchored proof's hash from its body (SHA-256 of canonical JSON);
  3. fetches the Rekor entry DIRECTLY FROM REKOR (not from us) and checks that it logs that hash, with that
     signature, under YOUR trust anchor key, with a valid RFC 9162 inclusion proof;
  4. checks that the chain published today still contains every anchored head unchanged;
  5. with --full-chain, downloads every proof and re-checks every link from proof 0 (and every signature, if the
     'cryptography' package is installed).

If anything was rewritten or backdated after an anchor, step 3 or 4 fails.

  python3 -I verify_daily_anchor.py --chain hourly-proof --trust-anchor <base64 Ed25519 key> [--all] [--full-chain]

Get the trust anchor from a source you trust (it is also listed in https://cainstudio.online/manifest.json).
Exit 0 = ANCHORED_AND_CONSISTENT; anything else names what failed.
"""
import argparse
import base64
import hashlib
import json
import sys
import time
import urllib.request

REKOR = "https://rekor.sigstore.dev"
SPKI_ED25519_PREFIX = bytes.fromhex("302a300506032b6570032100")


def get(url, body=None):
    req = urllib.request.Request(url, data=json.dumps(body).encode() if body is not None else None,
                                 headers={"Content-Type": "application/json", "Accept": "application/json",
                                          "User-Agent": "cain42-anchor-check/1"})
    with urllib.request.urlopen(req, timeout=60) as r:
        return json.loads(r.read().decode())


def canon(o):
    return json.dumps(o, sort_keys=True, separators=(",", ":"), ensure_ascii=True).encode()


def _h(b):
    return hashlib.sha256(b).digest()


def verify_inclusion(leaf_index, tree_size, leaf_hash, proof, root):
    """RFC 9162 section 2.1.3.2."""
    if leaf_index >= tree_size:
        return False
    fn, sn, r = leaf_index, tree_size - 1, leaf_hash
    for p in proof:
        if sn == 0:
            return False
        if fn & 1 or fn == sn:
            r = _h(b"\x01" + p + r)
            if not fn & 1:
                while fn and not fn & 1:
                    fn >>= 1
                    sn >>= 1
        else:
            r = _h(b"\x01" + r + p)
        fn >>= 1
        sn >>= 1
    return sn == 0 and r == root


def pem_to_raw(pem):
    der = base64.b64decode("".join(l for l in pem.strip().splitlines() if "-----" not in l))
    return der[12:] if len(der) == 44 and der.startswith(SPKI_ED25519_PREFIX) else None


def check_rekor(uuid, data_sha, sig_b64, anchor_raw, rekor):
    resp = get(f"{rekor}/api/v1/log/entries/{uuid}")
    ent = resp[next(iter(resp))]
    body_bytes = base64.b64decode(ent["body"])
    spec = json.loads(body_bytes).get("spec", {})
    problems = []
    if spec.get("data", {}).get("hash", {}).get("value") != data_sha:
        problems.append("Rekor logged a different hash")
    if spec.get("signature", {}).get("content") != sig_b64:
        problems.append("Rekor logged a different signature")
    pem = base64.b64decode(spec.get("signature", {}).get("publicKey", {}).get("content", "")).decode(errors="replace")
    if pem_to_raw(pem) != anchor_raw:
        problems.append("the logged key is not your trust anchor")
    pr = (ent.get("verification") or {}).get("inclusionProof") or {}
    if not pr or not verify_inclusion(int(pr["logIndex"]), int(pr["treeSize"]), _h(b"\x00" + body_bytes),
                                      [bytes.fromhex(x) for x in pr["hashes"]], bytes.fromhex(pr["rootHash"])):
        problems.append("no valid inclusion proof")
    return problems, int(ent.get("integratedTime", 0)), ent.get("logIndex")


def main(argv=None):
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--chain", default="hourly-proof", help="hourly-proof (cain-mr-01) or hourly-proof-mr02 (cain-mr-02)")
    ap.add_argument("--trust-anchor", required=True, help="base64 raw Ed25519 evidence-root key you obtained yourself")
    ap.add_argument("--base", default="https://clawx.click/evidence/")
    ap.add_argument("--rekor", default=REKOR)
    ap.add_argument("--all", action="store_true", help="check every anchor, not only the latest")
    ap.add_argument("--full-chain", action="store_true", help="download every proof and re-check every link")
    a = ap.parse_args(argv)
    anchor_raw = base64.b64decode(a.trust_anchor)
    if len(anchor_raw) != 32:
        print("trust anchor must be a 32-byte Ed25519 key in base64"); return 2
    base = a.base.rstrip("/") + "/" + a.chain + "/"
    anchors = get(base + "rekor-anchors.json")["anchors"]
    index = get(base + "index.json")
    if base64.b64decode(index["evidence_root_public_key_b64"]) != anchor_raw:
        print("FAIL: the chain's published key is not your trust anchor"); return 1
    listed = {p["file"]: p["proof_hash"] for p in index["proofs"]}
    fails = 0
    for an in (anchors if a.all else anchors[-1:]):
        proof = get(base + an["head_file"])
        h = hashlib.sha256(canon(proof["body"])).hexdigest()
        problems = []
        if h != an["head_proof_hash"] or h != proof["proof_hash"]:
            problems.append("the proof's body no longer hashes to the anchored value")
        if listed.get(an["head_file"]) != an["head_proof_hash"]:
            problems.append("today's chain index no longer lists this anchored head unchanged")
        rp, t, idx = check_rekor(an["rekor_uuid"], hashlib.sha256(an["head_proof_hash"].encode()).hexdigest(),
                                 proof["evidence_root_signature_b64"], anchor_raw, a.rekor)
        problems += rp
        when = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(t))
        print(f"{'OK  ' if not problems else 'FAIL'} {an['head_file']} ({an['proofs_in_chain']} proofs) "
              f"in Rekor index {idx} since {when}" + (f": {problems}" if problems else ""))
        fails += bool(problems)
    if a.full_chain:
        try:
            from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
            pk = Ed25519PublicKey.from_public_bytes(anchor_raw)
        except ImportError:
            pk = None
            print("note: 'cryptography' not installed; signatures were checked by Rekor at log time only")
        prev = hashlib.sha256(canon({"domain": "CAIN42/HOURLY-PROOF/v1", "genesis": index["cluster_id"]})).hexdigest()
        for i, row in enumerate(index["proofs"]):
            p = get(base + row["file"])
            h = hashlib.sha256(canon(p["body"])).hexdigest()
            bad = (h != row["proof_hash"] or p["body"].get("previous_proof_hash") != prev
                   or p["body"].get("n") != i)
            if pk and not bad:
                try:
                    pk.verify(base64.b64decode(p["evidence_root_signature_b64"]), h.encode())
                except Exception:  # noqa: BLE001
                    bad = True
            if bad:
                print(f"FAIL chain broken at {row['file']}"); fails += 1; break
            prev = h
            if i % 200 == 0:
                print(f"  ... {i + 1}/{len(index['proofs'])} proofs linked", flush=True)
        else:
            print(f"OK   full chain: {len(index['proofs'])} proofs linked from proof 0")
    print("VERDICT", "ANCHORED_AND_CONSISTENT" if not fails else "FAIL")
    return 0 if not fails else 1


if __name__ == "__main__":
    sys.exit(main())
