#!/usr/bin/env python3
"""
verify_decern_boundary.py (v1.0.0)
Standalone Black-Box Boundary Invariant Checker for Decern by PriviNet

Scope & Honesty Notice:
  This zero-dependency Python 3.9+ script models and exhaustively checks the
  public black-box authorization boundary rules described at:
    - https://privinet.net/decern
    - https://privinet.net/decern-technical
    - https://privinet.net/decern-verification
  It enumerates all 864 combinations of asset rails, caller wire mutations,
  quorum approval counts, replay/expiration states, intent-digest bindings, and
  caller credential states, verifying four black-box safety properties:
    INV-1: Zero live signing keys in caller/UI/agent; gate cannot be bypassed.
    INV-2: Raw-byte equivalence (wire_digest == approved_intent_digest & cap).
    INV-3: Strict 2-of-3 approval quorum + single-use nonce + active TTL.
    INV-4: Standalone offline receipt tamper detection (+1 unit or field edit).

  This public reference model is NOT an external cryptographic review of the
  private Rust implementation (U.S. provisional patent 64/130,485 pending).
"""

from __future__ import annotations

import hashlib
import itertools
import json
import sys
from dataclasses import dataclass


@dataclass(frozen=True)
class RailSpec:
    rail_id: str
    policy_cap: int
    allowlisted_dest: str
    safe_operation_flag: int  # 0 = standard Call, 1 = DelegateCall (forbidden)


RAILS: tuple[RailSpec, ...] = (
    RailSpec("evm_sepolia_safe_usdc", 2_500_000, "0x71C95911E9a5D330f4D621842EC243EE1343292e", 0),
    RailSpec("evm_token_mint_supply_cap", 1_000_000, "0x71C95911E9a5D330f4D621842EC243EE1343292e", 0),
    RailSpec("bitcoin_signet_taproot", 2_500_000_000, "tb1qallowlistedcoldvault0000000000000000000", 0),
)


def sha256_hex(payload: str) -> str:
    return hashlib.sha256(payload.encode("utf-8")).hexdigest()


def canonical_wire(rail: RailSpec, dest: str, amount: int, op_flag: int, nonce: str) -> str:
    return f"rail={rail.rail_id}|dest={dest}|amount={amount}|op={op_flag}|nonce={nonce}"


def evaluate_decern_gate(
    rail: RailSpec,
    raw_wire_dest: str,
    raw_wire_amount: int,
    raw_wire_op_flag: int,
    nonce: str,
    approved_intent_digest: str,
    valid_ml_dsa_65_approvals: int,
    nonce_consumed: bool,
    ttl_expired: bool,
    caller_holds_vault_key: bool,
) -> dict:
    if caller_holds_vault_key:
        raise AssertionError("Architecture violation: caller/UI/agent must hold 0 live keys.")

    reconstructed_wire = canonical_wire(rail, raw_wire_dest, raw_wire_amount, raw_wire_op_flag, nonce)
    reconstructed_digest = sha256_hex(reconstructed_wire)

    reasons: list[str] = []
    if raw_wire_op_flag != 0:
        reasons.append("REFUSED_DISGUISED_DELEGATECALL")
    if raw_wire_dest != rail.allowlisted_dest:
        reasons.append("REFUSED_DESTINATION_MISMATCH")
    if raw_wire_amount <= 0 or raw_wire_amount > rail.policy_cap:
        reasons.append("REFUSED_OVER_POLICY_CAP")
    if reconstructed_digest != approved_intent_digest:
        reasons.append("REFUSED_INTENT_DIGEST_MISMATCH")
    if valid_ml_dsa_65_approvals < 2:
        reasons.append("REFUSED_SUBQUORUM")
    if nonce_consumed:
        reasons.append("REFUSED_REPLAYED_NONCE")
    if ttl_expired:
        reasons.append("REFUSED_EXPIRED_APPROVAL")

    authorized = len(reasons) == 0
    decision = "AUTHORIZED_QUORUM_MATCH" if authorized else reasons[0]

    receipt = {
        "rail_id": rail.rail_id,
        "nonce": nonce,
        "decision": decision,
        "co_signatures_emitted": 1 if authorized else 0,
        "reconstructed_amount": raw_wire_amount,
        "reconstructed_dest": raw_wire_dest,
        "reconstructed_op_flag": raw_wire_op_flag,
        "valid_ml_dsa_65_approvals": valid_ml_dsa_65_approvals,
        "approved_intent_sha256": approved_intent_digest,
        "reconstructed_wire_sha256": reconstructed_digest,
    }
    receipt_body = json.dumps(receipt, sort_keys=True, separators=(",", ":"))
    receipt["receipt_seal_sha256"] = sha256_hex(receipt_body)
    return receipt


def verify_receipt_offline(receipt: dict) -> bool:
    copy_obj = {k: v for k, v in receipt.items() if k != "receipt_seal_sha256"}
    expected = sha256_hex(json.dumps(copy_obj, sort_keys=True, separators=(",", ":")))
    return expected == receipt.get("receipt_seal_sha256")


def run_exhaustive_check() -> int:
    wire_mutations = ("clean", "disguised_delegatecall", "destination_swap", "over_cap_10x")
    quorum_counts = (0, 1, 2, 3)
    freshness_states = ("fresh", "replayed_nonce", "expired_ttl")
    binding_states = ("matches_clean_intent", "bound_to_other_tx", "corrupted_intent_digest")
    caller_bypass_attempts = (False, True)  # True = caller attempts direct call without gate token

    total_states = 0
    authorized_states = 0
    refused_states = 0
    unauthorized_cosigs = 0
    offline_tamper_catches = 0

    for rail, mutation, quorum, freshness, binding, bypass_attempt in itertools.product(
        RAILS, wire_mutations, quorum_counts, freshness_states, binding_states, caller_bypass_attempts
    ):
        total_states += 1
        nonce = f"nonce-{total_states:04d}"
        clean_intent_str = canonical_wire(rail, rail.allowlisted_dest, rail.policy_cap, 0, nonce)
        clean_intent_digest = sha256_hex(clean_intent_str)

        if binding == "matches_clean_intent":
            intent_digest = clean_intent_digest
        elif binding == "bound_to_other_tx":
            intent_digest = sha256_hex(clean_intent_str + "|prior_tx")
        else:
            intent_digest = "0" * 64

        dest = rail.allowlisted_dest
        amount = rail.policy_cap
        op_flag = 0
        if mutation == "disguised_delegatecall":
            op_flag = 1
        elif mutation == "destination_swap":
            dest = "0xDeAdBeEf99999999999999999999999999999999"
        elif mutation == "over_cap_10x":
            amount = rail.policy_cap * 10

        nonce_consumed = freshness == "replayed_nonce"
        ttl_expired = freshness == "expired_ttl"

        effective_quorum = 0 if bypass_attempt else quorum

        receipt = evaluate_decern_gate(
            rail=rail,
            raw_wire_dest=dest,
            raw_wire_amount=amount,
            raw_wire_op_flag=op_flag,
            nonce=nonce,
            approved_intent_digest=intent_digest,
            valid_ml_dsa_65_approvals=effective_quorum,
            nonce_consumed=nonce_consumed,
            ttl_expired=ttl_expired,
            caller_holds_vault_key=False,
        )

        should_allow = (
            mutation == "clean"
            and binding == "matches_clean_intent"
            and freshness == "fresh"
            and effective_quorum >= 2
        )

        # INV-1, INV-2, INV-3 check
        if should_allow:
            assert receipt["co_signatures_emitted"] == 1, f"False refusal on valid state {total_states}"
            authorized_states += 1
        else:
            if receipt["co_signatures_emitted"] != 0:
                unauthorized_cosigs += 1
            assert receipt["co_signatures_emitted"] == 0, f"Safety violation on state {total_states}"
            refused_states += 1

        # INV-4: Standalone offline receipt verification + tamper rejection
        assert verify_receipt_offline(receipt), f"Valid receipt failed offline verification at state {total_states}"
        tampered = dict(receipt)
        tampered["reconstructed_amount"] = receipt["reconstructed_amount"] + 1
        assert not verify_receipt_offline(tampered), f"Tampered receipt (+1) was not caught at state {total_states}"
        offline_tamper_catches += 1

    print("DECERN BLACK-BOX BOUNDARY MODEL CHECKER v1.0.0")
    print("=" * 66)
    print(f"Exhaustive Cartesian states evaluated : {total_states}")
    print(f"Authorized states (valid 2-of-3/3-of-3): {authorized_states}")
    print(f"Refused attack/mismatch/replay states : {refused_states}")
    print(f"Unauthorized co-signatures emitted    : {unauthorized_cosigs}")
    print(f"Offline +1 tamper mutations caught    : {offline_tamper_catches}/{total_states}")
    print("-" * 66)
    print("INV-1 (Zero Caller Keys / No Bypass)  : PASS")
    print("INV-2 (Raw-Byte Digest Equivalence)   : PASS")
    print("INV-3 (2-of-3 Quorum & Nonce Replay)  : PASS")
    print("INV-4 (Offline Receipt Tamper Check)  : PASS")
    print("=" * 66)
    print("RESULT: ALL 4 PUBLIC BLACK-BOX BOUNDARY INVARIANTS VERIFIED (EXIT 0).")
    return 0


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