#!/usr/bin/env python3
"""tlay_verify.py: verify a TLAY result bundle or receipt offline, with trust anchors you pinned yourself.

    pip install "cryptography>=42"
    python3 tlay_verify.py tlay-result-rel_xxx.json --anchors demo.json [--strict] [--json]

One file, one dependency (`cryptography`), no network access. It recomputes, from the file alone:

  release_commit_signature      the release service signed exactly this receipt
  attestation_record_signature  the key authority signed the attestation verification record
  attestation_verdict           that record says PASS for this policy (SIMULATED in local simulation)
  workload_candidate_signature  the workload's receipt key, bound in that record, signed the result candidate
  layer_consistency             candidate, record and receipt name the same release, policy, program and result
  result_commitment             the result bytes and salt in the bundle open the signed commitment
                                (NOT_CHECKED for a receipt alone, or for a result sealed to a buyer unless that
                                buyer passes --buyer-id and --result-key)
  policy_authorization          the key authority's signed approval of this policy (or of the series it is a day of,
                                for this program) is in the deployment's log, signed before the key was released
                                (NOT_AVAILABLE for bundles exported before 2026-11-01)
  output_policy                 the result has only the fields its output schema allows, none that must never leave
                                the workload, names this release, policy and inputs, and keeps the policy's privacy
                                unit, epsilon, size and bounds (NOT_CHECKED without a readable result)
  transparency_inclusion        a signed tree head of the deployment's transparency log, and a Merkle path from it,
                                cover this exact receipt
  bundle_header                 the bundle's own copies of the release / receipt / policy identifiers, the policy
                                document (by hash) and the result digest agree with the signed receipt (bundles only)

Beside the checks (never in the verdict) it reports the upload receipts: CHECKED with how many receipts of the
devices' uploads the key authority held and the program checked the records it read against (a missing one stops
the run), NOT_CHECKED when that key authority takes none, as the signed attestation record states.

Fields no signature covers (exported_at, exported_by, policy_id, labels, statement, verification_report) are listed
as informational. The verdict is PASS, PARTIAL (a layer could not be checked: no result, no inclusion proof, or a
sealed result) or FAIL.

A PASS whose attestation is SIMULATED (a local simulation, no hardware evidence) is reported as such.

Exit code: 0 for PASS or PARTIAL, 1 for FAIL, 2 when the input cannot be read or `cryptography` is missing. --strict
accepts only a PASS with hardware attestation (every layer checked, none SIMULATED): use it as an acceptance gate. A
receipt shows who signed what; it is not a proof that the computation itself was correct.

--json prints a verification report (schema tlay-verification-report/v1), the same record compute.tlay.io/verify
offers for download: verdict, security mode, trust source and key ids, every check, what was not checked and why.

    python3 tlay_verify.py BUNDLE --anchors A --buyer-id buyer-1 --result-key buyer-1.key

opens a result sealed to that buyer (tlay-sealed-result/v1: HPKE RFC 9180 base mode, DHKEM X25519, HKDF-SHA256,
ChaCha20-Poly1305) on this machine, so result_commitment and output_policy are checked too. The key file holds the
buyer's 32-byte X25519 private key in base64; it is read, never printed or written. A key that does not open the
result, or a buyer id the result is not sealed to, makes result_commitment FAIL.

    python3 tlay_verify.py BUNDLE --anchors A --buyer-id buyer-1 --result-key buyer-1.key --result-out result.json

also writes the result bytes that matched the receipt's result_commitment to result.json (open or opened here), so
what you use is what was checked. The file must not exist yet (an existing file or symlink is never replaced), is
created with mode 0600, and is written only if the run exits 0 (with --strict: only a PASS with hardware
attestation). Nothing is written on FAIL; only the path and the length are printed, never the bytes or their hash.

    python3 tlay_verify.py --index evidence.json

checks every bundle in a published evidence index (compute.tlay.io/anchors/evidence.json, files in the same
directory) against the anchors file its entry names, and prints one line per run. The index is not trusted: a run
whose bundle's receipt is not the one its entry names is FAIL (index_receipt), and so is a missing file. Exit code 1
if any run fails.

Trust anchors are the two public keys (key authority, release service) of the deployment, published away from its
servers (https://compute.tlay.io/anchors/). Without --anchors the keys embedded in the bundle are used, which only
shows that the bundle is consistent with itself.

Mirrors tlay_contracts.receipts.verify_receipt and tlay_contracts.bundle.verify_bundle (same checks, same verdicts;
cross-checked against tests/vectors/receipt_verify_v1.json in the TLAY repository).
"""

from __future__ import annotations

import argparse
import base64
import hashlib
import json
import os
import re
from decimal import Decimal
import sys
from typing import Any, Optional

VERSION = "1.18.0"
SIG_PREFIX = b"TLAY-SIG\x00"
COMMIT_DOMAIN = "tlay/release-commit/v1"
ATTESTATION_RECORD_DOMAIN = "tlay/attestation-record/v1"
CANDIDATE_DOMAIN = "tlay/result-candidate/v1"
STH_DOMAIN = "tlay/sth/v1"
RESULT_COMMIT_PREFIX = b"TLAY-COMMIT\x00tlay/result-commitment/v1\x00"
BUNDLE_VERSION = "tlay-result-bundle/v1"
HEADER_IDS = ("release_id", "receipt_id", "policy_hash", "security_mode")
UNSIGNED_FIELDS = ("exported_at", "exported_by", "policy_id", "labels", "statement", "verification_report")
UNCHECKED_TRANSPARENCY = ("integrity", "label", "latest_sth", "policy_inclusion_proof", "statement")
MAX_BYTES = 4 * 1024 * 1024
MAX_SAFE_INTEGER = 2**53 - 1
MAX_DEPTH = 64  # containers nested deeper than this are refused (as tlay_crypto.canonical.MAX_JSON_DEPTH)


# ---------------------------------------------------------------- RFC 8785 for the values TLAY documents use
def canonical(v: Any) -> bytes:
    return _canon(v, 0).encode("utf-8")


def _canon(v: Any, depth: int) -> str:
    if isinstance(v, (list, dict)) and depth >= MAX_DEPTH:
        raise ValueError("document nesting too deep")
    if v is None or isinstance(v, bool):
        return json.dumps(v)
    if isinstance(v, int):
        if abs(v) > MAX_SAFE_INTEGER:
            raise ValueError("integer outside the I-JSON range")
        return str(v)
    if isinstance(v, float):
        raise ValueError("floats are not used in TLAY documents")
    if isinstance(v, str):
        v.encode("utf-8")  # a lone surrogate raises here
        return json.dumps(v, ensure_ascii=False)
    if isinstance(v, list):
        return "[" + ",".join(_canon(x, depth + 1) for x in v) + "]"
    if isinstance(v, dict):
        items = sorted(v.items(), key=lambda kv: kv[0].encode("utf-16-be"))  # UTF-16 code unit order (RFC 8785 3.2.3)
        return "{" + ",".join(json.dumps(k, ensure_ascii=False) + ":" + _canon(x, depth + 1) for k, x in items) + "}"
    raise ValueError("not a JSON value")


def sha256_hex(b: bytes) -> str:
    return hashlib.sha256(b).hexdigest()


def b64d(s: Any) -> bytes:
    if not isinstance(s, str):
        raise ValueError("expected base64 text")
    return base64.b64decode(s, validate=True)


def verify_domain(pub_b64: Any, domain: str, message: bytes, sig_b64: Any) -> bool:
    from cryptography.exceptions import InvalidSignature
    from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey

    try:
        pub = b64d(pub_b64)
        sig = b64d(sig_b64)
        if len(pub) != 32 or len(sig) != 64:
            return False
        Ed25519PublicKey.from_public_bytes(pub).verify(sig, SIG_PREFIX + domain.encode("ascii") + b"\x00" + message)
        return True
    except (InvalidSignature, ValueError, TypeError):
        return False


def _obj(v: Any) -> dict[str, Any]:
    return v if isinstance(v, dict) else {}


def _check(name: str, ok: bool, detail: str, simulated: bool = False) -> dict[str, str]:
    return {"name": name, "status": "FAIL" if not ok else ("SIMULATED" if simulated else "PASS"), "detail": detail}


# ---------------------------------------------------------------- receipt layers
def verify_receipt(receipt: Any, anchors: dict[str, Any], result: Optional[bytes] = None, salt: Optional[bytes] = None) -> list[dict[str, str]]:
    receipt = _obj(receipt)
    rs, ka = _obj(anchors.get("release_service")), _obj(anchors.get("key_authority"))
    out = []

    commit = _obj(receipt.get("commit"))
    try:
        body = {k: v for k, v in receipt.items() if k != "commit"}
        ok = (set(commit) == {"signature_alg", "key_id", "signature"} and commit["signature_alg"] == "Ed25519"
              and commit["key_id"] == rs.get("key_id") and verify_domain(rs.get("public_key"), COMMIT_DOMAIN, canonical(body), commit["signature"]))
    except (KeyError, ValueError, TypeError):
        ok = False
    out.append(_check("release_commit_signature", ok, f"Release service signature over the committed receipt (key {rs.get('key_id')})"))

    att = _obj(receipt.get("attestation_record"))
    rec = _obj(att.get("record"))
    try:
        ok = att.get("key_id") == ka.get("key_id") and verify_domain(ka.get("public_key"), ATTESTATION_RECORD_DOMAIN, canonical(rec), att.get("signature"))
    except (ValueError, TypeError):
        ok = False
    out.append(_check("attestation_record_signature", ok, "Key authority signature over the attestation verification record"))

    simulated = rec.get("provider") == "local_simulation"
    ev = rec.get("evidence_digest")
    out.append(_check(
        "attestation_verdict", rec.get("verdict") == "PASS" and rec.get("policy_hash") == receipt.get("policy_hash"),
        "Local simulation: no hardware isolation, evidence is produced by a test key" if simulated
        else f"Verifier {rec.get('verifier_version')} accepted {rec.get('provider')} evidence {ev[:16] if isinstance(ev, str) else ''}",
        simulated=simulated,
    ))

    cand = _obj(receipt.get("candidate"))
    payload = _obj(cand.get("payload"))
    try:
        ok = cand.get("receipt_public_key") == rec.get("receipt_public_key") and verify_domain(
            cand.get("receipt_public_key"), CANDIDATE_DOMAIN, canonical(payload), cand.get("signature"))
    except (ValueError, TypeError):
        ok = False
    out.append(_check("workload_candidate_signature", ok, "Workload receipt key (bound in the attestation record) signed the candidate"))

    try:
        rec_digest: Optional[str] = sha256_hex(canonical(rec))
    except ValueError:
        rec_digest = None
    consistent = (
        rec_digest is not None
        and payload.get("release_id") == receipt.get("release_id")
        and payload.get("policy_hash") == receipt.get("policy_hash")
        and payload.get("result_commitment") == receipt.get("result_commitment")
        and payload.get("snapshot_commitment") == receipt.get("snapshot_commitment")
        and payload.get("workload_measurement") == receipt.get("workload_digest") == rec.get("workload_measurement")
        and payload.get("attestation_record_digest") == rec_digest
    )
    out.append(_check("layer_consistency", consistent, "Candidate, attestation record and commit refer to the same release, policy, program and result"))

    if result is not None and salt is not None:
        ok = len(salt) == 32 and "rc1:" + sha256_hex(RESULT_COMMIT_PREFIX + salt + hashlib.sha256(result).digest()) == receipt.get("result_commitment")
        out.append(_check("result_commitment", ok, "The result bytes and salt in the file open the signed result commitment"))
    else:
        out.append({"name": "result_commitment", "status": "NOT_CHECKED", "detail": "No readable result in this file (receipt only, or sealed to a buyer)"})
    return out


# ---------------------------------------------------------------- transparency log (RFC 9162 inclusion)
def _leaf_hash(b: bytes) -> bytes:
    return hashlib.sha256(b"\x00" + b).digest()


def _node(left: bytes, right: bytes) -> bytes:
    return hashlib.sha256(b"\x01" + left + right).digest()


def verify_inclusion(index: Any, size: Any, leaf: bytes, proof: list[bytes], root: bytes) -> bool:
    if type(index) is not int or type(size) is not int or not 0 <= index < size:
        return False
    fn, sn, r = index, size - 1, leaf
    for p in proof:
        if sn == 0:
            return False
        if fn & 1 or fn == sn:
            r = _node(p, r)
            if not fn & 1:
                while True:
                    fn >>= 1
                    sn >>= 1
                    if fn & 1 or fn == 0:
                        break
        else:
            r = _node(r, p)
        fn >>= 1
        sn >>= 1
    return sn == 0 and r == root


# The deployment's one log (tlay_contracts.transparency.LOG_ID): a head or leaf of any other log id is not this log's
# (review 2026-11-17, D3). Anchors may pin it as transparency_log.log_id (review 2026-11-19); pinning another fails.
LOG_ID = "tlay-release-log-v1"


def pinned_log_ok(anchors: Any) -> bool:
    pinned = _obj(_obj(anchors).get("transparency_log")).get("log_id")
    return pinned is None or pinned == LOG_ID


def inclusion_status(proof: Any, receipt: dict[str, Any], release_pub: Any) -> str:
    if not isinstance(proof, dict):
        return "NOT_AVAILABLE"
    if not release_pub:
        return "NOT_CHECKED"
    try:
        sth = proof["sth"]
        if sth["sth"].get("log_id") != LOG_ID or proof["leaf"].get("log_id") != LOG_ID:
            return "FAIL"
        if not verify_domain(release_pub, STH_DOMAIN, canonical(sth["sth"]), sth["signature"]):
            return "FAIL"
        leaf_bytes = b64d(proof["leaf_b64"])
        if canonical(proof["leaf"]) != leaf_bytes:
            return "FAIL"
        path = [bytes.fromhex(p) for p in proof["proof"]]
        if not verify_inclusion(proof["leaf_index"], sth["sth"]["tree_size"], _leaf_hash(leaf_bytes), path, bytes.fromhex(sth["sth"]["root_hash"])):
            return "FAIL"
        leaf = proof["leaf"]
        ok = (leaf.get("type") == "release_committed" and leaf.get("receipt_digest") == sha256_hex(canonical(receipt))
              and leaf.get("result_commitment") == receipt.get("result_commitment") and leaf.get("release_id") == receipt.get("release_id"))
        return "PASS" if ok else "FAIL"
    except (KeyError, ValueError, TypeError, AttributeError):
        return "FAIL"


# ---------------------------------------------------------------- witnessed tree heads (docs/adr/0049)
COSIG_DOMAIN = "tlay/witness-cosig/v1"
COSIG_FIELDS = {"log_id", "tree_size", "root_hash", "log_key_id", "witness_id", "cosigned_at"}


def witnesses_of(anchors: Any) -> tuple[list[dict[str, Any]], int]:
    w = _obj(_obj(anchors).get("witnesses"))
    lst = [x for x in w.get("list") or [] if isinstance(x, dict) and isinstance(x.get("public_key"), str)] if isinstance(w.get("list"), list) else []
    th = w.get("threshold")
    return lst, (th if isinstance(th, int) and not isinstance(th, bool) and th >= 1 else 1)


def upload_receipts_status(receipt: Any) -> dict[str, Any]:
    """tlay_contracts.receipts.upload_receipts_status: what the attestation record states about upload receipts."""
    record = _obj(_obj(_obj(receipt).get("attestation_record")).get("record"))
    if "upload_receipts" not in record:
        return {"status": "NOT_CHECKED", "count": None,
                "detail": "The key authority took no upload receipts for this release (none configured), so the program did not check the records it read against receipts the devices hold"}
    ur = record["upload_receipts"]
    # From ADR 0057 the statement also carries the set's Merkle root, for the devices' own inclusion checks.
    if (not isinstance(ur, dict) or set(ur) not in ({"count", "sha256"}, {"count", "sha256", "merkle_root"}) or type(ur["count"]) is not int
            or ur["count"] < 0 or not all(isinstance(ur[k], str) and re.fullmatch(r"[0-9a-f]{64}", ur[k]) for k in ur if k != "count")):
        return {"status": "INVALID", "count": None, "detail": "The attestation record's statement of upload receipts is malformed"}
    return {"status": "CHECKED", "count": ur["count"],
            "detail": f"The key authority held {ur['count']} upload receipt(s) for this release; the program checked the sealed records against them before reading any (a missing one stops the run)"}


# ---------------------------------------------------------------- raw attestation evidence (docs/adr/0055)
# A copy of tlay_contracts.attestation_evidence.check_block (a unit test keeps the two in agreement), with RS256 done in
# plain integer arithmetic so this file needs nothing new.
EVIDENCE_FORMAT = "tlay-attestation-evidence/v1"
GOOGLE_CS_ISSUER = "https://confidentialcomputing.googleapis.com"
_SHA256_DIGEST_INFO = bytes.fromhex("3031300d060960864801650304020105000420")


def _b64url(s: str) -> bytes:
    return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))


def evidence_digest(evidence: Any, provider: str = "gcp_confidential_space") -> str:
    if provider == "local_simulation":
        return sha256_hex(canonical(evidence))
    return hashlib.sha256(json.dumps(evidence, sort_keys=True).encode("utf-8", "surrogatepass")).hexdigest()


def binding_digest(nonce: str, recipient_pk: str, receipt_pk: str) -> str:
    return hashlib.sha256(b"TLAY-BIND\x00tlay/attestation-binding/v1\x00" + canonical(
        {"challenge_nonce": nonce, "recipient_public_key": recipient_pk, "receipt_public_key": receipt_pk})).hexdigest()


def rs256_verify(jwk: Any, signing_input: bytes, signature: bytes) -> bool:
    try:
        if jwk.get("kty") != "RSA":
            return False
        n = int.from_bytes(_b64url(str(jwk["n"])), "big")
        e = int.from_bytes(_b64url(str(jwk["e"])), "big")
    except Exception:  # noqa: BLE001
        return False
    k = (n.bit_length() + 7) // 8
    if k < 256 or len(signature) != k or e < 3:
        return False
    s = int.from_bytes(signature, "big")
    if s >= n:
        return False
    t = _SHA256_DIGEST_INFO + hashlib.sha256(signing_input).digest()
    return pow(s, e, n).to_bytes(k, "big") == b"\x00\x01" + b"\xff" * (k - len(t) - 3) + b"\x00" + t


def check_attestation_evidence(block: Any, record: Any, audience: Optional[str] = None) -> tuple[str, list[str]]:
    if block is None:
        return "NOT_AVAILABLE", []
    record = _obj(record)
    problems: list[str] = []
    if not isinstance(block, dict) or set(block) != {"format", "provider", "evidence", "nonce", "jwk"} or block.get("format") != EVIDENCE_FORMAT:
        return "FAIL", ["the evidence block is not tlay-attestation-evidence/v1"]
    evidence, nonce = block["evidence"], block["nonce"]
    try:
        if evidence_digest(evidence, str(block["provider"])) != record.get("evidence_digest"):
            problems.append("the evidence does not hash to the record's evidence_digest")
    except (TypeError, ValueError):
        problems.append("the evidence is not serializable")
    if block["provider"] != record.get("provider"):
        problems.append("the evidence's provider is not the record's")
    if problems:
        return "FAIL", problems
    ev = _obj(evidence)
    if block["provider"] == "local_simulation":
        stmt = _obj(ev.get("statement"))
        if stmt.get("receipt_public_key") != record.get("receipt_public_key"):
            problems.append("the evidence binds another receipt key")
        elif not isinstance(nonce, str) or stmt.get("nonce_binding") != binding_digest(nonce, str(stmt.get("recipient_public_key")), str(stmt.get("receipt_public_key"))):
            problems.append("the nonce does not give the evidence's binding")
        return ("FAIL", problems) if problems else ("SIMULATED", [])
    if block["provider"] != "gcp_confidential_space":
        return "FAIL", [f"unknown provider {block['provider']!r}"]
    jwk = _obj(block["jwk"])
    try:
        h, pl, sg = str(ev.get("token")).split(".")
        header, claims, signing_input, sig = json.loads(_b64url(h)), json.loads(_b64url(pl)), (h + "." + pl).encode("ascii"), _b64url(sg)
    except Exception:  # noqa: BLE001
        return "FAIL", ["the token is not a JWT"]
    if header.get("alg") != "RS256" or header.get("kid") != jwk.get("kid"):
        problems.append("the token is not RS256 under the supplied key id")
    elif not rs256_verify(jwk, signing_input, sig):
        problems.append("the token's signature does not verify with the supplied key")
    c = _obj(_obj(claims.get("submods")).get("container"))
    want = _obj(record.get("claims"))
    if claims.get("iss") != GOOGLE_CS_ISSUER:
        problems.append("the token's issuer is not Google's Confidential Space")
    aud = claims.get("aud")
    if audience is not None and audience not in ([aud] if isinstance(aud, str) else aud if isinstance(aud, list) else []):
        problems.append("the token's audience is not the policy's")
    if c.get("image_digest") != record.get("workload_measurement"):
        problems.append("the token's image digest is not the record's workload measurement")
    for name in ("hwmodel", "swname", "dbgstat"):
        if claims.get(name) != want.get(name):
            problems.append(f"the token's {name} is not the record's")
    if claims.get("dbgstat") != "disabled-since-boot" or claims.get("swname") != "CONFIDENTIAL_SPACE" or claims.get("secboot") is not True:
        problems.append("the token does not state a production Confidential Space image with debugging off and secure boot")
    if ev.get("receipt_public_key") != record.get("receipt_public_key"):
        problems.append("the evidence binds another receipt key")
    nonces = claims.get("eat_nonce")
    nonces = [nonces] if isinstance(nonces, str) else [n for n in nonces if isinstance(n, str)] if isinstance(nonces, list) else []
    if not isinstance(nonce, str) or binding_digest(nonce, str(ev.get("recipient_public_key")), str(ev.get("receipt_public_key"))) not in nonces:
        problems.append("the token's eat_nonce does not bind the challenge to the workload's keys")
    return ("FAIL", problems) if problems else ("PASS", [])


def google_lists_kid(kid: Any) -> Optional[bool]:
    """--online: whether Google's Confidential Space JWKS lists this key id now (None when it cannot be fetched)."""
    import urllib.request

    try:
        with urllib.request.urlopen(GOOGLE_CS_ISSUER + "/.well-known/openid-configuration", timeout=10) as r:
            uri = json.loads(r.read(65536))["jwks_uri"]
        if not str(uri).startswith("https://"):
            return None
        with urllib.request.urlopen(uri, timeout=10) as r:
            keys = json.loads(r.read(262144)).get("keys") or []
        return any(isinstance(k, dict) and k.get("kid") == kid for k in keys)
    except Exception:  # noqa: BLE001
        return None


def head_witnessed_status(doc: Any, receipt: dict[str, Any], release_pubs: list[str], witnesses: list[dict[str, Any]], threshold: int) -> str:
    """PASS: the release's commit leaf is in a head the release service signed and that at least `threshold`
    distinct listed witnesses cosigned; NOT_AVAILABLE: no witnessed head covers it yet; NOT_CHECKED: no witnesses."""
    if not witnesses or threshold < 1:
        return "NOT_CHECKED"
    if not isinstance(doc, dict):
        return "NOT_AVAILABLE"
    try:
        if "PASS" not in [inclusion_status(doc, receipt, k) for k in release_pubs if k]:
            return "FAIL"
        sth = doc["sth"]["sth"]
        by_id = {w.get("witness_id"): w for w in witnesses}
        seen = set()
        for cos in doc.get("cosignatures") or []:
            body = _obj(_obj(cos).get("body"))
            w = by_id.get(body.get("witness_id"))
            if (w is None or body.get("witness_id") in seen or set(body) != COSIG_FIELDS
                    or any(body.get(f) != sth.get(f) for f in ("log_id", "tree_size", "root_hash"))):
                continue
            if verify_domain(w["public_key"], COSIG_DOMAIN, canonical(body), cos.get("signature")):
                seen.add(body["witness_id"])
        return "PASS" if len(seen) >= threshold else "FAIL"
    except (KeyError, ValueError, TypeError, AttributeError):
        return "FAIL"


# ---------------------------------------------------------------- approval and output policy (docs/adr/0022)
DECISION_DOMAIN = "tlay/keyauth-decision/v1"
SERIES_DOMAIN = "tlay/series-authorization/v1"
DECISION_FIELDS = frozenset({"record_version", "seq", "decision_id", "decision", "policy_hash", "decided_at", "decided_by_sha256", "request_id",
                             "note_sha256", "key_id"})
DECISION_REQUIRED = frozenset({"record_version", "seq", "decision_id", "decision", "policy_hash", "decided_at", "decided_by_sha256"})
DECISION_LEAF_EXTRA = ("type", "signature", "signer_key_id", "at", "log_id", "index")
NO_REVOCATION_NOTE = "An inclusion proof cannot show that no revocation was logged; the release service refuses to reserve budget once one is."
RESULT_FIELDS = frozenset({"output_schema", "release_id", "metric_id", "metric_name", "noisy_value", "unit", "public_N", "epsilon", "delta",
                           "privacy_unit", "mechanism_version", "policy_hash", "snapshot_commitment", "mode", "receipt_id"})
MODEL_COMMON = frozenset({"output_schema", "release_id", "receipt_id", "policy_hash", "mode", "model_type", "features", "prediction", "public_N",
                          "epsilon", "delta", "privacy_unit", "mechanism_version", "input_snapshots_commitment"})
MODEL_FIELDS = {"linear": MODEL_COMMON | {"weights", "bias"},
                "mlp": MODEL_COMMON | {"hidden_units", "activation", "hidden_weights", "hidden_bias", "output_weights", "output_bias"}}
MODEL_OPTIONAL = frozenset({"heldout_evaluation", "trust", "coverage", "covariate_coverage", "joint_coverage", "version"})
MODEL_SCHEMAS = ("runtime_forecast_model_v1", "energy_forecast_model_v1")
FORBIDDEN_FIELDS = frozenset({"true_mean", "exact_sum", "noise", "noise_sample", "seed", "random_seed", "values", "roster", "uploaded_count",
                              "missing_rate", "loss", "losses", "loss_curve", "checkpoints", "gradients", "validation", "val_mae", "train_mae"})
_DECIMAL = re.compile(r"-?(0|[1-9][0-9]*)(\.[0-9]+)?")


def leaf_included(proof: Any, release_keys: list[Any], leaf_type: str) -> Optional[dict[str, Any]]:
    """The proof's leaf when a signed tree head of one of the release-service keys and a Merkle path cover it."""
    if not isinstance(proof, dict) or _obj(proof.get("leaf")).get("type") != leaf_type:
        return None
    for pub in release_keys:
        try:
            sth = proof["sth"]
            if sth["sth"].get("log_id") != LOG_ID or proof["leaf"].get("log_id") != LOG_ID:
                continue
            leaf_bytes = b64d(proof["leaf_b64"])
            if (verify_domain(pub, STH_DOMAIN, canonical(sth["sth"]), sth["signature"]) and canonical(proof["leaf"]) == leaf_bytes
                    and verify_inclusion(proof["leaf_index"], sth["sth"]["tree_size"], _leaf_hash(leaf_bytes),
                                         [bytes.fromhex(p) for p in proof["proof"]], bytes.fromhex(sth["sth"]["root_hash"]))):
                return proof["leaf"]
        except (KeyError, ValueError, TypeError, AttributeError):
            continue
    return None


def _decision_ok(r: dict[str, Any]) -> bool:
    """The shape the key authority signs (tlay_contracts.transparency.decision_record_problems)."""
    def hex64(v: Any) -> bool:
        return isinstance(v, str) and _HEX64.fullmatch(v) is not None

    def short_id(v: Any) -> bool:
        return v is None or (isinstance(v, str) and 1 <= len(v) <= 40 and v.replace("_", "").isalnum())

    did, seq, at = r.get("decision_id"), r.get("seq"), r.get("decided_at")
    return (set(r) <= DECISION_FIELDS and DECISION_REQUIRED <= set(r) and r.get("record_version") == "1"
            and type(seq) is int and 1 <= seq < 2**53
            and isinstance(did, str) and did.startswith("kad_") and 8 <= len(did) <= 40 and did[4:].isalnum()
            and r.get("decision") in ("APPROVED", "REJECTED", "REVOKED") and hex64(r.get("policy_hash")) and hex64(r.get("decided_by_sha256"))
            and (r.get("note_sha256") is None or hex64(r["note_sha256"])) and short_id(r.get("request_id")) and short_id(r.get("key_id"))
            and not (r.get("decision") == "APPROVED" and not r.get("key_id"))
            and isinstance(at, str) and len(at) <= 40 and at.endswith("Z"))


def _day(leaf: dict[str, Any]) -> str:
    """A series child's day, counted from 1 (the leaf's series_index counts from 0)."""
    i = leaf.get("series_index")
    return str(i + 1) if type(i) is int else "?"


def authorization_check(evidence: Any, receipt: dict[str, Any], anchors: dict[str, Any], release_keys: list[Any]) -> dict[str, str]:
    """The key authority approved the policy the receipt names, and the approval is in the deployment's log."""
    name, ka, ev = "policy_authorization", _obj(anchors.get("key_authority")), _obj(evidence)
    if not ev or not (ev.get("decision_proof") or ev.get("series_proof")):
        return {"name": name, "status": "NOT_AVAILABLE", "detail": "No approval record in this file; bundles exported before 2026-11-01 do not carry one"}
    if not release_keys or not ka.get("public_key"):
        return {"name": name, "status": "NOT_CHECKED", "detail": "Needs the key authority and release service anchors"}
    verified_at = _obj(_obj(receipt.get("attestation_record")).get("record")).get("verified_at")
    try:
        if ev.get("decision_proof"):
            leaf = leaf_included(ev["decision_proof"], release_keys, "keyauth_decision") or {}
            rec = {k: v for k, v in leaf.items() if k not in DECISION_LEAF_EXTRA}
            ok = (bool(leaf) and rec.get("decision") == "APPROVED" and rec.get("policy_hash") == receipt.get("policy_hash") and _decision_ok(rec)
                  and leaf.get("signer_key_id") == ka.get("key_id") and verify_domain(ka["public_key"], DECISION_DOMAIN, canonical(rec), leaf.get("signature"))
                  and isinstance(verified_at, str) and rec["decided_at"] <= verified_at)
            return _check(name, ok, f"Key authority approval {rec.get('decision_id')} of this policy, signed {rec.get('decided_at')} before the key release "
                          "and included in the log. " + NO_REVOCATION_NOTE if ok else "No logged, signed key authority approval of this policy before its key release")
        child = leaf_included(ev.get("policy_proof"), release_keys, "policy_authorized") or {}
        series = leaf_included(ev.get("series_proof"), release_keys, "series_authorized") or {}
        signed = _obj(ev.get("series_record"))
        rec, shash = _obj(signed.get("record")), child.get("series_hash")
        ok = (bool(child) and bool(series) and child.get("policy_hash") == receipt.get("policy_hash") and isinstance(shash, str)
              and series.get("series_hash") == shash and sha256_hex(canonical(signed)) == series.get("record_digest")
              and signed.get("key_id") == ka.get("key_id") and rec.get("series_hash") == shash and rec.get("status") == "AUTHORIZED"
              and verify_domain(ka["public_key"], SERIES_DOMAIN, canonical(rec), signed.get("signature"))
              and rec.get("workload_digest") == receipt.get("workload_digest"))
    except (KeyError, ValueError, TypeError, AttributeError):
        ok = False
    return _check(name, ok, f"Day {_day(child)} of series {shash[:12]}…, which the key authority approved for this program; both in the log. "
                  + NO_REVOCATION_NOTE if ok else "This policy is not shown to be a logged day of a series the key authority approved for this program")


def _num(v: Any) -> Optional[tuple[int, str, str]]:
    """A plain decimal string or an integer as (sign, integer digits, fraction digits) for exact comparison."""
    if type(v) is int:
        v = str(v)
    if not isinstance(v, str) or not _DECIMAL.fullmatch(v):
        return None
    neg, body = v.startswith("-"), v.lstrip("-")
    whole, _, frac = body.partition(".")
    frac = frac.rstrip("0")
    zero = whole == "0" and not frac
    return (-1 if neg and not zero else 1, whole, frac)


def _le(a: tuple[int, str, str], b: tuple[int, str, str]) -> bool:
    """a <= b for two exact decimals from _num."""
    if a[0] != b[0]:
        return a[0] < b[0]
    n = max(len(a[2]), len(b[2]))
    ka, kb = (len(a[1]), a[1], a[2].ljust(n, "0")), (len(b[1]), b[1], b[2].ljust(n, "0"))
    return ka <= kb if a[0] > 0 else ka >= kb



def _version_matches_receipt(version, receipt):
    """docs/adr/0035 (tlay_contracts.evidence.version_matches_receipt): the model's version block is the receipt's, less its
    explanation and plus the gate's noised value, and the outcome is that value strictly above 0."""
    tr = receipt.get("training") if isinstance(receipt.get("training"), dict) else {}
    rv = tr.get("version") if isinstance(tr.get("version"), dict) else {}
    stated = {k: v for k, v in rv.items() if k not in ("rule", "composition")}
    if not isinstance(version, dict):
        return False
    gate = version.get("gate")
    if gate is None:
        return stated == version
    imp = gate.get("improvement") if isinstance(gate, dict) else None
    if not isinstance(imp, str) or not re.fullmatch(r"-?(0|[1-9][0-9]*)(\.[0-9]+)?", imp):
        return False
    public = dict(version, gate={k: v for k, v in gate.items() if k != "improvement"})
    return stated == public and gate.get("promoted") is (Decimal(imp) > 0)

def output_policy_check(result: Optional[bytes], receipt: dict[str, Any], policy: Optional[dict[str, Any]]) -> dict[str, str]:
    """The result in the file has only the fields its output schema allows and is bound to this release and policy."""
    name = "output_policy"
    if result is None:
        return {"name": name, "status": "NOT_CHECKED",
                "detail": "Needs the result (its buyers only); the release service checked it against the output schema and policy before committing"}
    try:
        doc = _strict_load(result)
        if not isinstance(doc, dict) or canonical(doc) != result:
            raise ValueError
    except (ValueError, UnicodeDecodeError):
        return {"name": name, "status": "FAIL", "detail": "The result is not a canonical JSON document"}
    keys, problems = set(doc), []
    model = doc.get("output_schema") in MODEL_SCHEMAS
    if model:
        allowed = MODEL_FIELDS.get(doc.get("model_type")) if isinstance(doc.get("model_type"), str) else None
        if allowed is None or keys - MODEL_OPTIONAL != allowed:
            problems.append("fields")
    elif keys != RESULT_FIELDS:
        problems.append("fields")
    if keys & FORBIDDEN_FIELDS:
        problems.append("forbidden field")
    commitment = doc.get("input_snapshots_commitment" if model else "snapshot_commitment")
    for label, mine, theirs in (("release_id", doc.get("release_id"), receipt.get("release_id")), ("receipt_id", doc.get("receipt_id"), receipt.get("receipt_id")),
                                ("policy_hash", doc.get("policy_hash"), receipt.get("policy_hash")), ("mode", doc.get("mode"), receipt.get("security_mode")),
                                ("input commitment", commitment, receipt.get("snapshot_commitment"))):
        if mine is None or mine != theirs:
            problems.append(label)
    if model and "version" in doc and not _version_matches_receipt(doc["version"], receipt):
        problems.append("version")
    if policy is not None:
        for f in ("output_schema", "privacy_unit", "epsilon", "delta", "public_N"):
            if doc.get(f) != policy.get(f) or (f == "public_N" and type(doc.get(f)) is not int):
                problems.append(f)
        if model and doc.get("model_type") != _obj(policy.get("training")).get("model_type"):
            problems.append("model_type")
        if not model:
            v, b = _num(doc.get("noisy_value")), _obj(policy.get("bounds"))
            lo, hi = _num(b.get("min")), _num(b.get("max"))
            if v is None or lo is None or hi is None or not (_le(lo, v) and _le(v, hi)):
                problems.append("bounds")
    if problems:
        return {"name": name, "status": "FAIL", "detail": "The result breaks its output policy: " + ", ".join(problems)}
    what, limit = ("model", "model type") if model else ("statistic", "bounds")
    if policy is None:  # removing the policy from a file must not turn the comparison above into a pass
        return {"name": name, "status": "NOT_CHECKED",
                "detail": f"The {what} has only the fields its output schema allows and names this release, policy and inputs, but with "
                f"no policy document to compare against, its output schema, privacy unit, epsilon, size and {limit} are not checked"}
    return {"name": name, "status": "PASS",
            "detail": f"The {what} has only the fields its output schema allows and names this release, policy and inputs, "
            f"and keeps the policy's output schema, privacy unit, epsilon, size and {limit}"}


# ---------------------------------------------------------------- whole file
def _strict_load(raw: bytes) -> Any:
    """Read a document exactly as tlay_crypto.strict_json_loads does (tests/vectors/strict_json_v1.json): UTF-8 with
    an optional byte order mark; no duplicate keys, floats, NaN or Infinity; integers within 2^53 - 1; no lone
    surrogates; containers nested at most MAX_DEPTH deep. Every refusal is a ValueError."""

    def no_float(_s: str) -> Any:
        raise ValueError("floats are not used in TLAY documents")

    def no_dupes(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
        d: dict[str, Any] = {}
        for k, v in pairs:
            if k in d:
                raise ValueError(f"duplicate key {k!r}")
            d[k] = v
        return d

    try:
        doc = json.loads(raw.decode("utf-8-sig"), parse_float=no_float, parse_constant=no_float, object_pairs_hook=no_dupes)
    except RecursionError as exc:
        raise ValueError("document nesting too deep") from exc
    stack: list[tuple[Any, int]] = [(doc, 0)]
    while stack:
        node, depth = stack.pop()
        if isinstance(node, (dict, list)):
            if depth >= MAX_DEPTH:
                raise ValueError("document nesting too deep")
            items = list(node.items()) if isinstance(node, dict) else [(None, x) for x in node]
            for k, x in items:
                if k is not None:
                    k.encode("utf-8")  # a lone surrogate in a key raises here
                stack.append((x, depth + 1))
        elif isinstance(node, int) and not isinstance(node, bool):
            if abs(node) > MAX_SAFE_INTEGER:
                raise ValueError("integer outside the I-JSON range")
        elif isinstance(node, str):
            node.encode("utf-8")  # a lone surrogate raises here (UnicodeEncodeError is a ValueError)
    return doc


# ---------------------------------------------------------------- sealed results (tlay_contracts.sealed_result)
# HPKE base mode (RFC 9180 sections 4, 5.1, 7.1): DHKEM(X25519, HKDF-SHA256) 0x0020, HKDF-SHA256 0x0001,
# ChaCha20-Poly1305 0x0003, single-shot open (sequence 0). Checked against RFC 9180 A.2.1 and against the sealing code.
SEALED_SCHEMA = "tlay-sealed-result/v1"
RESULT_KEY_INFO = b"tlay-result-key/v1"
_KEM_SUITE = b"KEM\x00\x20"
_HPKE_SUITE = b"HPKE\x00\x20\x00\x01\x00\x03"


def _labeled_extract(suite: bytes, salt: bytes, label: bytes, ikm: bytes) -> bytes:
    import hmac
    return hmac.new(salt or b"\x00" * 32, b"HPKE-v1" + suite + label + ikm, hashlib.sha256).digest()


def _labeled_expand(suite: bytes, prk: bytes, label: bytes, info: bytes, n: int) -> bytes:
    import hmac
    data, out, t, i = n.to_bytes(2, "big") + b"HPKE-v1" + suite + label + info, b"", b"", 1
    while len(out) < n:
        t = hmac.new(prk, t + data + bytes([i]), hashlib.sha256).digest()
        out, i = out + t, i + 1
    return out[:n]


def hpke_open(private_raw: bytes, enc: bytes, ct: bytes, aad: bytes, info: bytes) -> bytes:
    """Raises (ValueError, cryptography's InvalidTag) on any failure; an all-zero X25519 output is rejected."""
    from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey, X25519PublicKey
    from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305
    from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat

    if len(private_raw) != 32 or len(enc) != 32:
        raise ValueError("an X25519 key and an encapsulated key are 32 bytes")
    sk = X25519PrivateKey.from_private_bytes(private_raw)
    dh = sk.exchange(X25519PublicKey.from_public_bytes(enc))
    pk_rm = sk.public_key().public_bytes(Encoding.Raw, PublicFormat.Raw)
    shared = _labeled_expand(_KEM_SUITE, _labeled_extract(_KEM_SUITE, b"", b"eae_prk", dh), b"shared_secret", enc + pk_rm, 32)
    context = b"\x00" + _labeled_extract(_HPKE_SUITE, b"", b"psk_id_hash", b"") + _labeled_extract(_HPKE_SUITE, b"", b"info_hash", info)
    secret = _labeled_extract(_HPKE_SUITE, shared, b"secret", b"")
    key = _labeled_expand(_HPKE_SUITE, secret, b"key", context, 32)
    nonce = _labeled_expand(_HPKE_SUITE, secret, b"base_nonce", context, 12)
    return ChaCha20Poly1305(key).decrypt(nonce, ct, aad)


def open_sealed_result(doc_bytes: bytes, buyer_id: str, private_raw: bytes) -> tuple[bytes, bytes]:
    """(result bytes, commitment salt) of a tlay-sealed-result/v1 document, as tlay_contracts.sealed_result opens it.
    Raises ValueError (or InvalidTag) if it is not one, the buyer is not a recipient, or the key does not open it."""
    from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305

    d = _obj(_strict_load(doc_bytes))
    if d.get("schema") != SEALED_SCHEMA or d.get("aead") != "chacha20poly1305" or not isinstance(d.get("release_id"), str):
        raise ValueError("not a tlay-sealed-result/v1 document")
    mine = [r for r in d.get("recipients") or [] if isinstance(r, dict) and r.get("buyer_id") == buyer_id]
    if len(mine) != 1:
        raise ValueError("not a recipient")
    r = mine[0]
    wrap_aad = canonical({"schema": SEALED_SCHEMA, "release_id": d["release_id"], "buyer_id": buyer_id, "public_key": r.get("public_key")})
    key = hpke_open(private_raw, b64d(r.get("enc_b64")), b64d(r.get("wrapped_key_b64")), wrap_aad, RESULT_KEY_INFO)
    inner = _obj(_strict_load(ChaCha20Poly1305(key).decrypt(b64d(d.get("nonce_b64")), b64d(d.get("ciphertext_b64")),
                                                            canonical({"schema": SEALED_SCHEMA, "release_id": d["release_id"]}))))
    return b64d(inner.get("result_b64")), b64d(inner.get("salt_b64"))


def read_result_key(path: str) -> bytes:
    """The buyer's X25519 private key: base64 of 32 raw bytes, the file's only content."""
    with open(path, "rb") as f:
        raw = f.read(4096)
    try:
        key = b64d(raw.decode("ascii").strip())
    except (UnicodeDecodeError, ValueError):
        raise ValueError("the result key file is not base64 of a 32-byte X25519 private key") from None
    if len(key) != 32:
        raise ValueError("the result key file is not base64 of a 32-byte X25519 private key")
    return key


def header_check(doc: dict[str, Any], receipt: dict[str, Any], result: Optional[bytes]) -> dict[str, str]:
    bad = [k for k in HEADER_IDS if k in doc and doc[k] != receipt.get(k)]
    compared = [k for k in HEADER_IDS if k in doc]
    if "policy" in doc:
        compared.append("policy")
        try:
            if sha256_hex(canonical(doc["policy"])) != receipt.get("policy_hash"):
                bad.append("policy")
        except ValueError:
            bad.append("policy")
    if "result_sha256" in _obj(doc.get("result")) and result is not None:
        compared.append("result_sha256")
        if doc["result"]["result_sha256"] != sha256_hex(result):
            bad.append("result_sha256")
    res = _obj(doc.get("result"))
    if res.get("sealed"):  # A result is sealed exactly when its policy names recipients; the flag must not hide open bytes.
        compared.append("result.sealed")
        policy = doc.get("policy")
        named = policy.get("result_recipients") if isinstance(policy, dict) else None
        if "result_b64" in res or (isinstance(policy, dict) and not (isinstance(named, list) and named)):
            bad.append("result.sealed")
    if bad:
        return {"name": "bundle_header", "status": "FAIL", "detail": "Bundle fields disagree with the signed receipt: " + ", ".join(bad)}
    if res.get("sealed") and "policy" not in doc:  # removing the policy must not leave the sealed mark unchecked unseen
        return {"name": "bundle_header", "status": "NOT_CHECKED", "detail": "The result is marked sealed, but the file has no policy document, so that the policy names the buyers it is sealed to cannot be checked; the other copies agree: " + ", ".join(k for k in compared if k != "result.sealed")}
    return {"name": "bundle_header", "status": "PASS", "detail": "Bundle copies agree with the signed receipt: " + (", ".join(compared) or "none present")}


# ---------------------------------------------------------------- pre-committed key rotation (docs/adr/0008)
ROTATION_DOMAIN = "tlay/key-rotation/v1"
ROTATION_FIELDS = frozenset({"record_version", "role", "previous_key_id", "key_id", "public_key", "next_key_sha256", "effective_from"})
MAX_ROTATIONS = 16
_HEX64 = re.compile(r"[0-9a-f]{64}")
_UTC = re.compile(r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z")


def key_id_of(pub_b64: str) -> str:
    return "ed25519:" + hashlib.sha256(b64d(pub_b64)).hexdigest()[:16]


def _link(signed: Any, role: str, prev: dict[str, Any]) -> Optional[dict[str, Any]]:
    """The key a rotation record introduces after `prev`: its public key must hash to prev's commitment, it must name
    prev's key id and carry its own, and it must verify under its own key. None if any of that fails."""
    r = _obj(_obj(signed).get("record"))
    try:
        if set(r) != ROTATION_FIELDS or r["record_version"] != "1" or r["role"] != role:
            return None
        if r["previous_key_id"] != prev.get("key_id") or not prev.get("next_key_sha256"):
            return None
        raw = b64d(r["public_key"])
        if len(raw) != 32 or hashlib.sha256(raw).hexdigest() != prev["next_key_sha256"] or r["key_id"] != key_id_of(r["public_key"]):
            return None
        if not isinstance(r["next_key_sha256"], str) or not _HEX64.fullmatch(r["next_key_sha256"]):
            return None
        if not isinstance(r["effective_from"], str) or not _UTC.fullmatch(r["effective_from"]):
            return None
        if not verify_domain(r["public_key"], ROTATION_DOMAIN, canonical(r), _obj(signed).get("signature")):
            return None
    except (KeyError, TypeError, ValueError):
        return None
    return {"key_id": r["key_id"], "public_key": r["public_key"], "next_key_sha256": r["next_key_sha256"]}


def resolve_chain(pinned: Any, rotations: Any, role: str) -> list[dict[str, Any]]:
    """Keys reachable from the pinned anchor through valid rotation records, pinned first; stops at a missing link,
    at a fork (two different valid records after one key) or after MAX_ROTATIONS links."""
    chain = [pinned] if isinstance(pinned, dict) and pinned.get("public_key") else []
    records = rotations if isinstance(rotations, list) else []
    while chain and len(chain) <= MAX_ROTATIONS:
        found = {}
        for signed in records:
            nxt = _link(signed, role, chain[-1])
            if nxt is not None:
                found[canonical(_obj(signed)["record"])] = nxt
        if len(found) != 1:
            break
        chain.append(next(iter(found.values())))
    return chain


def resolve_anchor(pinned: Any, rotations: Any, role: str, key_id: Any) -> Optional[dict[str, Any]]:
    for a in resolve_chain(pinned, rotations, role) or ([pinned] if isinstance(pinned, dict) else []):
        if a.get("key_id") == key_id:
            return a
    return None


def verdict(checks: list[dict[str, str]]) -> str:
    st = {c["status"] for c in checks}
    return "FAIL" if "FAIL" in st else ("PARTIAL" if st & {"NOT_CHECKED", "NOT_AVAILABLE"} else "PASS")


def verify_document(doc: dict[str, Any], anchors: Optional[dict[str, Any]], rotations: Optional[list[Any]] = None,
                    buyer: Optional[tuple[str, bytes]] = None) -> dict[str, Any]:
    if "bundle_version" in doc and doc["bundle_version"] != BUNDLE_VERSION:
        raise ValueError(f"unknown bundle_version {doc['bundle_version']!r} (this verifier reads {BUNDLE_VERSION})")
    if doc.get("bundle_version") == BUNDLE_VERSION or "receipt" in doc:
        receipt = doc.get("receipt")
    else:
        receipt = doc if "receipt_version" in doc else None
    if not isinstance(receipt, dict):
        raise ValueError("no TLAY receipt in this file")
    notes: list[str] = []
    if anchors is None:
        anchors = _obj(doc.get("trust_anchors"))
        source = "embedded in the file (NOT independent: pass --anchors with keys you obtained elsewhere)"
    else:
        source = "pinned (--anchors)"
        for role in ("release_service", "key_authority"):
            emb = _obj(_obj(doc.get("trust_anchors")).get(role)).get("public_key")
            if emb and emb != _obj(anchors.get(role)).get("public_key"):
                notes.append(f"the file's {role} key differs from your pinned key")
    result = salt = None
    res = _obj(doc.get("result"))
    if res.get("sealed") and buyer is not None:
        buyer_id, result_key = buyer
        try:
            result, salt = open_sealed_result(b64d(res.get("sealed_result_b64")), buyer_id, result_key)
            notes.append(f"the result is sealed to the named buyers; opened here with the result key of {buyer_id}")
        except Exception as exc:  # noqa: BLE001 - wrong key, not a recipient, malformed: the commitment check reports FAIL
            result, salt = b"", b"\x00" * 32
            notes.append(f"the sealed result could not be opened as {buyer_id}: {type(exc).__name__}")
    elif res.get("sealed"):
        notes.append("the result is sealed to a named buyer: that buyer can open it here with --buyer-id and --result-key to check result_commitment and output_policy")
    elif "result_b64" in res:
        try:
            result, salt = b64d(res["result_b64"]), b64d(res.get("result_salt_b64"))
        except ValueError:
            result, salt = b"", b""
            notes.append("the result in the file is not valid base64")
    # A key rotated since the anchors were pinned counts only through pre-committed rotation records (docs/adr/0008).
    rotations = list(rotations or []) + (doc["key_rotations"] if isinstance(doc.get("key_rotations"), list) else [])
    pinned = anchors
    anchors = dict(anchors)
    wanted = {"release_service": _obj(receipt.get("commit")).get("key_id"), "key_authority": _obj(receipt.get("attestation_record")).get("key_id")}
    for role, kid in wanted.items():
        mine = _obj(pinned.get(role))
        if kid is None or mine.get("key_id") == kid:
            continue
        found = resolve_anchor(mine, rotations, role, kid)
        if found is not None:
            anchors[role] = found
            notes.append(f"{role}: key {kid} accepted through pre-committed rotation(s) from the pinned key {mine.get('key_id')}")
    checks = verify_receipt(receipt, anchors, result, salt)
    rel_chain = resolve_chain(_obj(pinned.get("release_service")), rotations, "release_service")
    policy = doc.get("policy") if isinstance(doc.get("policy"), dict) and doc is not receipt else None
    try:
        if policy is not None and sha256_hex(canonical(policy)) != receipt.get("policy_hash"):
            policy = None  # only the policy document the receipt's policy hash names counts
    except ValueError:
        policy = None
    checks.append(authorization_check(_obj(doc.get("transparency")).get("authorization_evidence"), receipt, anchors,
                                      [a["public_key"] for a in rel_chain if a.get("public_key")]))
    checks.append(output_policy_check(result, receipt, policy))
    proof = _obj(doc.get("transparency")).get("release_inclusion_proof")
    # A tree head names no signer: try each release-service key reachable from the pinned one.
    tried = [inclusion_status(proof, receipt, a.get("public_key")) for a in rel_chain]
    tried = tried or [inclusion_status(proof, receipt, None)]
    status = "PASS" if "PASS" in tried else tried[0]
    if status == "PASS" and not pinned_log_ok(pinned):
        status = "FAIL"
        notes.append(f"your anchors pin log id {_obj(pinned.get('transparency_log')).get('log_id')!r}; this receipt's head is of {LOG_ID!r}")
    checks.append({"name": "transparency_inclusion", "status": status,
                   "detail": "Signed tree head + Merkle path of the deployment's transparency log cover this exact receipt"})
    # Witnessed head (docs/adr/0049): a check of its own only when it can pass or fail; a head not witnessed yet, or no
    # witnesses listed, is reported beside the checks and does not make the verdict PARTIAL.
    witnessed = head_witnessed_status(_obj(doc.get("transparency")).get("witnessed_inclusion"), receipt,
                                      [a["public_key"] for a in rel_chain if a.get("public_key")], *witnesses_of(pinned))
    if witnessed in ("PASS", "FAIL"):
        checks.append({"name": "head_witnessed", "status": witnessed,
                       "detail": "The receipt's log entry is in a tree head that the listed witnesses cosigned after checking it against the heads they saw before"})
    # The raw attestation evidence (docs/adr/0055): a check of its own only when it can pass or fail.
    ev_block = _obj(doc.get("transparency")).get("attestation_evidence") if doc is not receipt else None
    audience = _obj(_obj(policy).get("attestation")).get("audience") if policy is not None else None
    ev_status, ev_problems = check_attestation_evidence(ev_block, _obj(receipt.get("attestation_record")).get("record"), audience)
    if ev_status == "PASS" and policy is None:  # the token's audience is compared with the policy's
        ev_status, ev_problems = "NOT_CHECKED", ["the token's audience cannot be compared: the file has no policy document the receipt names"]
    if ev_status in ("PASS", "FAIL"):
        checks.append({"name": "attestation_evidence", "status": ev_status,
                       "detail": "Google's Confidential Space token, hashed in the signed attestation record, states this image, TDX, debugging off and this session's keys"})
    notes.extend(f"attestation evidence: {x}" for x in ev_problems)
    if ev_status == "PASS":
        notes.append("attestation evidence: the issuer key came with the bundle; --online checks that Google lists its kid")
    if doc is not receipt:  # any wrapper around the receipt, labelled as a bundle or not, has its copies checked
        checks.append(header_check(doc, receipt, None if res.get("sealed") else result))  # as tlay_contracts: the digest of open bytes only
        unsigned = [k for k in UNSIGNED_FIELDS if k in doc]
        if unsigned:
            notes.append("not covered by any signature (informational only): " + ", ".join(unsigned))
        unchecked = [f"transparency.{k}" for k in UNCHECKED_TRANSPARENCY if k in _obj(doc.get("transparency"))]
        if unchecked:
            notes.append("carried in the file but not checked (informational only): " + ", ".join(unchecked))
    v = verdict(checks)
    simulated = any(c["status"] == "SIMULATED" for c in checks)
    visibility = "sealed" if res.get("sealed") else "open" if "result_b64" in res else "absent"
    key_ids = {role: _obj(anchors.get(role)).get("key_id") for role in ("key_authority", "release_service") if _obj(anchors.get(role)).get("key_id")}
    return {"simulated": simulated, "head_witnessed": witnessed, "attestation_evidence": ev_status,
            "evidence_kid": _obj(_obj(ev_block).get("jwk")).get("kid") if ev_status == "PASS" else None,
            "upload_receipts": upload_receipts_status(receipt), "receipt_id": receipt.get("receipt_id"), "release_id": receipt.get("release_id"), "security_mode": receipt.get("security_mode"),
            "anchors": source, "checks": checks, "notes": notes, "verdict": v, "ok": v != "FAIL",
            "trust_source": "bundle-supplied" if source.startswith("embedded") else "user-pinned", "anchor_key_ids": key_ids,
            "result_visibility": visibility, "informational_fields": [k for k in UNSIGNED_FIELDS if k in doc] if doc is not receipt else [],
            # The bytes the receipt's result_commitment matched, for --result-out only: never in the report or on screen.
            "result_bytes": result if any(c["name"] == "result_commitment" and c["status"] == "PASS" for c in checks) else None}


def report(out: dict[str, Any], name: str, raw: bytes, doc: dict[str, Any]) -> dict[str, Any]:
    """The verification report (schema tlay-verification-report/v1, docs/EVIDENCE_CONTRACT.md §8), the same record
    compute.tlay.io/verify offers for download. It holds the checks and identifiers, never the result, salt or keys."""
    import datetime

    mode = out["security_mode"] if out["security_mode"] in ("local_simulation", "attested_pilot") else "unknown"
    return {
        "schema_version": "tlay-verification-report/v1",
        "verifier_version": f"tlay_verify@{VERSION}",
        "checked_at": datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
        "input": {"name": name, "sha256": hashlib.sha256(raw).hexdigest(), "bundle_version": doc.get("bundle_version")},
        "receipt_id": out["receipt_id"],
        "release_id": out["release_id"],
        "verdict": out["verdict"],
        "simulated": out["simulated"],
        "security_mode": mode,
        "trust_source": out["trust_source"],
        "trust_anchor_key_ids": out["anchor_key_ids"],
        "evidence_scope": {"attested_pilot": "attestation_record_signature", "local_simulation": "simulated_attestation_record"}.get(mode, "unknown"),
        "raw_hardware_evidence": {"PASS": "PASS", "FAIL": "FAIL", "SIMULATED": "SIMULATED"}.get(out["attestation_evidence"], "NOT_CHECKED"),
        "result_visibility": out["result_visibility"],
        "checks": [{"name": c["name"], "status": c["status"], "detail": c["detail"]} for c in out["checks"]],
        "unchecked_reasons": [{"name": c["name"], "reason": c["detail"]} for c in out["checks"] if c["status"] == "NOT_CHECKED"],
        "informational_fields": out["informational_fields"],
        "notes": out["notes"],
    }


INDEX_FILE = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]*\.json")


def _index_file(base: str, path: Any) -> str:
    """An index entry's file, inside the index's own directory: only its last path segment is used."""
    name = path.rsplit("/", 1)[-1] if isinstance(path, str) else ""
    if not INDEX_FILE.fullmatch(name):
        raise ValueError(f"not a published file name: {path!r}")
    return os.path.join(base, name)


def _read_json(path: str) -> Any:
    with open(path, "rb") as f:
        raw = f.read(MAX_BYTES + 1)
    if len(raw) > MAX_BYTES:
        raise ValueError("file larger than 4 MiB")
    return _strict_load(raw)


def check_index(index_path: str) -> list[dict[str, Any]]:
    """Check every run of an evidence index (schema index_version 1) with the anchors file its entry names.

    One row per run: {id, title, receipt_id, verdict, not_passed, detail}. verdict is None for a run with anchors and
    no bundle. The index is not trusted: a bundle whose receipt is not the one the entry names, or an entry that names
    none, fails index_receipt; a file that cannot be read fails the run."""
    index = _read_json(index_path)
    runs = index.get("runs") if isinstance(index, dict) else None
    if not isinstance(runs, list) or not runs:
        raise ValueError("the evidence index lists no runs")
    base = os.path.dirname(os.path.abspath(index_path))
    rows: list[dict[str, Any]] = []
    for run in runs:
        run = _obj(run)
        row: dict[str, Any] = {"id": run.get("id"), "title": run.get("title"), "receipt_id": run.get("receipt_id"),
                               "verdict": None, "not_passed": [], "simulated": [], "detail": ""}
        try:
            an = _read_json(_index_file(base, run.get("anchors")))
            if run.get("bundle") is None:
                row["detail"] = "only this run's anchors were published; there is no result bundle to check"
                rows.append(row)
                continue
            doc = _read_json(_index_file(base, run.get("bundle")))
            if not isinstance(doc, dict) or not isinstance(an, dict):
                raise ValueError("not a JSON object")
            rotations = an.get("key_rotations") if isinstance(an.get("key_rotations"), list) else []
            out = verify_document(doc, _obj(an.get("anchors", an)), rotations)
        except (OSError, ValueError, UnicodeDecodeError) as exc:
            row.update(verdict="FAIL", not_passed=["index_file"], detail=f"cannot verify: {exc}")
            rows.append(row)
            continue
        checks = list(out["checks"])
        named = run.get("receipt_id")
        if not isinstance(named, str) or named != out["receipt_id"]:
            said = f"the index names receipt {named}" if isinstance(named, str) else "the index entry names no receipt"
            checks.append({"name": "index_receipt", "status": "FAIL", "detail": f"{said}, but this bundle's receipt is {out['receipt_id']}"})
        row["verdict"] = verdict(checks)
        row["not_passed"] = sorted(c["name"] for c in checks if c["status"] != "PASS")
        row["simulated"] = sorted(c["name"] for c in checks if c["status"] == "SIMULATED")
        row["detail"] = "; ".join(f"{c['name']} {c['status']}: {c['detail']}" for c in checks if c["status"] == "FAIL")
        rows.append(row)
    return rows


def main_index(index_path: str, as_json: bool) -> int:
    try:
        import cryptography  # noqa: F401
    except ImportError:
        print('cannot verify: the "cryptography" package is missing; install it with: pip install "cryptography>=42"', file=sys.stderr)
        return 2
    try:
        rows = check_index(index_path)
    except (OSError, ValueError, UnicodeDecodeError) as exc:
        print(f"cannot verify: {exc}", file=sys.stderr)
        return 2
    if as_json:
        print(json.dumps({"index": os.path.basename(index_path), "tlay_verify": VERSION, "runs": rows}, indent=2, ensure_ascii=False))
    else:
        print(f"Evidence index {os.path.basename(index_path)}  (tlay_verify {VERSION}, offline)")
        w = max(len(str(r["id"])) for r in rows)
        for r in rows:
            v = r["verdict"] or "-"
            parts = []
            failed_or_unchecked = [n for n in r["not_passed"] if n not in r["simulated"]]
            if failed_or_unchecked:
                parts.append(("failed or not checked: " if r["verdict"] == "FAIL" else "not checked: ") + ", ".join(failed_or_unchecked))
            if r["simulated"]:
                parts.append("simulated (no hardware evidence): " + ", ".join(r["simulated"]))
            extra = "; ".join(parts) or "every check passed"
            if r["verdict"] is None:
                extra = r["detail"]
            print(f"  {v:<8} {str(r['id']):<{w}}  {r['receipt_id'] or '-'}  {extra}")
            if r["verdict"] == "FAIL":
                print(f"           {r['detail']}")
        checked = [r for r in rows if r["verdict"]]
        failed = sum(r["verdict"] == "FAIL" for r in checked)
        print(f"{len(checked)} bundles checked, {failed} failed. Run a bundle alone (tlay_verify.py BUNDLE --anchors FILE) for every check and note.")
    return 1 if any(r["verdict"] == "FAIL" for r in rows) else 0


def main(argv: Optional[list[str]] = None) -> int:
    ap = argparse.ArgumentParser(description="Verify a TLAY result bundle or receipt offline.")
    ap.add_argument("file", nargs="?", help="result bundle or receipt JSON file")
    ap.add_argument("--index", help="check every bundle of a published evidence index (evidence.json; its files in the same directory)")
    ap.add_argument("--anchors", help="JSON file with the trust anchors you pinned (e.g. demo.json from compute.tlay.io/anchors/)")
    ap.add_argument("--json", action="store_true", help="print a verification report (schema tlay-verification-report/v1) as JSON")
    ap.add_argument("--strict", action="store_true", help="exit 1 unless the verdict is PASS with hardware attestation (every layer checked, none SIMULATED)")
    ap.add_argument("--online", action="store_true", help="also fetch Google's Confidential Space JWKS and report whether it lists the evidence's key id")
    ap.add_argument("--buyer-id", help="with --result-key: the buyer the result is sealed to (as named in the policy)")
    ap.add_argument("--result-key", help="file with that buyer's X25519 result key (base64, 32 bytes): opens a sealed result on this machine")
    ap.add_argument("--result-out", metavar="FILE", help="write the result bytes that matched the receipt's result_commitment to FILE "
                    "(a new file, mode 0600), only if this run exits 0; nothing is written otherwise")
    ap.add_argument("--version", action="version", version=f"tlay_verify {VERSION}")
    a = ap.parse_args(argv)
    if a.index:
        if a.file or a.anchors or a.strict or a.online or a.buyer_id or a.result_key or a.result_out:
            ap.error("--index takes no bundle file, --anchors, --strict, --online, result key or --result-out: each index entry names its anchors")
        return main_index(a.index, a.json)
    if not a.file:
        ap.error("give a bundle or receipt file, or --index evidence.json")
    if bool(a.buyer_id) != bool(a.result_key):
        ap.error("--buyer-id and --result-key go together")
    try:
        import cryptography  # noqa: F401  (checked first, so a missing dependency never shows half a result)
    except ImportError:
        print('cannot verify: the "cryptography" package is missing; install it with: pip install "cryptography>=42"', file=sys.stderr)
        return 2
    try:
        with open(a.file, "rb") as f:
            raw = f.read(MAX_BYTES + 1)
        if len(raw) > MAX_BYTES:
            raise ValueError("file larger than 4 MiB")
        doc = _strict_load(raw)
        if not isinstance(doc, dict):
            raise ValueError("not a JSON object")
        anchors = None
        if a.anchors:
            with open(a.anchors, "rb") as f:
                an = _strict_load(f.read(MAX_BYTES))
            anchors = _obj(an.get("anchors", an)) if isinstance(an, dict) else {}
            file_rotations = an.get("key_rotations") if isinstance(an, dict) and isinstance(an.get("key_rotations"), list) else []
        else:
            file_rotations = []
        buyer = (a.buyer_id, read_result_key(a.result_key)) if a.result_key else None
        out = verify_document(doc, anchors, file_rotations, buyer)
        if a.online and out["evidence_kid"]:
            listed = google_lists_kid(out["evidence_kid"])
            out["notes"].append({True: "attestation evidence: Google's JWKS lists this key id now",
                                 False: "attestation evidence: Google's JWKS does not list this key id now (it rotates keys; check an archived copy)",
                                 None: "attestation evidence: Google's JWKS could not be fetched"}[listed])
    except (OSError, ValueError, UnicodeDecodeError) as exc:
        print(f"cannot verify: {exc}", file=sys.stderr)
        return 2
    if a.json:
        print(json.dumps(report(out, os.path.basename(a.file), raw, doc), indent=2, ensure_ascii=False))
    else:
        print(f"Receipt {out['receipt_id']}  release {out['release_id']}  (tlay_verify {VERSION}, offline)")
        print(f"Security mode: {out['security_mode']}")
        print(f"Trust anchors: {out['anchors']}")
        w = max(len(c["name"]) for c in out["checks"])
        for c in out["checks"]:
            print(f"  {c['status']:<11} {c['name']:<{w}}  {c['detail']}")
        ur = out["upload_receipts"]
        print(f"Upload receipts: {ur['status']}: {ur['detail']}")
        print(f"Raw attestation evidence: {out['attestation_evidence']}")
        for n in out["notes"]:
            print(f"NOTE: {n}")
        if out["security_mode"] == "local_simulation":
            print("NOTE: local simulation: the attestation layer is SIMULATED, not hardware evidence.")
        print({"PASS": "VERDICT: PASS (attestation SIMULATED: no hardware evidence; --strict rejects this)" if out["simulated"]
               else "VERDICT: PASS (every layer checked, none failed)",
               "PARTIAL": "VERDICT: PARTIAL (none failed, but a layer was NOT_CHECKED / NOT_AVAILABLE; --strict rejects this)",
               "FAIL": "VERDICT: FAIL (at least one check failed)"}[out["verdict"]])
    rc = 1 if out["verdict"] == "FAIL" or (a.strict and (out["verdict"] != "PASS" or out["simulated"])) else 0
    if a.result_out:
        return write_result(a.result_out, out, rc, sys.stderr if a.json else sys.stdout)
    return rc


def write_result(path: str, out: dict[str, Any], rc: int, say: Any) -> int:
    """--result-out: the exact bytes result_commitment matched, to a new file (never an existing file or a symlink), mode
    0600, and only when the run exits 0. Shows the path and the length, never the bytes, their hash or the key."""
    data = out.get("result_bytes")
    if rc != 0:
        print(f"Result not written: this run exits {rc} (verdict {out['verdict']}{', --strict' if out['verdict'] != 'FAIL' else ''})", file=say)
        return rc
    if data is None:
        why = ("the result is sealed: give --buyer-id and --result-key" if out["result_visibility"] == "sealed"
               else "this file carries no result")
        print(f"cannot write the result: {why}", file=sys.stderr)
        return 2
    flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_BINARY", 0)
    try:
        fd = os.open(path, flags, 0o600)
    except OSError as exc:
        print(f"cannot write the result: {path}: {exc.strerror or exc} (an existing file is never replaced)", file=sys.stderr)
        return 2
    with os.fdopen(fd, "wb") as f:
        f.write(data)
    print(f"Result written to {path} ({len(data)} bytes): the bytes the receipt's result_commitment matched", file=say)
    return 0


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