#!/usr/bin/env python3
"""Standalone offline verifier for Decern Stage-0 Sepolia counterparty receipts.

Requires only the Python 3 standard library (zero external dependencies) so
external security reviewers can verify Stage-0 counterparty receipts or bundles
offline, including full cryptographic NIST FIPS 204 ML-DSA-65 verification.

Verifies:
1. File size limits (1 MiB cap), pre-parse JSON nesting depth (max 32), strict
   ASCII NFKC strings, and strict JSON parsing rejecting duplicate keys,
   floats, scientific notation, NaN, Infinity, null fields, and unknown keys.
2. Schema, prototype stage notice, Sepolia network identifier ('ethereum-sepolia'),
   and chain ID (11155111).
3. Fail-closed signing-attempt and approver-set invariants across all verdicts
   (0 signing attempts on blocked runs; 1 signing attempt, valid policy fields,
   and verified ML-DSA-65 quorum count on authorized runs; strictly sorted
   distinct approver IDs matching valid_approvals_verified on every receipt).
4. Optional timestamp freshness checks (--now-unix-secs, --max-age-secs) and
   session/replay checks (--seen-sessions-file and within-bundle uniqueness).
5. Byte-for-byte canonical SHA-256 integrity commitment
   ('receipt_integrity_sha256') over stage_notice, reconstructed EVM action
   semantics, and quorum metadata.
6. Public-key SHA-256 pinning and full NIST FIPS 204 ML-DSA-65 cryptographic
   signature verification over the detached receipt seal.
"""

from __future__ import annotations

import argparse
import copy
import hashlib
import hmac
import json
import pathlib
import sys
import unicodedata
from typing import Any, NoReturn

RECEIPT_SCHEMA = "decern.stage0.counterparty_receipt.v1"
BUNDLE_SCHEMA = "decern.stage0.trial_bundle.v1"
SEAL_DOMAIN_TAG = "decern.stage0.receipt.seal.v1"
STAGE0_PROTOTYPE_NOTICE_V1 = (
    "Zero-custody Stage-0 Sepolia shadow trial receipt. "
    "Prototype only; never custody real value."
)
SEPOLIA_NETWORK_ID = "ethereum-sepolia"
SEPOLIA_CHAIN_ID = 11_155_111

MAX_FILE_BYTES = 1_048_576  # 1 MiB fail-closed pre-read file cap
MAX_JSON_DEPTH = 32
MAX_INT_DIGITS = 40
DEFAULT_MAX_AGE_SECS = 86_400
MAX_FUTURE_SKEW_SECS = 300
MIN_VALID_UNIX_SECS = 1_577_836_800  # 2020-01-01T00:00:00Z
MAX_VALID_UNIX_SECS = 4_102_444_800  # 2100-01-01T00:00:00Z

U8_MAX = (1 << 8) - 1
U16_MAX = (1 << 16) - 1
U64_MAX = (1 << 64) - 1
U128_MAX = (1 << 128) - 1

HEX_LOWER_CHARS = frozenset("0123456789abcdef")
HEX_ANY_CHARS = frozenset("0123456789abcdefABCDEF")

# NIST FIPS 204 ML-DSA-65 exact parameters
_MLDSA_Q = 8_380_417
_MLDSA_N = 256
_MLDSA_D = 13
_MLDSA_TAU = 49
_MLDSA_C_TILDE_BYTES = 48
_MLDSA_GAMMA1 = 1 << 19
_MLDSA_GAMMA2 = (_MLDSA_Q - 1) // 32  # 261888
_MLDSA_K = 6
_MLDSA_L = 5
_MLDSA_BETA = 196
_MLDSA_OMEGA = 55
_MLDSA_ZETA = 1753
_MLDSA_N_INV = pow(_MLDSA_N, -1, _MLDSA_Q)  # 8347681
_MLDSA_M_W1 = (_MLDSA_Q - 1) // (2 * _MLDSA_GAMMA2)  # 16
ML_DSA_65_PK_BYTES = 1952
ML_DSA_65_SIG_BYTES = 3309
ML_DSA_65_PK_HEX_LEN = ML_DSA_65_PK_BYTES * 2
ML_DSA_65_SIG_HEX_LEN = ML_DSA_65_SIG_BYTES * 2


def _bitrev8(x: int) -> int:
    return int(f"{x:08b}"[::-1], 2)


_MLDSA_ZETAS = tuple(pow(_MLDSA_ZETA, _bitrev8(k), _MLDSA_Q) for k in range(256))

BUNDLE_KEYS = frozenset(
    {
        "schema",
        "receipt_signer_pubkey_sha256",
        "receipts",
    }
)
RECEIPT_KEYS = frozenset(
    {
        "schema",
        "stage_notice",
        "scenario_id",
        "evaluated_at_unix_secs",
        "network_id",
        "chain_id",
        "asset_id",
        "policy_id",
        "verdict",
        "signing_attempts",
        "reason_code",
        "action",
        "quorum",
        "receipt_integrity_sha256",
        "receipt_seal",
    }
)
ACTION_KEYS = frozenset(
    {
        "envelope_kind",
        "signer_subject_hex",
        "target_contract_hex",
        "operation",
        "safe_operation",
        "recipient_or_target_hex",
        "amount_base_units",
        "signable_digest_hex",
    }
)
QUORUM_KEYS = frozenset(
    {
        "algorithm",
        "threshold_required",
        "valid_approvals_verified",
        "approved_approver_ids_hex",
    }
)
SEAL_KEYS = frozenset(
    {
        "algorithm",
        "domain_tag",
        "public_key_sha256",
        "public_key_hex",
        "signature_hex",
    }
)


class VerificationError(Exception):
    """Raised when any fail-closed Stage-0 receipt or CLI check fails."""


class _FailClosedArgumentParser(argparse.ArgumentParser):
    """ArgumentParser that reports CLI errors via VerificationError."""

    def error(self, message: str) -> NoReturn:
        raise VerificationError(f"CLI argument error: {message}")


def _reject_json_constant(token: str) -> NoReturn:
    raise VerificationError(f"non-standard JSON numeric constant forbidden: {token}")


def _reject_float(token: str) -> NoReturn:
    raise VerificationError(f"floating-point or scientific-notation JSON number forbidden: {token}")


def _parse_bounded_int(token: str) -> int:
    if len(token) > MAX_INT_DIGITS:
        raise VerificationError(f"integer token exceeds max digits ({MAX_INT_DIGITS})")
    return int(token)


def _reject_duplicate_keys(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
    out: dict[str, Any] = {}
    for key, val in pairs:
        if key in out:
            raise VerificationError(f"duplicate JSON key forbidden: {key}")
        out[key] = val
    return out


def _precheck_json_depth(raw: str, max_depth: int = MAX_JSON_DEPTH) -> None:
    """Scans raw JSON brackets before json.loads so deep nesting cannot raise RecursionError."""
    depth = 0
    in_string = False
    escaped = False
    for ch in raw:
        if in_string:
            if escaped:
                escaped = False
            elif ch == "\\":
                escaped = True
            elif ch == '"':
                in_string = False
            continue
        if ch == '"':
            in_string = True
        elif ch in "{[":
            depth += 1
            if depth > max_depth:
                raise VerificationError(f"JSON nesting depth exceeds maximum ({max_depth})")
        elif ch in "}]":
            depth = max(0, depth - 1)


def _enforce_max_depth(root: Any, max_depth: int = MAX_JSON_DEPTH) -> None:
    """Iteratively bounds JSON nesting depth before any deepcopy or traversal."""
    stack: list[tuple[Any, int]] = [(root, 0)]
    while stack:
        current, depth = stack.pop()
        if depth > max_depth:
            raise VerificationError(f"JSON nesting depth exceeds maximum ({max_depth})")
        if isinstance(current, dict):
            for val in current.values():
                if isinstance(val, (dict, list)):
                    stack.append((val, depth + 1))
        elif isinstance(current, list):
            for item in current:
                if isinstance(item, (dict, list)):
                    stack.append((item, depth + 1))


def _read_bounded_text(path: pathlib.Path, label: str = "input file") -> str:
    try:
        if not path.exists():
            raise VerificationError(f"{label} does not exist: {path}")
        if not path.is_file():
            raise VerificationError(f"{label} is not a regular file: {path}")
        size = path.stat().st_size
        if size == 0:
            raise VerificationError(f"{label} is empty: {path}")
        if size > MAX_FILE_BYTES:
            raise VerificationError(
                f"{label} exceeds maximum allowed size of {MAX_FILE_BYTES} bytes ({size} bytes)"
            )
        raw_bytes = path.read_bytes()
        if len(raw_bytes) > MAX_FILE_BYTES:
            raise VerificationError(
                f"{label} exceeds maximum allowed size of {MAX_FILE_BYTES} bytes"
            )
        return raw_bytes.decode("utf-8")
    except VerificationError:
        raise
    except (OSError, UnicodeDecodeError) as exc:
        raise VerificationError(f"could not read UTF-8 {label} {path}: {exc}") from exc


def _parse_hardened_json(raw: str, source_desc: str) -> Any:
    _precheck_json_depth(raw, MAX_JSON_DEPTH)
    try:
        doc = json.loads(
            raw,
            parse_constant=_reject_json_constant,
            parse_float=_reject_float,
            parse_int=_parse_bounded_int,
            object_pairs_hook=_reject_duplicate_keys,
        )
    except VerificationError:
        raise
    except (json.JSONDecodeError, RecursionError, ValueError) as exc:
        raise VerificationError(f"could not parse JSON from {source_desc}: {exc}") from exc
    _enforce_max_depth(doc, MAX_JSON_DEPTH)
    return doc


def _require_dict_exact_keys(
    obj: Any, expected_keys: frozenset[str], name: str
) -> dict[str, Any]:
    if not isinstance(obj, dict):
        raise VerificationError(f"{name} must be a JSON object")
    actual_keys = set(obj.keys())
    unknown = actual_keys - expected_keys
    if unknown:
        raise VerificationError(f"unexpected keys in {name}: {sorted(unknown)}")
    missing = expected_keys - actual_keys
    if missing:
        raise VerificationError(f"missing required keys in {name}: {sorted(missing)}")
    return obj


def _require_uint(value: Any, max_value: int, name: str) -> int:
    if type(value) is not int or value < 0 or value > max_value:
        raise VerificationError(f"invalid unsigned integer field: {name}")
    return value


def _clean_token(value: Any, name: str, max_len: int = 256) -> str:
    if not isinstance(value, str) or not value or len(value) > max_len:
        raise VerificationError(f"invalid or empty string field: {name}")
    if not value.isascii():
        raise VerificationError(f"non-ASCII character or Unicode homoglyph forbidden in {name}")
    if unicodedata.normalize("NFKC", value) != value:
        raise VerificationError(f"non-normalized string forbidden in {name}")
    if value.strip() != value:
        raise VerificationError(f"leading or trailing whitespace forbidden in {name}")
    for ch in value:
        code = ord(ch)
        if code < 0x20 or code > 0x7E:
            raise VerificationError(f"control or non-printable character forbidden in {name}")
    if "," in value:
        raise VerificationError(f"prohibited delimiter in field: {name}")
    return value


def _validate_stage_notice(value: Any) -> str:
    if not isinstance(value, str):
        raise VerificationError("stage_notice must be a string")
    if not value.isascii() or "\n" in value or "\r" in value or "\x00" in value:
        raise VerificationError("prohibited character in stage_notice")
    if value != STAGE0_PROTOTYPE_NOTICE_V1:
        raise VerificationError("stage_notice does not match STAGE0_PROTOTYPE_NOTICE_V1")
    return value


def _validate_lower_hex(value: Any, expected_len: int, name: str) -> str:
    if (
        not isinstance(value, str)
        or not value.isascii()
        or len(value) != expected_len
        or any(ch not in HEX_LOWER_CHARS for ch in value)
    ):
        raise VerificationError(f"malformed {expected_len}-char lowercase hex field: {name}")
    return value


def _validate_0x_lower_hex(value: Any, byte_len: int, name: str) -> str:
    expected_len = 2 + byte_len * 2
    if (
        not isinstance(value, str)
        or not value.isascii()
        or len(value) != expected_len
        or not value.startswith("0x")
        or any(ch not in HEX_LOWER_CHARS for ch in value[2:])
    ):
        raise VerificationError(
            f"malformed 0x-prefixed {byte_len}-byte lowercase hex field: {name}"
        )
    return value


def _validate_u128_decimal_str(value: Any, name: str) -> str:
    if (
        not isinstance(value, str)
        or len(value) == 0
        or not value.isascii()
        or not all("0" <= ch <= "9" for ch in value)
        or (value != "0" and value.startswith("0"))
        or int(value) > U128_MAX
    ):
        raise VerificationError(f"invalid decimal u128 string field: {name}")
    return value


def _validate_approver_ids(approvers: Any, valid_count: int) -> list[str]:
    if not isinstance(approvers, list):
        raise VerificationError("quorum.approved_approver_ids_hex must be a list")
    validated: list[str] = []
    for item in approvers:
        validated.append(_validate_lower_hex(item, 64, "quorum.approved_approver_ids_hex"))
    for idx in range(len(validated) - 1):
        if validated[idx] >= validated[idx + 1]:
            raise VerificationError(
                "quorum.approved_approver_ids_hex must be strictly sorted without duplicates"
            )
    if len(validated) != valid_count:
        raise VerificationError(
            "quorum.approved_approver_ids_hex length does not match valid_approvals_verified"
        )
    return validated


# ===========================================================================
# Pure-Python NIST FIPS 204 ML-DSA-65 Verification
# ===========================================================================

def _ntt(w: list[int]) -> list[int]:
    """FIPS 204 Algorithm 41: Number-Theoretic Transform over Z_q."""
    w_hat = list(w)
    m = 0
    length = 128
    while length >= 1:
        start = 0
        while start < 256:
            m += 1
            z = _MLDSA_ZETAS[m]
            for j in range(start, start + length):
                t = (z * w_hat[j + length]) % _MLDSA_Q
                w_hat[j + length] = (w_hat[j] - t) % _MLDSA_Q
                w_hat[j] = (w_hat[j] + t) % _MLDSA_Q
            start += 2 * length
        length //= 2
    return w_hat


def _inv_ntt(w_hat: list[int]) -> list[int]:
    """FIPS 204 Algorithm 42: Inverse Number-Theoretic Transform over Z_q."""
    w = list(w_hat)
    m = 256
    length = 1
    while length < 256:
        start = 0
        while start < 256:
            m -= 1
            z = (-_MLDSA_ZETAS[m]) % _MLDSA_Q
            for j in range(start, start + length):
                t = w[j]
                w[j] = (t + w[j + length]) % _MLDSA_Q
                w[j + length] = (z * (t - w[j + length])) % _MLDSA_Q
            start += 2 * length
        length *= 2
    return [(x * _MLDSA_N_INV) % _MLDSA_Q for x in w]


def _poly_ntt_mul(a_hat: list[int], b_hat: list[int]) -> list[int]:
    return [(a_hat[i] * b_hat[i]) % _MLDSA_Q for i in range(256)]


def _simple_bit_unpack_10(buf: bytes) -> list[int]:
    """Unpacks 320 bytes into 256 10-bit unsigned integers (4 coeffs per 5 bytes)."""
    out: list[int] = []
    for i in range(0, 320, 5):
        b0, b1, b2, b3, b4 = buf[i], buf[i + 1], buf[i + 2], buf[i + 3], buf[i + 4]
        out.append(b0 | ((b1 & 0x03) << 8))
        out.append((b1 >> 2) | ((b2 & 0x0F) << 6))
        out.append((b2 >> 4) | ((b3 & 0x3F) << 4))
        out.append((b3 >> 6) | (b4 << 2))
    return out


def _bit_unpack_z(buf: bytes) -> list[int]:
    """Unpacks 640 bytes into 256 signed z coefficients (gamma1 = 2^19, 20 bits each)."""
    out: list[int] = []
    for i in range(0, 640, 5):
        b0, b1, b2, b3, b4 = buf[i], buf[i + 1], buf[i + 2], buf[i + 3], buf[i + 4]
        v0 = b0 | (b1 << 8) | ((b2 & 0x0F) << 16)
        v1 = (b2 >> 4) | (b3 << 4) | (b4 << 12)
        out.append(_MLDSA_GAMMA1 - v0)
        out.append(_MLDSA_GAMMA1 - v1)
    return out


def _hint_bit_unpack(y: bytes) -> list[list[int]] | None:
    """FIPS 204 Algorithm 21: strictly validates hint encoding and padding."""
    if len(y) != _MLDSA_OMEGA + _MLDSA_K:
        return None
    h = [[0] * 256 for _ in range(_MLDSA_K)]
    index = 0
    for i in range(_MLDSA_K):
        limit = y[_MLDSA_OMEGA + i]
        if limit < index or limit > _MLDSA_OMEGA:
            return None
        first = index
        while index < limit:
            if index > first and y[index - 1] >= y[index]:
                return None
            h[i][y[index]] = 1
            index += 1
    for i in range(index, _MLDSA_OMEGA):
        if y[i] != 0:
            return None
    return h


def _expand_a(rho: bytes) -> list[list[list[int]]]:
    """FIPS 204 Algorithm 32: Expands 32-byte rho into K x L NTT matrix A_hat."""
    matrix: list[list[list[int]]] = []
    for r in range(_MLDSA_K):
        row: list[list[int]] = []
        for s in range(_MLDSA_L):
            # ML-DSA-65 worst-case rejection needs ~900 bytes; 1344 bytes is > 7x headroom.
            stream = hashlib.shake_128(rho + bytes((s, r))).digest(1344)
            poly: list[int] = []
            pos = 0
            while len(poly) < 256:
                if pos + 3 > len(stream):
                    raise VerificationError("ML-DSA-65 ExpandA XOF stream exhausted")
                b0 = stream[pos]
                b1 = stream[pos + 1]
                b2 = stream[pos + 2] & 0x7F
                pos += 3
                val = b0 | (b1 << 8) | (b2 << 16)
                if val < _MLDSA_Q:
                    poly.append(val)
            row.append(poly)
        matrix.append(row)
    return matrix


def _sample_in_ball(c_tilde: bytes) -> list[int]:
    """FIPS 204 Algorithm 29: Samples challenge polynomial c with Hamming weight tau."""
    stream = hashlib.shake_256(c_tilde).digest(512)
    sign_bits = int.from_bytes(stream[:8], "little")
    pos = 8
    c = [0] * 256
    for i in range(256 - _MLDSA_TAU, 256):
        while True:
            if pos >= len(stream):
                raise VerificationError("ML-DSA-65 SampleInBall XOF stream exhausted")
            j = stream[pos]
            pos += 1
            if j <= i:
                break
        c[i] = c[j]
        bit = (sign_bits >> (i + _MLDSA_TAU - 256)) & 1
        c[j] = (1 - 2 * bit) % _MLDSA_Q
    return c


def _use_hint(h_bit: int, r: int) -> int:
    """FIPS 204 Algorithms 36 & 40: Decompose and recover high bits using hint bit."""
    r_plus = r % _MLDSA_Q
    two_g2 = 2 * _MLDSA_GAMMA2
    r0 = r_plus % two_g2
    if r0 > _MLDSA_GAMMA2:
        r0 -= two_g2
    if r_plus - r0 == _MLDSA_Q - 1:
        r1 = 0
        r0 -= 1
    else:
        r1 = (r_plus - r0) // two_g2
    if h_bit == 1:
        if r0 > 0:
            return (r1 + 1) % _MLDSA_M_W1
        return (r1 - 1) % _MLDSA_M_W1
    return r1


def _w1_encode(w1: list[list[int]]) -> bytes:
    """FIPS 204 Algorithm 28: Encodes K=6 w1 polynomials (4 bits per coeff -> 768 bytes)."""
    out = bytearray()
    for poly in w1:
        for i in range(0, 256, 2):
            out.append((poly[i] & 0x0F) | ((poly[i + 1] & 0x0F) << 4))
    return bytes(out)


def ml_dsa_65_verify(pk_bytes: bytes, msg: bytes, sig_bytes: bytes, ctx: bytes = b"") -> bool:
    """Verifies a NIST FIPS 204 ML-DSA-65 signature (Algorithm 3 ML-DSA.Verify)."""
    if len(pk_bytes) != ML_DSA_65_PK_BYTES or len(sig_bytes) != ML_DSA_65_SIG_BYTES:
        return False
    if len(ctx) > 255:
        return False

    rho = pk_bytes[:32]
    t1 = [_simple_bit_unpack_10(pk_bytes[32 + 320 * i : 32 + 320 * (i + 1)]) for i in range(_MLDSA_K)]

    c_tilde = sig_bytes[:_MLDSA_C_TILDE_BYTES]
    z_offset = _MLDSA_C_TILDE_BYTES
    z = [_bit_unpack_z(sig_bytes[z_offset + 640 * i : z_offset + 640 * (i + 1)]) for i in range(_MLDSA_L)]
    h = _hint_bit_unpack(sig_bytes[z_offset + 640 * _MLDSA_L :])
    if h is None:
        return False

    bound = _MLDSA_GAMMA1 - _MLDSA_BETA
    for poly in z:
        for coeff in poly:
            if abs(coeff) >= bound:
                return False

    a_hat = _expand_a(rho)
    tr = hashlib.shake_256(pk_bytes).digest(64)
    m_prime = bytes((0, len(ctx))) + ctx + msg
    mu = hashlib.shake_256(tr + m_prime).digest(64)

    c_poly = _sample_in_ball(c_tilde)
    c_hat = _ntt(c_poly)
    z_hat = [_ntt([coeff % _MLDSA_Q for coeff in poly]) for poly in z]

    w1_prime: list[list[int]] = []
    for r in range(_MLDSA_K):
        acc = [0] * 256
        for s in range(_MLDSA_L):
            prod = _poly_ntt_mul(a_hat[r][s], z_hat[s])
            for j in range(256):
                acc[j] = (acc[j] + prod[j]) % _MLDSA_Q
        t1_shifted = [(coeff << _MLDSA_D) % _MLDSA_Q for coeff in t1[r]]
        t1_shifted_hat = _ntt(t1_shifted)
        c_t1 = _poly_ntt_mul(c_hat, t1_shifted_hat)
        diff_hat = [(acc[j] - c_t1[j]) % _MLDSA_Q for j in range(256)]
        w_approx = _inv_ntt(diff_hat)
        w1_prime.append([_use_hint(h[r][j], w_approx[j]) for j in range(256)])

    w1_encoded = _w1_encode(w1_prime)
    c_tilde_prime = hashlib.shake_256(mu + w1_encoded).digest(_MLDSA_C_TILDE_BYTES)
    return hmac.compare_digest(c_tilde, c_tilde_prime)


# ===========================================================================
# Stage-0 Counterparty Receipt Integrity & Policy Verification
# ===========================================================================

def compute_receipt_integrity_sha256(receipt: dict[str, Any]) -> str:
    """Recomputes the exact canonical SHA-256 commitment over Stage-0 receipt fields."""
    _require_dict_exact_keys(receipt, RECEIPT_KEYS, "receipt")
    action = _require_dict_exact_keys(receipt.get("action"), ACTION_KEYS, "receipt.action")
    quorum = _require_dict_exact_keys(receipt.get("quorum"), QUORUM_KEYS, "receipt.quorum")

    schema = _clean_token(receipt.get("schema"), "schema")
    stage_notice = _validate_stage_notice(receipt.get("stage_notice"))
    scenario_id = _clean_token(receipt.get("scenario_id"), "scenario_id")
    evaluated_at = _require_uint(
        receipt.get("evaluated_at_unix_secs"), U64_MAX, "evaluated_at_unix_secs"
    )
    network_id = _clean_token(receipt.get("network_id"), "network_id")
    chain_id = _require_uint(receipt.get("chain_id"), U64_MAX, "chain_id")
    asset_id = _clean_token(receipt.get("asset_id"), "asset_id")
    policy_id = _clean_token(receipt.get("policy_id"), "policy_id")
    verdict = _clean_token(receipt.get("verdict"), "verdict")
    signing_attempts = _require_uint(receipt.get("signing_attempts"), U8_MAX, "signing_attempts")
    reason_code = _clean_token(receipt.get("reason_code"), "reason_code")

    envelope_kind = _clean_token(action.get("envelope_kind"), "action.envelope_kind")
    signer_subject = _validate_0x_lower_hex(
        action.get("signer_subject_hex"), 20, "action.signer_subject_hex"
    )
    target_contract = _validate_0x_lower_hex(
        action.get("target_contract_hex"), 20, "action.target_contract_hex"
    )
    operation = _clean_token(action.get("operation"), "action.operation")

    raw_safe_op = action.get("safe_operation")
    if raw_safe_op is None:
        safe_op = "none"
    else:
        safe_op = _clean_token(raw_safe_op, "action.safe_operation")
        if safe_op not in ("call", "delegate_call"):
            raise VerificationError(
                "action.safe_operation must be 'call', 'delegate_call', or null"
            )

    raw_recipient = action.get("recipient_or_target_hex")
    if raw_recipient is None:
        recipient = "none"
    else:
        recipient = _validate_0x_lower_hex(
            raw_recipient, 20, "action.recipient_or_target_hex"
        )

    raw_amount = action.get("amount_base_units")
    if raw_amount is None:
        amount = "none"
    else:
        amount = _validate_u128_decimal_str(raw_amount, "action.amount_base_units")

    digest = _validate_0x_lower_hex(
        action.get("signable_digest_hex"), 32, "action.signable_digest_hex"
    )

    q_alg = _clean_token(quorum.get("algorithm"), "quorum.algorithm")
    threshold = _require_uint(quorum.get("threshold_required"), U16_MAX, "threshold_required")
    valid_count = _require_uint(
        quorum.get("valid_approvals_verified"), U16_MAX, "valid_approvals_verified"
    )
    approvers = _validate_approver_ids(quorum.get("approved_approver_ids_hex"), valid_count)

    canonical = "\n".join(
        [
            schema,
            f"stage_notice={stage_notice}",
            f"scenario_id={scenario_id}",
            f"evaluated_at_unix_secs={evaluated_at}",
            f"network_id={network_id}",
            f"chain_id={chain_id}",
            f"asset_id={asset_id}",
            f"policy_id={policy_id}",
            f"verdict={verdict}",
            f"signing_attempts={signing_attempts}",
            f"reason_code={reason_code}",
            f"envelope_kind={envelope_kind}",
            f"signer_subject_hex={signer_subject}",
            f"target_contract_hex={target_contract}",
            f"operation={operation}",
            f"safe_operation={safe_op}",
            f"recipient_or_target_hex={recipient}",
            f"amount_base_units={amount}",
            f"signable_digest_hex={digest}",
            f"quorum_algorithm={q_alg}",
            f"threshold_required={threshold}",
            f"valid_approvals_verified={valid_count}",
            f"approved_approver_ids_csv={','.join(approvers)}",
        ]
    )
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


def verify_single_receipt(
    receipt: Any,
    pinned_pubkey_sha256: str | None,
    *,
    now_unix_secs: int | None = None,
    max_age_secs: int = DEFAULT_MAX_AGE_SECS,
    seen_sessions: set[str] | None = None,
) -> None:
    """Validates one Stage-0 counterparty receipt dictionary, failing closed."""
    _require_dict_exact_keys(receipt, RECEIPT_KEYS, "receipt")
    action = _require_dict_exact_keys(receipt.get("action"), ACTION_KEYS, "receipt.action")
    quorum = _require_dict_exact_keys(receipt.get("quorum"), QUORUM_KEYS, "receipt.quorum")
    seal = _require_dict_exact_keys(receipt.get("receipt_seal"), SEAL_KEYS, "receipt.receipt_seal")

    if receipt.get("schema") != RECEIPT_SCHEMA:
        raise VerificationError(f"unsupported receipt schema: {receipt.get('schema')}")
    if receipt.get("stage_notice") != STAGE0_PROTOTYPE_NOTICE_V1:
        raise VerificationError("stage_notice does not match STAGE0_PROTOTYPE_NOTICE_V1")

    scenario_id = _clean_token(receipt.get("scenario_id"), "scenario_id")
    evaluated_at = _require_uint(
        receipt.get("evaluated_at_unix_secs"), U64_MAX, "evaluated_at_unix_secs"
    )
    if evaluated_at < MIN_VALID_UNIX_SECS or evaluated_at > MAX_VALID_UNIX_SECS:
        raise VerificationError(
            f"evaluated_at_unix_secs out of valid range [{MIN_VALID_UNIX_SECS}, {MAX_VALID_UNIX_SECS}]"
        )
    if now_unix_secs is not None:
        if evaluated_at > now_unix_secs + MAX_FUTURE_SKEW_SECS:
            raise VerificationError("receipt evaluated_at_unix_secs is too far in the future")
        if now_unix_secs - evaluated_at > max_age_secs:
            raise VerificationError(
                f"stale or expired receipt: age {now_unix_secs - evaluated_at}s exceeds max_age_secs {max_age_secs}s"
            )

    chain_id = _require_uint(receipt.get("chain_id"), U64_MAX, "chain_id")
    if receipt.get("network_id") != SEPOLIA_NETWORK_ID or chain_id != SEPOLIA_CHAIN_ID:
        raise VerificationError("non-Sepolia network or chain_id rejected")

    _clean_token(receipt.get("asset_id"), "asset_id")
    _clean_token(receipt.get("policy_id"), "policy_id")
    verdict = _clean_token(receipt.get("verdict"), "verdict")
    attempts = _require_uint(receipt.get("signing_attempts"), U8_MAX, "signing_attempts")
    reason_code = _clean_token(receipt.get("reason_code"), "reason_code")
    q_alg = _clean_token(quorum.get("algorithm"), "quorum.algorithm")
    if q_alg != "ml-dsa-65":
        raise VerificationError(f"unsupported quorum.algorithm: {q_alg}")

    threshold = _require_uint(quorum.get("threshold_required"), U16_MAX, "threshold_required")
    valid_count = _require_uint(
        quorum.get("valid_approvals_verified"), U16_MAX, "valid_approvals_verified"
    )
    approvers = _validate_approver_ids(quorum.get("approved_approver_ids_hex"), valid_count)

    _clean_token(action.get("envelope_kind"), "action.envelope_kind")
    operation = _clean_token(action.get("operation"), "action.operation")
    _validate_0x_lower_hex(action.get("signer_subject_hex"), 20, "action.signer_subject_hex")
    _validate_0x_lower_hex(action.get("target_contract_hex"), 20, "action.target_contract_hex")
    if action.get("recipient_or_target_hex") is not None:
        _validate_0x_lower_hex(
            action.get("recipient_or_target_hex"), 20, "action.recipient_or_target_hex"
        )
    digest_hex = _validate_0x_lower_hex(
        action.get("signable_digest_hex"), 32, "action.signable_digest_hex"
    )

    if verdict == "blocked_pre_signing":
        if attempts != 0:
            raise VerificationError("blocked_pre_signing receipt must have signing_attempts == 0")
        if reason_code == "authorized_quorum_and_policy_verified":
            raise VerificationError("blocked receipt carries authorized reason_code")
    elif verdict == "authorized":
        if attempts != 1:
            raise VerificationError("authorized receipt must have signing_attempts == 1")
        if reason_code != "authorized_quorum_and_policy_verified":
            raise VerificationError("authorized receipt missing authorized reason_code")
        if threshold < 1 or valid_count < threshold or len(approvers) != valid_count:
            raise VerificationError("authorized receipt failed ML-DSA-65 quorum count invariant")
        if digest_hex == ("0x" + "00" * 32):
            raise VerificationError("authorized receipt missing non-zero 32-byte signable_digest_hex")
        if action.get("safe_operation") == "delegate_call":
            raise VerificationError("authorized receipt cannot carry forbidden safe_operation=delegate_call")
        if operation in ("erc20_transfer", "token_mint"):
            if action.get("recipient_or_target_hex") is None:
                raise VerificationError(f"authorized {operation} missing recipient_or_target_hex")
            amt = action.get("amount_base_units")
            if amt is None or amt == "0":
                raise VerificationError(f"authorized {operation} missing positive amount_base_units")
    else:
        raise VerificationError(f"unknown verdict: {verdict}")

    expected_integrity = _validate_lower_hex(
        receipt.get("receipt_integrity_sha256"), 64, "receipt_integrity_sha256"
    )
    recomputed = compute_receipt_integrity_sha256(receipt)
    if not hmac.compare_digest(expected_integrity, recomputed):
        raise VerificationError(
            f"SHA-256 integrity mismatch for {scenario_id}: "
            f"expected {expected_integrity}, recomputed {recomputed}"
        )

    if seen_sessions is not None:
        if scenario_id in seen_sessions or expected_integrity in seen_sessions or digest_hex in seen_sessions:
            raise VerificationError(f"replayed session_id / receipt rejected: {scenario_id}")

    if seal.get("algorithm") != "ml-dsa-65" or seal.get("domain_tag") != SEAL_DOMAIN_TAG:
        raise VerificationError("invalid receipt_seal algorithm or domain_tag")

    seal_pk_sha256 = _validate_lower_hex(
        seal.get("public_key_sha256"), 64, "receipt_seal.public_key_sha256"
    )
    pk_hex = _validate_lower_hex(
        seal.get("public_key_hex"), ML_DSA_65_PK_HEX_LEN, "receipt_seal.public_key_hex"
    )
    sig_hex = _validate_lower_hex(
        seal.get("signature_hex"), ML_DSA_65_SIG_HEX_LEN, "receipt_seal.signature_hex"
    )

    pk_bytes = bytes.fromhex(pk_hex)
    sig_bytes = bytes.fromhex(sig_hex)
    if len(pk_bytes) != ML_DSA_65_PK_BYTES:
        raise VerificationError(f"invalid ML-DSA-65 public key byte length: {len(pk_bytes)}")
    if len(sig_bytes) != ML_DSA_65_SIG_BYTES:
        raise VerificationError(f"invalid ML-DSA-65 signature byte length: {len(sig_bytes)}")

    actual_pk_sha256 = hashlib.sha256(pk_bytes).hexdigest()
    if not hmac.compare_digest(actual_pk_sha256, seal_pk_sha256):
        raise VerificationError("public_key_sha256 does not match SHA-256(public_key_hex)")
    if pinned_pubkey_sha256 is not None and not hmac.compare_digest(actual_pk_sha256, pinned_pubkey_sha256):
        raise VerificationError("public_key_sha256 does not match pinned signer key")

    seal_msg = f"{SEAL_DOMAIN_TAG}\n{expected_integrity}".encode("ascii")
    if not ml_dsa_65_verify(pk_bytes, seal_msg, sig_bytes):
        raise VerificationError("ML-DSA-65 cryptographic signature verification failed")


def run_tamper_self_test(
    receipt: dict[str, Any],
    pin: str | None,
    *,
    now_unix_secs: int | None,
    max_age_secs: int,
) -> None:
    """Mutates evaluated_at_unix_secs and signature LSB on a verified receipt and asserts rejection."""
    tampered_ts = copy.deepcopy(receipt)
    tampered_ts["evaluated_at_unix_secs"] = receipt["evaluated_at_unix_secs"] + 1
    try:
        verify_single_receipt(
            tampered_ts,
            pin,
            now_unix_secs=now_unix_secs,
            max_age_secs=max_age_secs,
        )
    except VerificationError:
        pass
    else:
        raise VerificationError("self-test failed: mutated timestamp receipt was unexpectedly accepted")

    tampered_sig = copy.deepcopy(receipt)
    sig_hex = tampered_sig["receipt_seal"]["signature_hex"]
    flipped_nibble = f"{int(sig_hex[-1], 16) ^ 1:x}"
    tampered_sig["receipt_seal"]["signature_hex"] = sig_hex[:-1] + flipped_nibble
    try:
        verify_single_receipt(
            tampered_sig,
            pin,
            now_unix_secs=now_unix_secs,
            max_age_secs=max_age_secs,
        )
    except VerificationError:
        return
    raise VerificationError("self-test failed: 1-bit flipped signature was unexpectedly accepted")


def _validate_cli_pin(raw_pin: str | None) -> str | None:
    if raw_pin is None:
        return None
    if (
        not isinstance(raw_pin, str)
        or not raw_pin.isascii()
        or len(raw_pin) != 64
        or any(ch not in HEX_ANY_CHARS for ch in raw_pin)
    ):
        raise VerificationError(
            "invalid --pin-pubkey-sha256: expected 64-character hexadecimal SHA-256 digest"
        )
    return raw_pin.lower()


def _parse_cli_uint(raw_val: str | None, name: str, minimum: int = 0) -> int | None:
    if raw_val is None:
        return None
    if not raw_val.isascii() or not raw_val.isdigit():
        raise VerificationError(f"invalid {name}: expected non-negative ASCII integer")
    val = int(raw_val)
    if val < minimum or val > U64_MAX:
        raise VerificationError(f"out-of-range {name}: {val}")
    return val


def _load_seen_sessions(path: pathlib.Path | None) -> set[str]:
    if path is None:
        return set()
    raw = _read_bounded_text(path, "seen-sessions file")
    stripped = raw.strip()
    if stripped.startswith("["):
        parsed = _parse_hardened_json(stripped, str(path))
        if not isinstance(parsed, list) or not all(isinstance(x, str) for x in parsed):
            raise VerificationError("seen-sessions JSON file must be an array of strings")
        return {_clean_token(x, "seen_session_entry") for x in parsed}
    out: set[str] = set()
    for line in raw.splitlines():
        item = line.strip()
        if item:
            out.add(_clean_token(item, "seen_session_entry"))
    return out


def main() -> int:
    parser = _FailClosedArgumentParser(
        description="Verify Decern Stage-0 Sepolia receipt or bundle (with NIST FIPS 204 ML-DSA-65)."
    )
    parser.add_argument("path", type=pathlib.Path, help="Path to Stage-0 receipt or bundle JSON")
    parser.add_argument(
        "--pin-pubkey-sha256",
        default=None,
        help="Optional expected 64-char SHA-256 hex of the Stage-0 ML-DSA-65 receipt signer key",
    )
    parser.add_argument(
        "--now-unix-secs",
        default=None,
        help="Optional Unix timestamp (UTC seconds) to enforce receipt freshness",
    )
    parser.add_argument(
        "--max-age-secs",
        default=str(DEFAULT_MAX_AGE_SECS),
        help="Maximum receipt age in seconds when --now-unix-secs is supplied (default: 86400)",
    )
    parser.add_argument(
        "--seen-sessions-file",
        type=pathlib.Path,
        default=None,
        help="Optional file listing previously consumed scenario_ids / integrity hashes to reject replays",
    )
    parser.add_argument(
        "--self-test-tamper",
        action="store_true",
        help="Also verify that mutated timestamp and 1-bit flipped signature copies fail closed",
    )

    try:
        args = parser.parse_args()
        cli_pin = _validate_cli_pin(args.pin_pubkey_sha256)
        now_unix_secs = _parse_cli_uint(args.now_unix_secs, "--now-unix-secs")
        max_age_secs = _parse_cli_uint(args.max_age_secs, "--max-age-secs", minimum=1)
        assert max_age_secs is not None
        seen_sessions = _load_seen_sessions(args.seen_sessions_file)

        raw = _read_bounded_text(args.path, "receipt JSON")
        doc = _parse_hardened_json(raw, str(args.path))

        if not isinstance(doc, dict):
            raise VerificationError("JSON root must be an object")

        if "receipts" in doc or doc.get("schema") == BUNDLE_SCHEMA:
            _require_dict_exact_keys(doc, BUNDLE_KEYS, "bundle")
            if doc.get("schema") != BUNDLE_SCHEMA:
                raise VerificationError(f"unsupported bundle schema: {doc.get('schema')}")
            bundle_signer_pin = _validate_lower_hex(
                doc.get("receipt_signer_pubkey_sha256"),
                64,
                "receipt_signer_pubkey_sha256",
            )
            if cli_pin is not None and not hmac.compare_digest(bundle_signer_pin, cli_pin):
                raise VerificationError(
                    "bundle receipt_signer_pubkey_sha256 does not match --pin-pubkey-sha256"
                )
            receipts = doc.get("receipts")
            if not isinstance(receipts, list) or not receipts:
                raise VerificationError("empty receipts array in Stage-0 bundle")

            bundle_scenarios: set[str] = set()
            bundle_digests: set[str] = set()
            zero_digest = "0x" + "00" * 32
            for item in receipts:
                if not isinstance(item, dict):
                    raise VerificationError("bundle receipt element must be a JSON object")
                verify_single_receipt(
                    item,
                    bundle_signer_pin,
                    now_unix_secs=now_unix_secs,
                    max_age_secs=max_age_secs,
                    seen_sessions=seen_sessions,
                )
                if not hmac.compare_digest(item["receipt_seal"]["public_key_sha256"], bundle_signer_pin):
                    raise VerificationError(
                        "receipt public_key_sha256 does not match bundle signer fingerprint"
                    )
                sid = item["scenario_id"]
                if sid in bundle_scenarios:
                    raise VerificationError(f"replayed duplicate scenario_id in bundle: {sid}")
                bundle_scenarios.add(sid)
                s_digest = item["action"]["signable_digest_hex"]
                if s_digest != zero_digest:
                    if s_digest in bundle_digests:
                        raise VerificationError(
                            f"replayed duplicate signable_digest_hex in bundle: {s_digest}"
                        )
                    bundle_digests.add(s_digest)

            if args.self_test_tamper:
                run_tamper_self_test(
                    receipts[-1],
                    bundle_signer_pin,
                    now_unix_secs=now_unix_secs,
                    max_age_secs=max_age_secs,
                )
            print(
                f"VERIFY_OK: {len(receipts)}/{len(receipts)} Stage-0 Sepolia receipts verified "
                f"(ML-DSA-65 cryptographic seal valid, signer_pubkey_sha256={bundle_signer_pin})"
            )
            return 0

        if doc.get("schema") == RECEIPT_SCHEMA:
            verify_single_receipt(
                doc,
                cli_pin,
                now_unix_secs=now_unix_secs,
                max_age_secs=max_age_secs,
                seen_sessions=seen_sessions,
            )
            if args.self_test_tamper:
                run_tamper_self_test(
                    doc,
                    cli_pin,
                    now_unix_secs=now_unix_secs,
                    max_age_secs=max_age_secs,
                )
            print(
                f"VERIFY_OK: receipt {doc.get('scenario_id')} ({doc.get('verdict')}) "
                "verified (SHA-256 + NIST FIPS 204 ML-DSA-65 signature valid)"
            )
            return 0

        raise VerificationError("JSON root is neither a Stage-0 receipt nor a Stage-0 bundle")
    except VerificationError as exc:
        print(f"VERIFY_FAILED: {exc}", file=sys.stderr)
        return 1
    except Exception as exc:  # noqa: BLE001
        print(f"VERIFY_FAILED: unexpected internal error: {exc}", file=sys.stderr)
        return 1


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