#!/usr/bin/env python3
"""
Deterministic Consistency & Bounds Checker for the zBTC Protocol Specification
v2 (v3.1.0-rfc — Zero-Federation Phased Architecture, R8 Hardened:
    Stage 0 Verify Bitcoin SPV Oracle + Erlang-Hardened PTLC/LN
 -> Stage 1A Right-Sized BitVMX (n=8, M=3..5, N=7, Core >= 29.0) + Sovereign ZK Rollup
  | Stage 1B clArk Alternative Gate
 -> Stage 2 Zero-TTP Scale & Upgrade).

SCOPE & HONESTY DISCLOSURE:
  This script checks internal mathematical consistency using pure Python 3 stdlib ONLY:
    1.  Stage 0 coinbase midstate 1-/2-block SHA-256 final padding across all 64 remainders + >= 65 B filter (R8-M06)
    2.  Stage 0 honest go-zenon Plasma/wire ceilings, Dynamic Plasma 5-param pinning, & Bitcoin L1 0x02 DA cap (R8-M08)
    3.  Stage 0 exact Erlang/Poisson survival tails for PTLC (>= 48h) & LN HTLC (>= 24h) under 2.3x slowdown (R8-H07)
    4.  Proposition 2 complete hard-BTC capital accounting: locked vs operational baseline vs multi-dispute headroom (R8-M09)
    5.  Stage 1A BitVMX-CPU n=8 W-OTS + 10x153 vB P2A CPFP & Core >= 29.0 BIP-431 TRUC v3 compliance (R8-H04/H05)
    6.  Stage 1A widened timelocks (T_step=72 -> 1,584 < 1,728 < 1,872 < 2,016) & acyclic vault_id Lamport TakeTx (R8-C01)
    7.  Stage 1A native-L1 Stake_r ChalPayoutEscrow verifier EV @ 500 & 750 sat/vB, 16.53 kvB, lockup, 30% zBTC discount (R8-H02/N05)
    8.  Stage 1A exact 2^M Hall's Marriage Theorem checker + counterexample regression & cyclic (H(exitId)+r) mod M (R8-C04/M03)
    9.  Stage 1A multi-tier {0.50, 0.25, 0.25} bank-run exit bounds (T_cooldown=13.0d) & TransferCredit consolidation (R8-M04)
    10. Stage 1A K >= 18 unpublished-fork heuristic (Cap_user + M*B_zbtc) & Budish winning-fork flow-cost sensitivity (R8-H03)
    11. Stage 1B clArk active liquidity & log2(N) branch exit weights
    12. Non-no-op randomized state-machine simulation separating fifo_assign & take_confirmed across T_take with explicit
        AssignedObligations (A) conservation (V_unassigned + V_assigned == C + L + E + R + A + B), AdmissionTicketUTXO cap
        mutual exclusion, k=20 single-block ExitSlotUTXO grief burst, TransferCredit, real Bitcoin reorgs, and slashes
        (R8-C02, R8-C03, R8-H01, R8-N05, R8-M04).

  Every modeled constant is explicitly prefixed by provenance:
    - SOURCED_             : Bitcoin BIPs, historical chain telemetry, or go-zenon origin/dev
    - POLICY_              : Explicit protocol design parameters
    - PRE_MAINNET_TARGET_  : BitVMX-CPU / rollup sizing targets to be empirically measured on Signet (Gates G1-G5)

  This script is a consistency & bounds checker — NOT an empirical Signet benchmark
  and NOT a substitute for independent cryptographic/implementation audits.

Run: `python3 -I scripts/verify_spec_bounds.py`
"""
import hashlib
import math
import random
import struct

SAT = 100_000_000

# ==============================================================================
# SOURCED CONSTANTS (Bitcoin BIPs, Historical Telemetry, go-zenon origin/dev)
# ==============================================================================
SOURCED_BIP431_TRUC_MAX_VB = 10_000                 # BIP-431 TRUC v3 parent max vBytes
SOURCED_BIP431_TRUC_CHILD_MAX_VB = 1_000            # BIP-431 TRUC v3 child max vBytes
SOURCED_BTC_CORE_MIN_VERSION_P2A_ZERO = "29.0"      # Core >= 29.0 required for 0-sat P2A ephemeral dust (R8-M09)
SOURCED_BIP342_MAX_STACK_ITEMS = 1_000              # BIP-342 Tapscript max stack elements
SOURCED_BIP342_MAX_PUSH_BYTES = 520                 # BIP-342 Tapscript max push element size
SOURCED_BIP141_MAX_STRIPPED_BLOCK_BYTES = 1_000_000 # Bitcoin consensus max non-witness block bytes
SOURCED_BTC_MAX_BLOCK_WEIGHT = 4_000_000            # Bitcoin consensus 4 MWU = 1,000,000 vB/block
SOURCED_BTC_TARGET_BLOCK_SECS = 600                 # 10 min nominal Bitcoin block interval
SOURCED_BTC_BLOCKS_PER_DAY = 144                    # Nominal blocks/day
SOURCED_JUNE2021_SLOW_WEEKLY_MULT = 2.0             # June 2021 China ban: ~1.95-2.0x 7d avg
SOURCED_JUNE2021_SLOW_DAILY_MULT = 2.3              # June 2021 China ban: ~23 min/blk daily peak
SOURCED_APR2024_MEDIAN_FEE_SATVB = 1_805            # April 2024 halving/Runes median peak
SOURCED_P2A_CPFP_CHILD_VB = 153                     # Standard 1-in-P2TR + 1-in-P2A -> 1-out-P2TR CPFP child (vB)

# Bitcoin block subsidy schedule (BTC/block) across halvings
SOURCED_BTC_SUBSIDY_BY_ERA = {
    "2024-2028": 3.125,
    "2028-2032": 1.5625,
    "2032-2036": 0.78125,
    "2036-2040": 0.390625,
}

# ZNN market-cap context (Nov 2026 observed range; 0% ZNN in BTC custody safety!)
SOURCED_ZNN_MCAP_BTC_LOW = 25.0
SOURCED_ZNN_MCAP_BTC_HIGH = 33.0

# go-zenon origin/dev protocol constants
SOURCED_ZNN_MAX_DATA_LENGTH = 16_384                # dev:vm/constants/plasma.go:67
SOURCED_ZNN_ACCOUNT_BLOCK_BASE_PLASMA = 21_000      # dev:vm/constants/plasma.go
SOURCED_ZNN_AB_BYTE_DATA_PLASMA = 68                # dev:vm/constants/plasma.go (DynamicPlasmaSpork)
SOURCED_ZNN_EMBEDDED_SIMPLE_TIER = 52_500           # 2.5 * 21,000
SOURCED_ZNN_EMBEDDED_HEAVY_SPV_TIER = 73_500        # 3.5 * 21,000
SOURCED_ZNN_PLASMA_PER_QSR = 2_100                  # 1 QSR = 1 fusion unit = 2,100 Plasma @ price 1,000
SOURCED_ZNN_POW_DIFF_PER_PLASMA = 1_500             # dev:vm/constants/plasma.go
SOURCED_ZNN_MIN_RESOURCE_PRICE = 1_000              # dev:dp/dp.go
SOURCED_ZNN_DP_DEFAULT_MAX_BASE_PLASMA = 4_200_000  # dev:vm/embedded/definition/plasma.go:97
SOURCED_ZNN_DP_UPPER_MAX_BASE_PLASMA = 2_100_000_000  # dev:vm/embedded/definition/plasma.go:63
SOURCED_ZNN_DP_LOWER_MAX_BASE_PLASMA = 210_000      # dev:vm/embedded/definition/plasma.go:66
SOURCED_ZNN_OBSERVED_MOMENTUM_SECS = 11.4           # dev:vm/embedded/definition/spork.go (11.35-11.46s)
SOURCED_ZNN_CHAIN_BRIDGE_ROLLBACK = 30              # dev:protocol/chain_bridge.go:293
SOURCED_ZNN_MAX_MOMENTUM_CONTENT_BYTES = 8 * 1024 * 1024  # dev:verifier/momentum.go:93 (8 MiB)
SOURCED_ZNN_PROTOCOL_MAX_MSG_SIZE = 10 * 1024 * 1024      # dev:protocol/protocol.go (10 MiB)
SOURCED_ZNN_SOFT_RESPONSE_LIMIT = 2 * 1024 * 1024         # dev:protocol/protocol.go (2 MiB)
SOURCED_ZNN_MAX_DETAILED_MOMENTUM_WIRE = (
    SOURCED_ZNN_PROTOCOL_MAX_MSG_SIZE - SOURCED_ZNN_SOFT_RESPONSE_LIMIT - 4096
)  # 8,384,512 B (dev:protocol/protocol.go:70)
SOURCED_ZNN_MIN_ACCOUNT_BLOCK_WIRE_LOW = 300
SOURCED_ZNN_MIN_ACCOUNT_BLOCK_WIRE_HIGH = 350

# ==============================================================================
# POLICY PARAMETERS (Stage 0, Stage 1A BitVMX v3.1.0-rfc, Stage 1B clArk)
# ==============================================================================
POLICY_PINNED_MAX_BASE_PLASMA_FLOOR = 2_100_000     # Pinned >= 2.1M Plasma/Momentum
POLICY_PINNED_MAX_PRICE_CHANGE_PCT = 25             # MaxPriceChangePercent <= 25%
POLICY_PINNED_MIN_TARGET_SHARE_PCT = 25             # Fused/Pow targets >= 25% of 2.1M floor (525,000)
POLICY_PINNED_MIN_PRICE_DENOM = 8                   # PriceChangeDenominator >= 8 (spec/05 §2.2)
POLICY_STAGE0_MIN_STRIPPED_TX_BYTES = 65            # Rejects <= 64 B CVE-2017-12842 leaves (R8-M06)
POLICY_STAGE0_MAX_STRIPPED_TX_BYTES = 6_144         # Stage 0 SPV Event Oracle tx cap
POLICY_STAGE0_MAX_STORAGE_OPS = 24                  # Per-call L1 storage op ceiling

# Stage 0 Erlang-Hardened PTLC / LN non-custodial swap parameters (R8-H07)
POLICY_PTLC_BTC_CSV_BLOCKS = 72                     # Automated high-fee RBF refund watchtower fires at h_conf + 72
POLICY_PTLC_ZNN_DURATION_SECS = 172_800             # >= 48.0 hours (P(T_72 > 48h | 2.3x) < 1e-6!)
POLICY_LN_DELTA_SAFETY_BLOCKS = 36
POLICY_LN_OUTBOUND_DELTA_SAFETY_SECS = 86_400       # >= 24.0 hours (P(T_36 > 24h | 2.3x) < 2e-4!)

# Stage 1A Right-Sized BitVMX (n=8) + Sovereign ZK Rollup parameters
POLICY_BITVMX_N_BRANCH = 8                          # n=8 (3 bits/round -> 7 intermediate hashes)
POLICY_BITVMX_SEARCH_ROUNDS = 9                     # 8^9 = 2^27 = 134,217,728 RV32IM wrapped-SNARK verifier ops
POLICY_BITVMX_M_MIN = 3                             # Minimal competitive operator count
POLICY_BITVMX_M_MAX = 5                             # Pilot operator count
POLICY_BITVMX_L_LANES = 1                           # Lanes per operator
POLICY_BITVMX_N_VERIFIERS = 7                       # Pre-committed online verifiers
POLICY_BITVMX_R_ROUNDS = 64                         # Pre-signed rounds per lane
POLICY_STAGE2_TOTAL_LANES = 40                      # Stage 2 scaled lane count (40 * 64 = 2,560 leaves)

POLICY_VAULT_TIERS_SATS = (50_000_000, 25_000_000, 25_000_000)  # {0.50, 0.25, 0.25} BTC per 1.0 BTC deposit
POLICY_VAULT_ALT_SPLIT_SATS = (50_000_000, 50_000_000)          # Optional {0.50, 0.50} split comparison
POLICY_MAX_VAULT_DENOM_SATS = 50_000_000                        # 0.50 BTC ceiling per vault UTXO
POLICY_MIN_EXIT_SATS = 100_000                                  # 0.001 BTC normative dust floor (R8-M05)
POLICY_NEW_LEAF_DEPOSIT_SATS = 500                              # Refundable new-SMT-leaf deposit (R8-M01)
POLICY_MAX_NEW_LEAVES_PER_EPOCH = 1_000                         # <= 1,000 new SMT leaves per 6-block epoch (R8-M01)

# Stage 1A Hard-Partitioned Per-Lane Bond & Native-L1 Verifier Economics (R8-H01, R8-H02, R8-N05)
POLICY_BOND_BTC_SATS = 200_000_000                  # 2.00 BTC L1 Stake_r bond
POLICY_B_ZBTC_CUSTODY_SATS = 50_000_000             # 0.50 BTC maxVaultDenom Lamport restitution
POLICY_B_ZBTC_EQUIV_BOUNTY_SATS = 5_000_000         # 0.05 BTC Lamport equivocation bounty
POLICY_B_CUSTODY_TOTAL_SATS = (
    POLICY_B_ZBTC_CUSTODY_SATS + POLICY_B_ZBTC_EQUIV_BOUNTY_SATS
)                                                   # 0.55 BTC HARD-PARTITIONED B_custody (NEVER debited by grief!)
POLICY_B_GRIEF_TOTAL_SATS = 5_000_000               # 0.05 BTC HARD-PARTITIONED B_grief (ExitSlotUTXO grief only!)
POLICY_B_ZBTC_TOTAL_SATS = POLICY_B_CUSTODY_TOTAL_SATS + POLICY_B_GRIEF_TOTAL_SATS  # 0.60 BTC total/lane
POLICY_LANE_TOTAL_BOND_SATS = POLICY_BOND_BTC_SATS + POLICY_B_ZBTC_TOTAL_SATS       # 2.60 BTC/lane

POLICY_F_CHAL_SATS = 40_000_000                     # 0.40 BTC verifier challenge escrow
POLICY_VERIFIER_NATIVE_L1_PAYOUT_SATS = 15_000_000  # 0.15 BTC NATIVE L1 BTC payout per active challenger (R8-H02!)
POLICY_MIN_L1_STAKE_BURN_SATS = (
    POLICY_BOND_BTC_SATS - POLICY_BITVMX_N_VERIFIERS * POLICY_VERIFIER_NATIVE_L1_PAYOUT_SATS
)                                                   # 0.95 BTC minimum immediate OP_RETURN burn when all 7 challenge!
POLICY_EXIT_GRIEF_SLASH_SATS = 1_000_000            # 0.01 BTC per-exit grief penalty (pro-rata capped at B_grief!)
POLICY_DESIGN_SUSTAINED_FEE_SATVB = 500             # 500 sat/vB primary sustained design envelope
POLICY_STRESS_SUSTAINED_FEE_SATVB = 750             # 750 sat/vB stress-test verifier envelope
POLICY_VERIFIER_LOCKUP_COST_SATS = 285_000          # 0.00285 BTC conservative capital lockup cost (R8-H02)
POLICY_CRISIS_ZBTC_DISCOUNT = 0.30                  # 30% crisis zBTC discount stress test (0% impact on native L1!)

# Stage 1A Operational Reserve Accounting (R8-M09)
POLICY_OP_RESERVE_VERIFIER_CPFP_PER_V_BTC = 0.10    # 0.10 BTC * 7 = 0.70 BTC verifier CPFP reserve
POLICY_OP_RESERVE_DA_BATCHER_BTC = 0.50             # 0.50 BTC DA batcher L1 fee float
POLICY_OP_RESERVE_TOPUP_PER_OP_BTC = 0.25           # 0.25 * M BTC operator top-up/CPFP reserve

# Stage 1A Widened Simultaneous-Challenge BitVMX Timelocks (T_step = 72 blks = 12h, R8-H04)
POLICY_T_CHAL_WINDOW = 144                          # Simultaneous [0, 144] challenge window (24h)
POLICY_T_STEP = 72                                  # 12h per bisection step (widened from 48!)
POLICY_T_TAKE = 1_728                               # 12.0d (> max_dispute_end = 1,584; +144 blk margin!)
POLICY_T_COOLDOWN = 1_872                           # 13.0d (1,728 + 144-blk Lamport equivocation slash window)
POLICY_T_RETIRE = 2_016                             # 14.0d Stake retirement CSV
POLICY_T_EXIT_CANCEL = 288                          # 48h user unilateral EXIT_CANCEL leaf (restores zBTC only)
POLICY_K_MIN_FLOOR = 18                             # Hard minimum K >= 18 blocks (R8-H03)

# Stage 1A Capital & TVL Profiles (Cap_TVL_total = Cap_user + M * B_zbtc)
POLICY_STAGE1A_PROFILES = {
    "M=3 (<=10 user / 11.8 tot)": {"M": 3, "cap_user_btc": 10.0, "cap_total_btc": 11.80, "float_btc": 2.20, "K_2024": 18},
    "M=5 (<=15 user / 18.0 tot)": {"M": 5, "cap_user_btc": 15.0, "cap_total_btc": 18.00, "float_btc": 3.00, "K_2024": 18},
}
# Tiers keyed by Cap_user -> Cap_TVL_total (incl. M * 0.60 BTC B_zbtc: M=3,5,20,40)
POLICY_TVL_TIERS_TOTAL_BTC = {
    10: 11.80,
    15: 18.00,
    50: 62.00,
    200: 224.00,
}
POLICY_CONFIGURED_K_BY_ERA = {
    "2024-2028": {10: 18, 15: 18, 50: 42, 200: 144},
    "2028-2032": {10: 18, 15: 24, 50: 80, 200: 288},
    "2032-2036": {10: 32, 15: 48, 50: 160, 200: 576},
}

# ==============================================================================
# PRE-MAINNET TARGETS (BitVMX-CPU / Rollup / BitVM2 / clArk — Signet-Gated)
# ==============================================================================
PRE_MAINNET_TARGET_ROLLUP_TX_DATA_BYTES = 110       # Signed rollup transfer in AccountBlock.Data
PRE_MAINNET_TARGET_DEPOSIT_CERTBLOB_BYTES = 104     # Acyclic OP_DROP certBlob <= 520 B
PRE_MAINNET_TARGET_WOTS_DIGIT_WU = 95.5             # Per base-16 W-OTS digit weight (WU)
PRE_MAINNET_TARGET_BISECTION_OVERHEAD_VB = 250.0    # Per prover bisection tx non-WOTS overhead (vB)
PRE_MAINNET_TARGET_START_TX_VB = 3_000.0            # Prover StartTx vBytes
PRE_MAINNET_TARGET_FINAL_TRACE_TX_VB = 5_000.0      # Prover FinalTraceTx vBytes
PRE_MAINNET_TARGET_CHALLENGE_TX_VB = 350.0          # Verifier ChallengeTx vBytes
PRE_MAINNET_TARGET_VERIFIER_CHOICE_VB = 350.0       # Verifier 3-bit interval choice tx vBytes
PRE_MAINNET_TARGET_EXECUTE_OPCODE_VB = 8_000.0      # Verifier final 1-opcode disprove tx vBytes
PRE_MAINNET_TARGET_PROVER_BASE_CAP_VB = 75_000      # Conservative prover base dispute cap (vB)
PRE_MAINNET_TARGET_VERIFIER_BASE_CAP_VB = 15_000    # Conservative verifier base dispute cap (vB)
PRE_MAINNET_TARGET_CPFP_COUNT_PER_SIDE = 10         # 10 P2A CPFP children per side (10 * 153 = 1,530 vB)
PRE_MAINNET_TARGET_BITVM2_LANE_BOND_BTC_LOW = 13.30
PRE_MAINNET_TARGET_BITVM2_LANE_BOND_BTC_HIGH = 18.175
PRE_MAINNET_TARGET_CLARK_ACTIVE_LIQ_BTC = (2.0, 5.0)
PRE_MAINNET_TARGET_CLARK_VTXO_COUNTS = (64, 128, 256, 512, 1024)


# ==============================================================================
# PURE PYTHON STDLIB MATH, CRYPTO & INVARIANT HELPERS
# ==============================================================================
def ceil_div(a: int, b: int) -> int:
    return (a + b - 1) // b


def compact_size_len(n: int) -> int:
    if n < 253:
        return 1
    if n <= 0xFFFF:
        return 3
    if n <= 0xFFFFFFFF:
        return 5
    return 9


def erlang_survival_prob(k_blocks: int, duration_secs: float, mean_block_secs: float) -> float:
    """
    Exact Erlang(shape=k, rate=lambda) survival probability P(T_k > duration_secs)
    using pure Python stdlib (zero scipy dependency!):
        P(T_k > t) = P(Poisson(lambda * t) <= k - 1) = sum_{j=0}^{k-1} exp(-mu) * mu^j / j!
    Computed in log-space per term for full numerical stability.
    """
    mu = duration_secs / mean_block_secs
    if mu <= 0.0:
        return 1.0
    log_mu = math.log(mu)
    total = 0.0
    for j in range(k_blocks):
        log_term = -mu + j * log_mu - math.lgamma(j + 1)
        total += math.exp(log_term)
    return min(1.0, max(0.0, total))


def erlang_quantile_hours(k_blocks: int, q: float, mean_block_secs: float) -> float:
    """Binary search exact Erlang quantile in hours (P(T_k <= t) = q)."""
    lo = 0.0
    hi = k_blocks * mean_block_secs * 5.0
    for _ in range(80):
        mid = 0.5 * (lo + hi)
        cdf = 1.0 - erlang_survival_prob(k_blocks, mid, mean_block_secs)
        if cdf < q:
            lo = mid
        else:
            hi = mid
    return (0.5 * (lo + hi)) / 3600.0


def abi_embedded_plasma(tier: int, abi_len: int) -> int:
    assert abi_len <= SOURCED_ZNN_MAX_DATA_LENGTH, f"ABI len {abi_len} exceeds 16 KiB"
    return tier + max(0, abi_len - 4) * SOURCED_ZNN_AB_BYTE_DATA_PLASMA


# FIPS 180-4 SHA-256 single-block compression (for real coinbase midstate verification)
_SHA256_IV = (
    0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A,
    0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19,
)
_SHA256_K = (
    0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5,
    0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3, 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174,
    0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC, 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA,
    0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7, 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967,
    0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13, 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85,
    0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3, 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070,
    0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5, 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3,
    0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208, 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2,
)


def _rotr32(x: int, n: int) -> int:
    return ((x >> n) | ((x << (32 - n)) & 0xFFFFFFFF)) & 0xFFFFFFFF


def sha256_compress(state: tuple[int, ...], block64: bytes) -> tuple[int, ...]:
    assert len(block64) == 64
    w = list(struct.unpack(">16I", block64))
    for i in range(16, 64):
        s0 = _rotr32(w[i - 15], 7) ^ _rotr32(w[i - 15], 18) ^ (w[i - 15] >> 3)
        s1 = _rotr32(w[i - 2], 17) ^ _rotr32(w[i - 2], 19) ^ (w[i - 2] >> 10)
        w.append((w[i - 16] + s0 + w[i - 7] + s1) & 0xFFFFFFFF)
    a, b, c, d, e, f, g, h = state
    for i in range(64):
        S1 = _rotr32(e, 6) ^ _rotr32(e, 11) ^ _rotr32(e, 25)
        ch = (e & f) ^ ((~e & 0xFFFFFFFF) & g)
        t1 = (h + S1 + ch + _SHA256_K[i] + w[i]) & 0xFFFFFFFF
        S0 = _rotr32(a, 2) ^ _rotr32(a, 13) ^ _rotr32(a, 22)
        maj = (a & b) ^ (a & c) ^ (b & c)
        t2 = (S0 + maj) & 0xFFFFFFFF
        h, g, f, e, d, c, b, a = g, f, e, (d + t1) & 0xFFFFFFFF, c, b, a, (t1 + t2) & 0xFFFFFFFF
    return tuple((s + x) & 0xFFFFFFFF for s, x in zip(state, (a, b, c, d, e, f, g, h)))


def complete_midstate_double_sha256(midstate_bytes: bytes, tail: bytes, total_len: int) -> tuple[bytes, int]:
    assert len(midstate_bytes) == 32
    assert total_len >= POLICY_STAGE0_MIN_STRIPPED_TX_BYTES, (
        "CVE-2017-12842: totalCoinbaseBytes must be >= 65 (64-byte leaf forbidden)"
    )
    rem = total_len % 64
    assert len(tail) == rem and len(tail) < 64
    padded = bytearray(tail)
    padded.append(0x80)
    while len(padded) % 64 != 56:
        padded.append(0x00)
    padded.extend(struct.pack(">Q", total_len * 8))
    blocks = len(padded) // 64
    assert blocks in (1, 2)
    state = struct.unpack(">8I", midstate_bytes)
    for idx in range(blocks):
        state = sha256_compress(state, bytes(padded[idx * 64 : (idx + 1) * 64]))
    first_round = struct.pack(">8I", *state)
    return hashlib.sha256(first_round).digest(), blocks


def compute_acyclic_vault_id(
    funding_txid: bytes,
    funding_vout: int,
    vault_vout: int,
    amount_sats: int,
    op_bitmask: int,
) -> bytes:
    """Normative R8-C01 acyclic vault_id bound strictly to already-confirmed U_dep_wallet."""
    assert len(funding_txid) == 32
    payload = (
        b"zbtc:vault-id:v1"
        + funding_txid
        + struct.pack(">IIQQ", funding_vout, vault_vout, amount_sats, op_bitmask)
    )
    return hashlib.sha256(payload).digest()


def check_halls_marriage(
    vault_masks: list[int],
    usable_rounds_by_op: list[int],
    headroom_factor: float = 1.0,
) -> tuple[bool, int, int, int]:
    """
    Exact 2^M Hall's Marriage Theorem verification (R8-C04):
      For every non-empty subset T of {0..M-1}:
        |{v in V_live : E(v) <= T}| <= floor(headroom_factor * sum_{i in T} r_i^usable)
    Returns (passes, failing_subset_mask, demand, supply).
    """
    m = len(usable_rounds_by_op)
    assert 1 <= m <= 12
    for mask in range(1, 1 << m):
        demand = sum(1 for vm in vault_masks if vm != 0 and (vm & ~mask) == 0)
        supply_raw = sum(usable_rounds_by_op[i] for i in range(m) if (mask >> i) & 1)
        supply = int(math.floor(headroom_factor * supply_raw))
        if demand > supply:
            return False, mask, demand, supply
    return True, 0, 0, 0


def cyclic_exit_priority(exit_id: bytes, m_active: int) -> list[int]:
    """Normative R8-M03 collision-free cyclic priority k_r = (H(exitId) + r) mod M_active."""
    assert m_active >= 1
    h0 = int.from_bytes(hashlib.sha256(exit_id).digest()[:8], "big")
    return [(h0 + r) % m_active for r in range(m_active)]


def dp_next_price(
    current_price: int,
    used_plasma: int,
    target_plasma: int,
    max_change_pct: int,
    denom: int,
) -> int:
    delta = used_plasma - target_plasma
    num = delta * current_price
    if num >= 0:
        change = (num // target_plasma) // denom
    else:
        change = -((-num // target_plasma) // denom)
    nxt = current_price + change
    max_nxt = (current_price * (100 + max_change_pct)) // 100
    min_nxt = (current_price * (100 - max_change_pct)) // 100
    if nxt > max_nxt:
        nxt = max_nxt
    if nxt < min_nxt:
        nxt = min_nxt
    if nxt < SOURCED_ZNN_MIN_RESOURCE_PRICE:
        nxt = SOURCED_ZNN_MIN_RESOURCE_PRICE
    return nxt


# ==============================================================================
# REAL, NON-NO-OP 2,000-STEP STAGE 1A SOLVENCY & ADVERSARIAL SIMULATION (v3.1.0-rfc)
# ==============================================================================
def run_stage1a_solvency_sim(seed: int = 20261128, steps: int = 2_000) -> dict[str, int]:
    """
    Adversarial state-machine simulation of Stage 1A BitVMX (n=8, M=5, N=7) v3.1.0-rfc:
      - Explicit AssignedObligations (A) namespace separating fifo_assign & take_confirmed across T_take (R8-C02!)
      - Exact conservation: V_unassigned + V_assigned == C + L + E + R + A + B at EVERY step!
      - Denomination-matched AdmissionTicketUTXO Cap_TVL L1 mutual exclusion + deposit race test (R8-C03!)
      - Exact 2^M Hall's Marriage verification on deposit admission & operator slash (R8-C04!)
      - Hard-partitioned B_custody (0.55 BTC) vs B_grief (0.05 BTC) + k=20 single-block ExitSlotUTXO grief burst
        proving ZERO B_custody overflow & ZERO verifier payout impact (R8-H01, R8-N05!)
      - Signed TransferCredit residual consolidation for < 0.25 BTC credits (R8-M04!)
      - Explicit 0x07 RELEASE_ASSIGNMENT + Leaf 2M EXIT_CANCEL + dual-input Disprove slash + cross-operator Lamport slash
      - Genuine Bitcoin reorgs (popping 1..K-1 unconfirmed blocks & discarding orphaned events!)
    """
    rng = random.Random(seed)
    K = POLICY_CONFIGURED_K_BY_ERA["2024-2028"][15]  # 18 blocks
    cap_user_sats = int(15.0 * SAT)
    cap_total_sats = int(18.0 * SAT)  # 15.0 user + 3.0 operator B_zbtc (plus operator free_zbtc buffer)
    all_ops_mask = (1 << POLICY_BITVMX_M_MAX) - 1  # 0b11111

    # Denomination-matched AdmissionTicketUTXO pool (R8-C03):
    # Genesis tickets strictly cap total live vaults <= 20.0 BTC (15 user + 5 operator initial 1.0 BTC vaults)
    ticket_pool = {50_000_000: 20, 25_000_000: 40}  # 20*0.50 + 40*0.25 = 20.0 BTC exact L1 consensus cap!

    # Canonical K-deep rollup state
    users: dict[str, int] = {
        "alice": 0, "bob": 0, "mike": 0, "carol": 0, "dave": 0,
        "insurance_pool": 0, "challenger_bounty_pool": 0,
    }
    rollup_locks: dict[int, int] = {}  # L namespace
    unassigned_vaults: dict[int, dict] = {}  # vault_id -> {"sats", "mask"}
    assigned_vaults: dict[int, dict] = {}    # vault_id -> {"sats", "mask", "op_id", "assigned_h"}
    assigned_obligations: dict[int, int] = {}  # A namespace: vault_id -> sats
    next_vault_id = 1

    operators: dict[int, dict] = {}
    for op_id in range(POLICY_BITVMX_M_MAX):
        # Each operator deposits 1.00 BTC (consuming 2 x Ticket_050) -> 0.55 B_custody + 0.05 B_grief + 0.40 free_zbtc
        for _ in range(2):
            assert ticket_pool[50_000_000] >= 1
            ticket_pool[50_000_000] -= 1
            unassigned_vaults[next_vault_id] = {"sats": 50_000_000, "mask": all_ops_mask}
            next_vault_id += 1
        operators[op_id] = {
            "b_custody": POLICY_B_CUSTODY_TOTAL_SATS,  # 0.55 BTC hard-partitioned
            "b_grief": POLICY_B_GRIEF_TOTAL_SATS,      # 0.05 BTC hard-partitioned
            "free_zbtc": 40_000_000,
            "credit": 0,
            "rounds_left": POLICY_BITVMX_R_ROUNDS,
            "suspended": False,
        }

    pending_exits: dict[int, dict] = {}
    next_exit_id = 1

    finalized_height = 100
    tip_blocks: list[dict] = []
    unconf_spent_exits: set[int] = set()
    unconf_taken_vaults: set[int] = set()
    unconf_released_vaults: set[int] = set()

    counts: dict[str, int] = {
        k: 0 for k in (
            "deposit", "deposit_race_blocked_by_ticket", "transfer", "forced_exit",
            "front_paid", "front_grief", "front_grief_burst_k20", "exit_cancel",
            "fifo_assign", "take_confirmed", "release_assignment", "transfer_credit",
            "disprove_dual_slash", "lamport_equivocation_slash", "topup_op",
            "mine_block", "reorg", "reorg_blocks_reverted", "reorg_events_reverted",
        )
    }

    def rebuild_unconf_locks() -> None:
        unconf_spent_exits.clear()
        unconf_taken_vaults.clear()
        unconf_released_vaults.clear()
        for blk in tip_blocks:
            for ev in blk["events"]:
                kind = ev["kind"]
                if kind in ("front_paid", "front_grief", "exit_cancel"):
                    unconf_spent_exits.add(ev["exit_id"])
                elif kind == "front_grief_burst":
                    for eid in ev["exit_ids"]:
                        unconf_spent_exits.add(eid)
                elif kind in ("take_confirmed", "lamport_equivocation_slash"):
                    unconf_taken_vaults.add(ev["vault_id"])
                elif kind == "release_assignment":
                    unconf_released_vaults.add(ev["vault_id"])

    def run_deterministic_fifo_assign(blk_height: int) -> None:
        """
        Deterministically moves R[op] -> A[v] and V_unassigned -> V_assigned (R8-C02),
        keeping V_unassigned + V_assigned == C + L + E + R + A + B invariant across T_take!
        """
        for oid in sorted(operators.keys()):
            op = operators[oid]
            if op["rounds_left"] <= 0:
                continue
            # Assign oldest eligible vault while credit covers it
            while True:
                eligible_vids = [
                    vid for vid in sorted(unassigned_vaults.keys())
                    if ((unassigned_vaults[vid]["mask"] >> oid) & 1)
                    and op["credit"] >= unassigned_vaults[vid]["sats"]
                    and op["rounds_left"] > 0
                ]
                if not eligible_vids:
                    break
                vid = eligible_vids[0]
                vinfo = unassigned_vaults.pop(vid)
                vamt = vinfo["sats"]
                op["credit"] -= vamt
                assigned_vaults[vid] = {
                    "sats": vamt,
                    "mask": vinfo["mask"],
                    "op_id": oid,
                    "assigned_h": blk_height,
                }
                assigned_obligations[vid] = vamt
                counts["fifo_assign"] += 1

    def apply_finalized_event(ev: dict, blk_height: int) -> None:
        kind = ev["kind"]
        if kind == "deposit":
            # Enforce L1 AdmissionTicketUTXO mutual exclusion (R8-C03)
            needed = {50_000_000: 0, 25_000_000: 0}
            for _, vamt in ev["vaults"]:
                needed[vamt] += 1
            if ticket_pool[50_000_000] < needed[50_000_000] or ticket_pool[25_000_000] < needed[25_000_000]:
                # Loser deposit rejected at L1 consensus before U_dep_wallet is spent!
                counts["deposit_race_blocked_by_ticket"] += 1
                return
            for denom, qty in needed.items():
                ticket_pool[denom] -= qty
            for vid, vamt in ev["vaults"]:
                unassigned_vaults[vid] = {"sats": vamt, "mask": ev["mask"]}
            users[ev["user"]] += sum(vamt for _, vamt in ev["vaults"])
            counts["deposit"] += 1

        elif kind == "forced_exit":
            u = ev["user"]
            amt = ev["gross"]
            assert amt >= POLICY_MIN_EXIT_SATS
            if users[u] >= amt:
                users[u] -= amt
                pending_exits[ev["exit_id"]] = {"user": u, "gross": amt, "created_h": blk_height}
                counts["forced_exit"] += 1

        elif kind == "front_paid":
            eid = ev["exit_id"]
            if eid in pending_exits:
                ex = pending_exits.pop(eid)
                operators[ev["op_id"]]["credit"] += ex["gross"]
                counts["front_paid"] += 1
                run_deterministic_fifo_assign(blk_height)

        elif kind == "front_grief":
            eid = ev["exit_id"]
            op = operators[ev["op_id"]]
            if eid in pending_exits:
                ex = pending_exits.pop(eid)
                users[ex["user"]] += ex["gross"]
                # Hard-partitioned B_grief penalty: NEVER touches B_custody (R8-H01 / R8-N05)!
                pen = min(POLICY_EXIT_GRIEF_SLASH_SATS, op["b_grief"])
                op["b_grief"] -= pen
                users[ex["user"]] += pen
                op["suspended"] = True
                assert op["b_custody"] == POLICY_B_CUSTODY_TOTAL_SATS or op["suspended"]
                counts["front_grief"] += 1

        elif kind == "front_grief_burst":
            # Concurrent k-exit grief burst in ONE Bitcoin block (R8-H01 / R8-N05 proof!)
            op = operators[ev["op_id"]]
            b_custody_before = op["b_custody"]
            live_eids = [eid for eid in ev["exit_ids"] if eid in pending_exits]
            if live_eids:
                per_victim = min(POLICY_EXIT_GRIEF_SLASH_SATS, op["b_grief"] // len(live_eids))
                for eid in live_eids:
                    ex = pending_exits.pop(eid)
                    users[ex["user"]] += ex["gross"] + per_victim
                    op["b_grief"] -= per_victim
                op["suspended"] = True
                assert op["b_custody"] == b_custody_before, "B_custody touched by ExitSlotUTXO grief burst!"
                assert op["b_grief"] >= 0
                counts["front_grief_burst_k20"] += 1

        elif kind == "exit_cancel":
            eid = ev["exit_id"]
            if eid in pending_exits and blk_height >= pending_exits[eid]["created_h"] + POLICY_T_EXIT_CANCEL:
                ex = pending_exits.pop(eid)
                users[ex["user"]] += ex["gross"]
                counts["exit_cancel"] += 1

        elif kind == "take_confirmed":
            # Separate from fifo_assign! Confirms after T_take gap, retiring V_assigned & A AND recycling ticket!
            vid = ev["vault_id"]
            if vid in assigned_vaults and assigned_vaults[vid]["op_id"] == ev["op_id"]:
                vinfo = assigned_vaults.pop(vid)
                vamt = assigned_obligations.pop(vid)
                assert vamt == vinfo["sats"]
                ticket_pool[vamt] += 1  # Recycle denomination-matched AdmissionTicketUTXO!
                operators[ev["op_id"]]["rounds_left"] = max(0, operators[ev["op_id"]]["rounds_left"] - 1)
                counts["take_confirmed"] += 1

        elif kind == "release_assignment":
            # 0x07 RELEASE_ASSIGNMENT: V_assigned -> V_unassigned, A[v] -> R[op]
            vid = ev["vault_id"]
            if vid in assigned_vaults and assigned_vaults[vid]["op_id"] == ev["op_id"]:
                vinfo = assigned_vaults.pop(vid)
                vamt = assigned_obligations.pop(vid)
                unassigned_vaults[vid] = {"sats": vamt, "mask": vinfo["mask"]}
                operators[ev["op_id"]]["credit"] += vamt
                counts["release_assignment"] += 1

        elif kind == "transfer_credit":
            src, dst, amt = ev["from_op"], ev["to_op"], ev["amount"]
            if operators[src]["credit"] >= amt:
                operators[src]["credit"] -= amt
                operators[dst]["credit"] += amt
                counts["transfer_credit"] += 1
                run_deterministic_fifo_assign(blk_height)

        elif kind == "disprove_dual_slash":
            # Dual-input Disprove spends Stake_r + VaultConnector_r -> 0 BTC leaves vault!
            # Native L1 verifier bounties paid from Stake_r; L2 B_custody slashed to insurance_pool.
            op = operators[ev["op_id"]]
            if op["b_custody"] >= POLICY_B_CUSTODY_TOTAL_SATS:
                # If any vault was assigned to this op's challenged round, return V_assigned -> V_unassigned & A -> R
                for vid in [v for v, info in assigned_vaults.items() if info["op_id"] == ev["op_id"]][:1]:
                    vinfo = assigned_vaults.pop(vid)
                    vamt = assigned_obligations.pop(vid)
                    unassigned_vaults[vid] = {"sats": vamt, "mask": vinfo["mask"]}
                    op["credit"] += vamt
                op["b_custody"] -= POLICY_B_CUSTODY_TOTAL_SATS
                users["insurance_pool"] += POLICY_B_CUSTODY_TOTAL_SATS
                op["suspended"] = True
                counts["disprove_dual_slash"] += 1

        elif kind == "lamport_equivocation_slash":
            # Rogue operator stole vault v (either unassigned OR assigned to innocent O_k!)
            vid = ev["vault_id"]
            op = operators[ev["op_id"]]
            if vid in unassigned_vaults:
                vamt = unassigned_vaults[vid]["sats"]
                if op["b_custody"] >= vamt + POLICY_B_ZBTC_EQUIV_BOUNTY_SATS:
                    unassigned_vaults.pop(vid)
                    ticket_pool[vamt] += 1
                    op["b_custody"] -= (vamt + POLICY_B_ZBTC_EQUIV_BOUNTY_SATS)
                    users["challenger_bounty_pool"] += POLICY_B_ZBTC_EQUIV_BOUNTY_SATS
                    op["suspended"] = True
                    counts["lamport_equivocation_slash"] += 1
            elif vid in assigned_vaults:
                vinfo = assigned_vaults[vid]
                vamt = vinfo["sats"]
                if op["b_custody"] >= vamt + POLICY_B_ZBTC_EQUIV_BOUNTY_SATS:
                    assigned_vaults.pop(vid)
                    assigned_obligations.pop(vid)
                    ticket_pool[vamt] += 1
                    # Restore innocent assignee O_k 100% whole via R[O_k] += vamt!
                    operators[vinfo["op_id"]]["credit"] += vamt
                    op["b_custody"] -= (vamt + POLICY_B_ZBTC_EQUIV_BOUNTY_SATS)
                    users["challenger_bounty_pool"] += POLICY_B_ZBTC_EQUIV_BOUNTY_SATS
                    op["suspended"] = True
                    counts["lamport_equivocation_slash"] += 1

    def assert_solvency(label: str) -> None:
        v_unassigned = sum(v["sats"] for v in unassigned_vaults.values())
        v_assigned = sum(v["sats"] for v in assigned_vaults.values())
        lhs = v_unassigned + v_assigned

        c_total = sum(users.values()) + sum(op["free_zbtc"] for op in operators.values())
        l_total = sum(rollup_locks.values())
        e_total = sum(ex["gross"] for ex in pending_exits.values())
        r_total = sum(op["credit"] for op in operators.values())
        a_total = sum(assigned_obligations.values())
        b_total = sum(op["b_custody"] + op["b_grief"] for op in operators.values())
        rhs = c_total + l_total + e_total + r_total + a_total + b_total

        assert lhs == rhs, f"[{label}] Conservation mismatch! V={lhs} != C+L+E+R+A+B={rhs}"
        assert v_assigned == a_total, f"[{label}] V_assigned={v_assigned} != A={a_total}"
        # Ticket + live vault conservation: total minted tickets == 20*0.50 + 40*0.25 = 20.0 BTC ALWAYS!
        ticket_value = ticket_pool[50_000_000] * 50_000_000 + ticket_pool[25_000_000] * 25_000_000
        assert lhs + ticket_value == 20 * SAT, f"[{label}] Ticket conservation broken: {lhs} + {ticket_value}"
        for oid, op in operators.items():
            assert op["b_custody"] >= 0 and op["b_grief"] >= 0
            if not op["suspended"]:
                assert op["b_custody"] == POLICY_B_CUSTODY_TOTAL_SATS
                assert op["b_grief"] == POLICY_B_GRIEF_TOTAL_SATS

    def mine_one_block(events: list[dict]) -> None:
        nonlocal finalized_height
        next_h = finalized_height + len(tip_blocks) + 1
        tip_blocks.append({"height": next_h, "events": events})
        counts["mine_block"] += 1
        while len(tip_blocks) >= K:
            fin_blk = tip_blocks.pop(0)
            finalized_height = fin_blk["height"]
            for ev in fin_blk["events"]:
                apply_finalized_event(ev, finalized_height)
            rebuild_unconf_locks()

    def current_tip_height() -> int:
        return finalized_height + len(tip_blocks)

    assert_solvency("init")

    # ------------------------------------------------------------------
    # 1. DETERMINISTIC BOB & MIKE TRACES WITH EXPLICIT T_take GAP (A > 0!)
    # ------------------------------------------------------------------
    bob_vaults = [(next_vault_id + i, amt) for i, amt in enumerate(POLICY_VAULT_TIERS_SATS)]
    next_vault_id += 3
    alice_vaults = [(next_vault_id + i, amt) for i, amt in enumerate(POLICY_VAULT_TIERS_SATS)]
    next_vault_id += 3
    mine_one_block([
        {"kind": "deposit", "user": "bob", "vaults": bob_vaults, "mask": all_ops_mask},
        {"kind": "deposit", "user": "alice", "vaults": alice_vaults, "mask": all_ops_mask},
    ])
    for _ in range(K - 1):
        mine_one_block([])
    assert users["bob"] == SAT and users["alice"] == SAT
    assert_solvency("after_bob_alice_deposits")

    # Bob spends 0.50 zBTC to Carol, exits 0.50 BTC -> FIFO assigns (A = 0.50 BTC!) -> TakeTx confirms later!
    users["bob"] -= 50_000_000
    users["carol"] += 50_000_000
    counts["transfer"] += 1
    bob_eid = next_exit_id
    next_exit_id += 1
    mine_one_block([{"kind": "forced_exit", "user": "bob", "gross": 50_000_000, "exit_id": bob_eid}])
    for _ in range(K - 1):
        mine_one_block([])
    mine_one_block([{"kind": "front_paid", "exit_id": bob_eid, "op_id": 0}])
    for _ in range(K - 1):
        mine_one_block([])
    # Verify R8-C02: during the T_take gap, A == 0.50 BTC > 0 AND V == C+L+E+R+A+B holds!
    assert sum(assigned_obligations.values()) == 50_000_000
    assert_solvency("bob_mid_T_take_gap_A_nonzero")
    assigned_bob_vid = next(iter(assigned_vaults.keys()))
    mine_one_block([{"kind": "take_confirmed", "op_id": 0, "vault_id": assigned_bob_vid}])
    for _ in range(K - 1):
        mine_one_block([])
    assert sum(assigned_obligations.values()) == 0
    assert_solvency("after_bob_0.5_take_confirmed")

    # Mike scenario (Alice 1 + Bob2 1 -> Mike 2 -> Mike exits 0.25 BTC)
    bob2_vaults = [(next_vault_id + i, amt) for i, amt in enumerate(POLICY_VAULT_TIERS_SATS)]
    next_vault_id += 3
    mine_one_block([{"kind": "deposit", "user": "bob", "vaults": bob2_vaults, "mask": all_ops_mask}])
    for _ in range(K - 1):
        mine_one_block([])
    users["alice"] -= SAT
    users["bob"] -= SAT
    users["mike"] += 2 * SAT
    counts["transfer"] += 2
    mike_eid = next_exit_id
    next_exit_id += 1
    mine_one_block([{"kind": "forced_exit", "user": "mike", "gross": 25_000_000, "exit_id": mike_eid}])
    for _ in range(K - 1):
        mine_one_block([])
    mine_one_block([{"kind": "front_paid", "exit_id": mike_eid, "op_id": 1}])
    for _ in range(K - 1):
        mine_one_block([])
    assert sum(assigned_obligations.values()) == 25_000_000
    assert_solvency("mike_mid_T_take_gap_A_nonzero")
    assigned_mike_vid = next(iter(assigned_vaults.keys()))
    mine_one_block([{"kind": "take_confirmed", "op_id": 1, "vault_id": assigned_mike_vid}])
    for _ in range(K - 1):
        mine_one_block([])
    assert users["mike"] == 175_000_000 and sum(assigned_obligations.values()) == 0
    assert_solvency("after_mike_0.25_take_confirmed")

    # ------------------------------------------------------------------
    # 2. DETERMINISTIC R8-H01 / R8-N05 k=20 CONCURRENT GRIEF BURST TEST
    # ------------------------------------------------------------------
    burst_eids = []
    for _ in range(20):
        eid = next_exit_id
        next_exit_id += 1
        burst_eids.append(eid)
        mine_one_block([{"kind": "forced_exit", "user": "mike", "gross": 5_000_000, "exit_id": eid}])
    for _ in range(K):
        mine_one_block([])
    b_cust_before = operators[2]["b_custody"]
    mine_one_block([{"kind": "front_grief_burst", "op_id": 2, "exit_ids": burst_eids}])
    for _ in range(K):
        mine_one_block([])
    assert operators[2]["b_custody"] == b_cust_before == POLICY_B_CUSTODY_TOTAL_SATS
    assert operators[2]["b_grief"] == 0 and operators[2]["suspended"]
    assert_solvency("after_k20_grief_burst")

    # ------------------------------------------------------------------
    # 3. DETERMINISTIC R8-M04 TRANSFER_CREDIT RESIDUAL CONSOLIDATION TEST
    # ------------------------------------------------------------------
    # Give ops 3 & 4 each 0.15 BTC (< 0.25 BTC min vault), then consolidate via TransferCredit -> triggers FIFO assign!
    e_res1, e_res2 = next_exit_id, next_exit_id + 1
    next_exit_id += 2
    mine_one_block([
        {"kind": "forced_exit", "user": "mike", "gross": 15_000_000, "exit_id": e_res1},
        {"kind": "forced_exit", "user": "mike", "gross": 15_000_000, "exit_id": e_res2},
    ])
    for _ in range(K):
        mine_one_block([])
    mine_one_block([
        {"kind": "front_paid", "exit_id": e_res1, "op_id": 3},
        {"kind": "front_paid", "exit_id": e_res2, "op_id": 4},
    ])
    for _ in range(K):
        mine_one_block([])
    assert operators[3]["credit"] == 15_000_000 and operators[4]["credit"] == 15_000_000
    mine_one_block([{"kind": "transfer_credit", "from_op": 3, "to_op": 4, "amount": 15_000_000}])
    for _ in range(K):
        mine_one_block([])
    assert operators[3]["credit"] == 0 and operators[4]["credit"] == 5_000_000  # 0.30 -> assigned 0.25 vault, 0.05 left!
    assert_solvency("after_transfer_credit")

    # ------------------------------------------------------------------
    # 4. 2,000-STEP ADVERSARIAL RANDOMIZED SIMULATION (WITH REAL REORGS!)
    # ------------------------------------------------------------------
    actions = [
        "deposit", "transfer", "forced_exit", "front_paid", "front_grief",
        "exit_cancel", "take_confirmed", "release_assignment", "transfer_credit",
        "disprove_dual_slash", "lamport_equivocation_slash", "topup_op", "mine_block", "reorg",
    ]
    weights = [12, 16, 12, 12, 5, 6, 12, 5, 5, 4, 4, 10, 24, 10]
    normal_users = ["alice", "bob", "mike", "carol", "dave"]

    for step in range(steps):
        act = rng.choices(actions, weights=weights, k=1)[0]

        if act == "deposit":
            # Deliberately allow attempting deposits even near cap to exercise ticket mutual-exclusion rejection!
            u = rng.choice(normal_users)
            new_vs = [(next_vault_id + i, amt) for i, amt in enumerate(POLICY_VAULT_TIERS_SATS)]
            next_vault_id += 3
            mine_one_block([{"kind": "deposit", "user": u, "vaults": new_vs, "mask": all_ops_mask}])

        elif act == "transfer":
            rich = [u for u in normal_users if users[u] >= POLICY_MIN_EXIT_SATS]
            if rich:
                src = rng.choice(rich)
                dst = rng.choice([u for u in normal_users if u != src])
                amt = rng.randint(POLICY_MIN_EXIT_SATS, min(users[src], 50_000_000))
                users[src] -= amt
                users[dst] += amt
                counts["transfer"] += 1

        elif act == "forced_exit":
            rich = [u for u in normal_users if users[u] >= 10_000_000]
            if rich:
                u = rng.choice(rich)
                choices = [10_000_000, 25_000_000, 50_000_000]
                valid = [c for c in choices if users[u] >= c]
                amt = rng.choice(valid)
                eid = next_exit_id
                next_exit_id += 1
                mine_one_block([{"kind": "forced_exit", "user": u, "gross": amt, "exit_id": eid}])

        elif act == "front_paid":
            open_exits = [eid for eid in pending_exits if eid not in unconf_spent_exits]
            active_ops = [oid for oid, op in operators.items() if not op["suspended"]]
            if open_exits and active_ops:
                eid = rng.choice(open_exits)
                oid = rng.choice(active_ops)
                unconf_spent_exits.add(eid)
                mine_one_block([{"kind": "front_paid", "exit_id": eid, "op_id": oid}])

        elif act == "front_grief":
            open_exits = [eid for eid in pending_exits if eid not in unconf_spent_exits]
            active_ops = [oid for oid, op in operators.items() if not op["suspended"] and op["b_grief"] > 0]
            if open_exits and active_ops:
                eid = rng.choice(open_exits)
                oid = rng.choice(active_ops)
                unconf_spent_exits.add(eid)
                mine_one_block([{"kind": "front_grief", "exit_id": eid, "op_id": oid}])

        elif act == "exit_cancel":
            cur_h = current_tip_height()
            expired = [
                eid for eid, ex in pending_exits.items()
                if eid not in unconf_spent_exits and cur_h >= ex["created_h"] + POLICY_T_EXIT_CANCEL
            ]
            if expired:
                eid = rng.choice(expired)
                unconf_spent_exits.add(eid)
                mine_one_block([{"kind": "exit_cancel", "exit_id": eid}])

        elif act == "take_confirmed":
            ready = [
                (vid, info["op_id"]) for vid, info in assigned_vaults.items()
                if vid not in unconf_taken_vaults and vid not in unconf_released_vaults
            ]
            if ready:
                vid, oid = rng.choice(ready)
                unconf_taken_vaults.add(vid)
                mine_one_block([{"kind": "take_confirmed", "op_id": oid, "vault_id": vid}])

        elif act == "release_assignment":
            ready = [
                (vid, info["op_id"]) for vid, info in assigned_vaults.items()
                if vid not in unconf_taken_vaults and vid not in unconf_released_vaults
            ]
            if ready:
                vid, oid = rng.choice(ready)
                unconf_released_vaults.add(vid)
                mine_one_block([{"kind": "release_assignment", "op_id": oid, "vault_id": vid}])

        elif act == "transfer_credit":
            donors = [oid for oid, op in operators.items() if 0 < op["credit"] < 25_000_000]
            if donors:
                src = rng.choice(donors)
                dst = rng.choice([i for i in operators if i != src])
                mine_one_block([{"kind": "transfer_credit", "from_op": src, "to_op": dst, "amount": operators[src]["credit"]}])

        elif act == "disprove_dual_slash":
            active_ops = [oid for oid, op in operators.items() if not op["suspended"]]
            if active_ops:
                oid = rng.choice(active_ops)
                mine_one_block([{"kind": "disprove_dual_slash", "op_id": oid}])

        elif act == "lamport_equivocation_slash":
            all_vids = [
                vid for vid in list(unassigned_vaults.keys()) + list(assigned_vaults.keys())
                if vid not in unconf_taken_vaults
            ]
            active_ops = [
                oid for oid, op in operators.items()
                if not op["suspended"] and op["b_custody"] >= POLICY_B_CUSTODY_TOTAL_SATS
            ]
            if all_vids and active_ops:
                oid = rng.choice(active_ops)
                vid = rng.choice(all_vids)
                unconf_taken_vaults.add(vid)
                mine_one_block([{"kind": "lamport_equivocation_slash", "op_id": oid, "vault_id": vid}])

        elif act == "topup_op":
            susp = [oid for oid, op in operators.items() if op["suspended"]]
            if susp:
                oid = rng.choice(susp)
                op = operators[oid]
                need_c = max(0, POLICY_B_CUSTODY_TOTAL_SATS - op["b_custody"])
                need_g = max(0, POLICY_B_GRIEF_TOTAL_SATS - op["b_grief"])
                needed = need_c + need_g
                if op["free_zbtc"] >= needed:
                    op["free_zbtc"] -= needed
                    op["b_custody"] += need_c
                    op["b_grief"] += need_g
                    op["suspended"] = False
                    counts["topup_op"] += 1
                elif ticket_pool[50_000_000] >= 2:
                    ticket_pool[50_000_000] -= 2
                    for _ in range(2):
                        unassigned_vaults[next_vault_id] = {"sats": 50_000_000, "mask": all_ops_mask}
                        next_vault_id += 1
                    op["free_zbtc"] += SAT - needed
                    op["b_custody"] += need_c
                    op["b_grief"] += need_g
                    op["suspended"] = False
                    counts["topup_op"] += 1

        elif act == "mine_block":
            mine_one_block([])

        elif act == "reorg":
            if tip_blocks:
                depth = rng.randint(1, min(K - 1, len(tip_blocks)))
                orphaned = tip_blocks[-depth:]
                del tip_blocks[-depth:]
                ev_reverted = sum(len(b["events"]) for b in orphaned)
                counts["reorg"] += 1
                counts["reorg_blocks_reverted"] += depth
                counts["reorg_events_reverted"] += ev_reverted
                rebuild_unconf_locks()
                for _ in range(depth):
                    mine_one_block([])

        assert_solvency(f"step_{step}_{act}")

    # Guarantee EXIT_CANCEL path is exercised if random steps didn't hit a 288-block idle exit
    if counts["exit_cancel"] == 0:
        u = next((u for u in normal_users if users[u] >= 25_000_000), "insurance_pool")
        eid = next_exit_id
        next_exit_id += 1
        mine_one_block([{"kind": "forced_exit", "user": u, "gross": 25_000_000, "exit_id": eid}])
        for _ in range(K + POLICY_T_EXIT_CANCEL):
            mine_one_block([])
        mine_one_block([{"kind": "exit_cancel", "exit_id": eid}])
        for _ in range(K):
            mine_one_block([])
        assert_solvency("post_exit_cancel")

    # Guarantee ticket-cap deposit-race rejection was exercised
    if counts["deposit_race_blocked_by_ticket"] == 0:
        # Attempt a massive burst of deposits past the remaining ticket cap
        for _ in range(25):
            new_vs = [(next_vault_id + i, amt) for i, amt in enumerate(POLICY_VAULT_TIERS_SATS)]
            next_vault_id += 3
            mine_one_block([{"kind": "deposit", "user": "alice", "vaults": new_vs, "mask": all_ops_mask}])
        for _ in range(K):
            mine_one_block([])
        assert_solvency("post_ticket_race")

    # Flush remaining tip blocks to K-deep finality
    for _ in range(K):
        mine_one_block([])
    assert_solvency("final")
    return counts


# ==============================================================================
# MAIN ASSERTION SUITE
# ==============================================================================
def main() -> None:
    print("================================================================================")
    print("zBTC v2 (v3.1.0-rfc — R8 HARDENED) ZERO-FEDERATION CONSISTENCY & BOUNDS CHECKER")
    print("Note: Pure Python 3 stdlib. Checks internal consistency against SOURCED_,")
    print("      POLICY_, and PRE_MAINNET_TARGET_ inputs. Not an empirical Signet benchmark.")
    print("================================================================================")

    # --------------------------------------------------------------------------
    # 1. STAGE 0: COINBASE MIDSTATE 1-/2-BLOCK PADDING & >= 65 B FILTER (R8-M06)
    # --------------------------------------------------------------------------
    print("\n=== 1. STAGE 0: COINBASE MIDSTATE 1-/2-BLOCK SHA-256 PADDING & >= 65 B FILTER ===")
    one_blk_count, two_blk_count = 0, 0
    for rem in range(64):
        total_len = 128 + rem
        cb_bytes = bytes((i * 37 + rem) & 0xFF for i in range(total_len))
        st = sha256_compress(sha256_compress(_SHA256_IV, cb_bytes[0:64]), cb_bytes[64:128])
        midstate = struct.pack(">8I", *st)
        got_txid, final_blks = complete_midstate_double_sha256(midstate, cb_bytes[128:], total_len)
        assert got_txid == hashlib.sha256(hashlib.sha256(cb_bytes).digest()).digest()
        if rem < 56:
            assert final_blks == 1
            one_blk_count += 1
        else:
            assert final_blks == 2
            two_blk_count += 1
    assert one_blk_count == 56 and two_blk_count == 8
    for bad_len in (0, 32, 63, 64):
        try:
            complete_midstate_double_sha256(b"\x00" * 32, b"\x00" * (bad_len % 64), bad_len)
            raise AssertionError(f"Length {bad_len} must be rejected!")
        except AssertionError as e:
            assert "CVE-2017-12842" in str(e)
    print(
        f"  Verified 64/64 remainders vs hashlib double-SHA256 ({one_blk_count} 1-blk, {two_blk_count} 2-blk = 12.5%); "
        f"all len <= 64 rejected (min strippedTx = {POLICY_STAGE0_MIN_STRIPPED_TX_BYTES} B)."
    )

    # --------------------------------------------------------------------------
    # 2. STAGE 0: go-zenon THROUGHPUT, SPV ORACLE & BITCOIN L1 0x02 DA CEILING (R8-M08)
    # --------------------------------------------------------------------------
    print("\n=== 2. STAGE 0: go-zenon PLASMA / 8 MiB CEILING vs BITCOIN L1 0x02 DA CAP ===")
    rollup_tx_plasma = SOURCED_ZNN_ACCOUNT_BLOCK_BASE_PLASMA + PRE_MAINNET_TARGET_ROLLUP_TX_DATA_BYTES * SOURCED_ZNN_AB_BYTE_DATA_PLASMA
    assert rollup_tx_plasma == 28_480
    assert ceil_div(rollup_tx_plasma, SOURCED_ZNN_PLASMA_PER_QSR) == 14

    tps_floor_2blk = (POLICY_PINNED_MAX_BASE_PLASMA_FLOOR / SOURCED_ZNN_ACCOUNT_BLOCK_BASE_PLASMA / 2.0) / SOURCED_ZNN_OBSERVED_MOMENTUM_SECS
    tps_default_2blk = (SOURCED_ZNN_DP_DEFAULT_MAX_BASE_PLASMA / SOURCED_ZNN_ACCOUNT_BLOCK_BASE_PLASMA / 2.0) / SOURCED_ZNN_OBSERVED_MOMENTUM_SECS
    rollup_tps_floor_114 = (POLICY_PINNED_MAX_BASE_PLASMA_FLOOR / rollup_tx_plasma) / SOURCED_ZNN_OBSERVED_MOMENTUM_SECS
    rollup_tps_default_114 = (SOURCED_ZNN_DP_DEFAULT_MAX_BASE_PLASMA / rollup_tx_plasma) / SOURCED_ZNN_OBSERVED_MOMENTUM_SECS
    rollup_tps_floor_10s = (POLICY_PINNED_MAX_BASE_PLASMA_FLOOR / rollup_tx_plasma) / 10.0
    real_tps_low = ((SOURCED_ZNN_MAX_DETAILED_MOMENTUM_WIRE // SOURCED_ZNN_MIN_ACCOUNT_BLOCK_WIRE_HIGH) / 2.0) / SOURCED_ZNN_OBSERVED_MOMENTUM_SECS
    real_tps_high = ((SOURCED_ZNN_MAX_DETAILED_MOMENTUM_WIRE // SOURCED_ZNN_MIN_ACCOUNT_BLOCK_WIRE_LOW) / 2.0) / SOURCED_ZNN_OBSERVED_MOMENTUM_SECS
    assert 4.3 < tps_floor_2blk < 4.5 and 8.7 < tps_default_2blk < 8.9
    assert 6.3 < rollup_tps_floor_114 < 6.6 and 12.8 < rollup_tps_default_114 < 13.1
    assert 7.36 < rollup_tps_floor_10s < 7.38
    assert 1_000 < real_tps_low < 1_100 and 1_200 < real_tps_high < 1_260

    # Bitcoin L1 physical 0x02 mutated-leaf DA ceilings (R8-M08)
    btc_max_vb_per_sec = (SOURCED_BTC_MAX_BLOCK_WEIGHT / 4.0) / SOURCED_BTC_TARGET_BLOCK_SECS  # 1,666.67 vB/s
    da_blended_10vb_100pct = btc_max_vb_per_sec / 10.0   # 166.67 leaves/s @ 100% Bitcoin blockspace
    da_existing_4vb_100pct = btc_max_vb_per_sec / 4.0    # 416.67 existing 16B leaves/s @ 100%
    da_new_12vb_100pct = btc_max_vb_per_sec / 12.0       # 138.89 new 48B leaves/s @ 100%
    da_epoch_new_leaf_cap_per_sec = POLICY_MAX_NEW_LEAVES_PER_EPOCH / (6.0 * SOURCED_BTC_TARGET_BLOCK_SECS)
    assert abs(da_blended_10vb_100pct - 166.6666667) < 1e-4
    assert abs(da_existing_4vb_100pct - 416.6666667) < 1e-4
    assert da_epoch_new_leaf_cap_per_sec < 0.30

    # Stage 0 SPV Oracle ABI + Dynamic Plasma 5-param pinning
    prove_payload = 8 + 4 + 4 + 32 + POLICY_STAGE0_MAX_STRIPPED_TX_BYTES + 16 * 32 + 63 + 16 * 32
    prove_abi = (4 + 8 * 32) + (32 + POLICY_STAGE0_MAX_STRIPPED_TX_BYTES) + (32 + 16 * 32) + (32 + 64) + (32 + 16 * 32)
    assert prove_payload == 7_279 and prove_abi == 7_620
    prove_plasma = abi_embedded_plasma(SOURCED_ZNN_EMBEDDED_HEAVY_SPV_TIER, prove_abi)
    assert prove_plasma == 591_388 and POLICY_PINNED_MAX_BASE_PLASMA_FLOOR >= 3 * prove_plasma
    assert POLICY_PINNED_MAX_BASE_PLASMA_FLOOR // SOURCED_ZNN_EMBEDDED_SIMPLE_TIER == 40

    price_unpinned, price_pinned = SOURCED_ZNN_MIN_RESOURCE_PRICE, SOURCED_ZNN_MIN_RESOURCE_PRICE
    pinned_target = (POLICY_PINNED_MAX_BASE_PLASMA_FLOOR * POLICY_PINNED_MIN_TARGET_SHARE_PCT) // 100
    assert pinned_target == 525_000
    for _ in range(52):
        price_unpinned = dp_next_price(price_unpinned, 21_000, 1, POLICY_PINNED_MAX_PRICE_CHANGE_PCT, 1)
        price_pinned = dp_next_price(price_pinned, 21_000, pinned_target, POLICY_PINNED_MAX_PRICE_CHANGE_PCT, POLICY_PINNED_MIN_PRICE_DENOM)
    assert price_unpinned / 1_000 > 100_000 and price_pinned == 1_000
    print(
        f"  Zenon @ 11.4s: 2-blk={tps_floor_2blk:.1f}/{tps_default_2blk:.1f} tx/s | "
        f"1-blk rollup={rollup_tps_floor_114:.1f}/{rollup_tps_default_114:.1f} tx/s ({rollup_tps_floor_10s:.2f} @ 10s) | "
        f"8 MiB cap={real_tps_low:,.0f}-{real_tps_high:,.0f} tx/s"
    )
    print(
        f"  Bitcoin L1 0x02 DA cap @ 100% blockspace: blended(10vB)={da_blended_10vb_100pct:.1f} leaves/s "
        f"(1%={da_blended_10vb_100pct/100:.2f}/s) | existing(4vB)={da_existing_4vb_100pct:.1f}/s | "
        f"new(12vB)={da_new_12vb_100pct:.1f}/s | spam cap={POLICY_MAX_NEW_LEAVES_PER_EPOCH}/6-blk ({da_epoch_new_leaf_cap_per_sec:.2f}/s, {POLICY_NEW_LEAF_DEPOSIT_SATS}-sat deposit)"
    )

    # --------------------------------------------------------------------------
    # 3. STAGE 0: EXACT ERLANG TAILS FOR PTLC (>= 48h) & LN HTLC (>= 24h) (R8-H07)
    # --------------------------------------------------------------------------
    print("\n=== 3. STAGE 0: EXACT STDLIB ERLANG TAILS FOR PTLC (>= 48h) & LN HTLC (>= 24h) ===")
    mean_1x = SOURCED_BTC_TARGET_BLOCK_SECS
    mean_2p3x = SOURCED_BTC_TARGET_BLOCK_SECS * SOURCED_JUNE2021_SLOW_DAILY_MULT  # 1,380 s/blk
    # Regression-verify R8-H07's exact failure probabilities on old v3.0.0 values:
    old_ptlc_fail = erlang_survival_prob(72, 30 * 3600, mean_2p3x)
    old_ln_fail = erlang_survival_prob(36, 6 * 3600, mean_1x)
    assert abs(old_ptlc_fail - 0.2234) < 0.002, f"Expected ~22.34%, got {old_ptlc_fail:.4%}"
    assert abs(old_ln_fail - 0.4778) < 0.002, f"Expected ~47.78%, got {old_ln_fail:.4%}"
    # Verify hardened v3.1.0-rfc margins:
    new_ptlc_fail = erlang_survival_prob(POLICY_PTLC_BTC_CSV_BLOCKS, POLICY_PTLC_ZNN_DURATION_SECS, mean_2p3x)
    ptlc_p999_h = erlang_quantile_hours(POLICY_PTLC_BTC_CSV_BLOCKS, 0.999, mean_2p3x)
    new_ln_fail_2p3x = erlang_survival_prob(POLICY_LN_DELTA_SAFETY_BLOCKS, POLICY_LN_OUTBOUND_DELTA_SAFETY_SECS, mean_2p3x)
    new_ln_fail_1x = erlang_survival_prob(POLICY_LN_DELTA_SAFETY_BLOCKS, POLICY_LN_OUTBOUND_DELTA_SAFETY_SECS, mean_1x)
    ln_p999_h = erlang_quantile_hours(POLICY_LN_DELTA_SAFETY_BLOCKS, 0.999, mean_2p3x)
    assert new_ptlc_fail < 1e-6 and ptlc_p999_h < 39.0
    assert new_ln_fail_2p3x < 2e-4 and new_ln_fail_1x < 1e-18 and ln_p999_h < 22.5
    print(
        f"  PTLC (72 blks @ 2.3x): old 30h fail={old_ptlc_fail:.2%} -> NEW 48h fail={new_ptlc_fail:.2e} "
        f"(p99.9={ptlc_p999_h:.2f}h, margin={48.0 - ptlc_p999_h:.2f}h; block-72 RBF watchtower)"
    )
    print(
        f"  LN Outbound (36 blks): old 6h@1x fail={old_ln_fail:.2%} -> NEW 24h@2.3x fail={new_ln_fail_2p3x:.2e} "
        f"(p99.9={ln_p999_h:.2f}h, @1x fail={new_ln_fail_1x:.2e})"
    )

    # --------------------------------------------------------------------------
    # 4. STAGE 1A: COMPLETE HARD-BTC CAPITAL ACCOUNTING (R8-M09, R8-H02)
    # --------------------------------------------------------------------------
    print("\n=== 4. STAGE 1A: COMPLETE HARD-BTC CAPITAL (LOCKED vs OPERATIONAL vs MULTI-DISPUTE) ===")
    bitvm2_m3_low = 3 * PRE_MAINNET_TARGET_BITVM2_LANE_BOND_BTC_LOW
    bitvm2_m5_high = 5 * PRE_MAINNET_TARGET_BITVM2_LANE_BOND_BTC_HIGH
    assert bitvm2_m3_low > SOURCED_ZNN_MCAP_BTC_HIGH
    verifier_standby_btc = (POLICY_BITVMX_N_VERIFIERS * POLICY_F_CHAL_SATS) / SAT
    verifier_cpfp_res_btc = POLICY_BITVMX_N_VERIFIERS * POLICY_OP_RESERVE_VERIFIER_CPFP_PER_V_BTC
    assert abs(verifier_standby_btc - 2.80) < 1e-9 and abs(verifier_cpfp_res_btc - 0.70) < 1e-9

    for label, prof in POLICY_STAGE1A_PROFILES.items():
        m = prof["M"]
        bonds_btc = (m * POLICY_BITVMX_L_LANES * POLICY_LANE_TOTAL_BOND_SATS) / SAT
        locked_btc = bonds_btc + prof["float_btc"] + verifier_standby_btc
        op_reserves = verifier_cpfp_res_btc + POLICY_OP_RESERVE_DA_BATCHER_BTC + m * POLICY_OP_RESERVE_TOPUP_PER_OP_BTC
        op_baseline = locked_btc + op_reserves
        per_verifier_m_disputes = m * ((POLICY_F_CHAL_SATS / SAT) + 0.08265)
        pct_low = 100.0 * op_baseline / SOURCED_ZNN_MCAP_BTC_HIGH
        pct_high = 100.0 * op_baseline / SOURCED_ZNN_MCAP_BTC_LOW
        if m == 3:
            assert abs(locked_btc - 12.80) < 1e-9 and abs(op_baseline - 14.75) < 1e-9
        if m == 5:
            assert abs(locked_btc - 18.80) < 1e-9 and abs(op_baseline - 21.25) < 1e-9
        print(
            f"  {label:28s}: locked={locked_btc:5.2f} + op_res={op_reserves:4.2f} = {op_baseline:5.2f} BTC "
            f"({pct_low:.1f}%-{pct_high:.1f}% ZNN mcap) | M-dispute/honest-V={per_verifier_m_disputes:.2f} BTC"
        )
    print(f"  BitVM2 bonds-only contrast (M=3..5): {bitvm2_m3_low:.2f}-{bitvm2_m5_high:.3f} BTC | Core floor >= {SOURCED_BTC_CORE_MIN_VERSION_P2A_ZERO}")

    # --------------------------------------------------------------------------
    # 5. STAGE 1A: BitVMX n=8 BISECTION, 10x153 vB CPFP & TRUC v3 (R8-H04/H05)
    # --------------------------------------------------------------------------
    print("\n=== 5. STAGE 1A: BitVMX-CPU n=8 WRAPPED-SNARK VERIFIER & P2A CPFP TRUC v3 ===")
    digits_per_prover_tx = (POLICY_BITVMX_N_BRANCH - 1) * (40 + 3)
    assert digits_per_prover_tx == 301
    prover_step_vb = math.ceil(digits_per_prover_tx * PRE_MAINNET_TARGET_WOTS_DIGIT_WU) / 4.0 + PRE_MAINNET_TARGET_BISECTION_OVERHEAD_VB
    assert abs(prover_step_vb - 7_436.5) < 1e-9
    assert prover_step_vb <= SOURCED_BIP431_TRUC_MAX_VB
    assert prover_step_vb > SOURCED_BIP431_TRUC_CHILD_MAX_VB  # Confirms zero unconfirmed TRUC child chaining!

    cpfp_side_vb = PRE_MAINNET_TARGET_CPFP_COUNT_PER_SIDE * SOURCED_P2A_CPFP_CHILD_VB
    assert cpfp_side_vb == 1_530 and SOURCED_P2A_CPFP_CHILD_VB <= SOURCED_BIP431_TRUC_CHILD_MAX_VB
    prover_total_with_cpfp_vb = PRE_MAINNET_TARGET_PROVER_BASE_CAP_VB + cpfp_side_vb    # 76,530 vB
    verifier_total_with_cpfp_vb = PRE_MAINNET_TARGET_VERIFIER_BASE_CAP_VB + cpfp_side_vb  # 16,530 vB
    assert prover_total_with_cpfp_vb == 76_530 and verifier_total_with_cpfp_vb == 16_530

    prover_fee_500 = prover_total_with_cpfp_vb * POLICY_DESIGN_SUSTAINED_FEE_SATVB
    prover_breakeven = POLICY_F_CHAL_SATS // prover_total_with_cpfp_vb
    verifier_fee_500 = verifier_total_with_cpfp_vb * POLICY_DESIGN_SUSTAINED_FEE_SATVB
    verifier_fee_750 = verifier_total_with_cpfp_vb * POLICY_STRESS_SUSTAINED_FEE_SATVB
    assert prover_fee_500 == 38_265_000 <= POLICY_F_CHAL_SATS and prover_breakeven == 522
    assert verifier_fee_500 == 8_265_000 and verifier_fee_750 == 12_397_500
    seq_steps = 1 + 2 * POLICY_BITVMX_SEARCH_ROUNDS + 1
    assert seq_steps == 20 and POLICY_BITVMX_N_BRANCH ** POLICY_BITVMX_SEARCH_ROUNDS == 134_217_728
    print(
        f"  Prover step={prover_step_vb:,.1f} vB <= 10k TRUC parent (>1k child -> confirmed parents only!) | "
        f"Prover w/ 10x153 CPFP={prover_total_with_cpfp_vb:,} vB ({prover_fee_500/SAT:.5f} BTC <= 0.40, BE={prover_breakeven} sat/vB)"
    )
    print(
        f"  Verifier w/ 10x153 CPFP={verifier_total_with_cpfp_vb:,} vB: @500={verifier_fee_500/SAT:.5f} BTC, @750={verifier_fee_750/SAT:.5f} BTC"
    )

    # --------------------------------------------------------------------------
    # 6. STAGE 1A: WIDENED TIMELOCKS & ACYCLIC vault_id LAMPORT TakeTx (R8-C01)
    # --------------------------------------------------------------------------
    print("\n=== 6. STAGE 1A: WIDENED TIMELOCKS (T_step=72) & ACYCLIC vault_id LAMPORT TakeTx ===")
    max_dispute_end = POLICY_T_CHAL_WINDOW + seq_steps * POLICY_T_STEP
    assert max_dispute_end == 1_584
    assert POLICY_T_TAKE == 1_728 and POLICY_T_TAKE - max_dispute_end == 144
    assert POLICY_T_COOLDOWN == 1_872 and POLICY_T_COOLDOWN - POLICY_T_TAKE == 144
    assert POLICY_T_RETIRE == 2_016 and POLICY_T_RETIRE - POLICY_T_COOLDOWN == 144

    # Acyclic vault_id determinism & uniqueness across distinct vouts of same confirmed U_dep_wallet:
    funding_txid = hashlib.sha256(b"confirmed_U_dep_wallet_txid").digest()
    vid_0 = compute_acyclic_vault_id(funding_txid, 0, 0, 50_000_000, 0b11111)
    vid_1 = compute_acyclic_vault_id(funding_txid, 0, 1, 25_000_000, 0b11111)
    vid_2 = compute_acyclic_vault_id(funding_txid, 0, 2, 25_000_000, 0b11111)
    assert len({vid_0, vid_1, vid_2}) == 3 and all(len(v) == 32 for v in (vid_0, vid_1, vid_2))

    # Exact Lamport TakeTx size INCLUDING recycled AdmissionTicketUTXO at vout[1]!
    lamport_script_bytes = 256 * 23 + 34  # 5,922 B
    lamport_preimages_bytes = 256 * 21    # 5,376 B
    cb_stage1a, cb_stage2 = 1 + 32 + 32 * 9, 1 + 32 + 32 * 12  # 321 / 417 B
    assert lamport_script_bytes == 5_922 and lamport_preimages_bytes == 5_376 and cb_stage1a == 321 and cb_stage2 == 417
    # Non-witness: 10 + 2*41 (U_d + VaultConnector) + 43 (P_Op) + 43 (recycled Ticket) + 13 (P2A) = 191 B
    take_non_wit = 10 + 2 * 41 + 43 + 43 + 13
    take_wit_s1 = compact_size_len(259) + 65 + lamport_preimages_bytes + compact_size_len(lamport_script_bytes) + lamport_script_bytes + compact_size_len(cb_stage1a) + cb_stage1a + 110
    take_wit_s2 = compact_size_len(259) + 65 + lamport_preimages_bytes + compact_size_len(lamport_script_bytes) + lamport_script_bytes + compact_size_len(cb_stage2) + cb_stage2 + 110
    take_vb_s1 = (take_non_wit * 4 + take_wit_s1) / 4.0
    take_vb_s2 = (take_non_wit * 4 + take_wit_s2) / 4.0
    assert take_vb_s1 <= 3_200 and take_vb_s2 <= 3_200 <= SOURCED_BIP431_TRUC_MAX_VB
    assert take_vb_s1 > SOURCED_BIP431_TRUC_CHILD_MAX_VB  # Confirmed VaultConnector_r only!
    print(
        f"  Timelocks: [0,{POLICY_T_CHAL_WINDOW}] -> max_dispute={max_dispute_end} < T_take={POLICY_T_TAKE} (12d) "
        f"< T_cool={POLICY_T_COOLDOWN} (13d) < Retire={POLICY_T_RETIRE} (14d)"
    )
    print(
        f"  Acyclic vault_id Lamport TakeTx (w/ recycled Ticket): depth9={take_vb_s1:,.2f} vB / depth12={take_vb_s2:,.2f} vB "
        f"(<=3,200 <=10,000 TRUC parent; peak_stack=258 < 1,000)"
    )

    # --------------------------------------------------------------------------
    # 7. STAGE 1A: NATIVE-L1 Stake_r VERIFIER EV MATRIX (R8-H02, R8-N05 CLOSED!)
    # --------------------------------------------------------------------------
    print("\n=== 7. STAGE 1A: NATIVE-L1 Stake_r VERIFIER EV MATRIX (0% zBTC CRISIS DISCOUNT) ===")
    assert POLICY_BITVMX_N_VERIFIERS * POLICY_VERIFIER_NATIVE_L1_PAYOUT_SATS + POLICY_MIN_L1_STAKE_BURN_SATS == POLICY_BOND_BTC_SATS
    assert POLICY_MIN_L1_STAKE_BURN_SATS == 95_000_000  # 0.95 BTC min burn!
    # Native L1 payout = 0.15 BTC -> 0% haircut even at 30% (or 100%) zBTC crisis discount!
    ev_500 = POLICY_VERIFIER_NATIVE_L1_PAYOUT_SATS - verifier_fee_500 - POLICY_VERIFIER_LOCKUP_COST_SATS
    ev_750 = POLICY_VERIFIER_NATIVE_L1_PAYOUT_SATS - verifier_fee_750 - POLICY_VERIFIER_LOCKUP_COST_SATS
    verifier_breakeven_satvb = (POLICY_VERIFIER_NATIVE_L1_PAYOUT_SATS - POLICY_VERIFIER_LOCKUP_COST_SATS) // verifier_total_with_cpfp_vb
    assert ev_500 == 6_450_000 > 0        # +0.06450 BTC @ 500 sat/vB!
    assert ev_750 == 2_317_500 > 0        # +0.023175 BTC @ 750 sat/vB!
    assert verifier_breakeven_satvb == 890
    for k_collude in range(POLICY_BITVMX_N_VERIFIERS):
        honest_n = POLICY_BITVMX_N_VERIFIERS - k_collude
        l1_recapture = k_collude * POLICY_VERIFIER_NATIVE_L1_PAYOUT_SATS
        l1_only_pnl = -POLICY_BOND_BTC_SATS + l1_recapture  # -2.00 to -1.10 BTC on L1 ALONE!
        total_pnl = l1_only_pnl - POLICY_B_CUSTODY_TOTAL_SATS
        assert l1_only_pnl <= -110_000_000 and total_pnl <= -165_000_000
        if k_collude == 0:
            assert l1_only_pnl == -200_000_000 and total_pnl == -255_000_000
        if k_collude == 6:
            assert l1_only_pnl == -110_000_000 and total_pnl == -165_000_000
        print(
            f"  k_collude={k_collude} (honest={honest_n}): L1_payout=0.1500 BTC (0% zBTC discount!) | "
            f"EV@500={ev_500/SAT:+.5f}, EV@750={ev_750/SAT:+.5f} (BE={verifier_breakeven_satvb} sat/vB) | "
            f"Cartel L1={l1_only_pnl/SAT:+.2f} / Tot={total_pnl/SAT:+.2f} BTC"
        )

    # --------------------------------------------------------------------------
    # 8. STAGE 1A: EXACT 2^M HALL'S MARRIAGE & CYCLIC PRIORITY (R8-C04, R8-M03)
    # --------------------------------------------------------------------------
    print("\n=== 8. STAGE 1A: 2^M HALL'S MARRIAGE CHECKER & CYCLIC EXIT PRIORITY ===")
    # Demonstrate R8-C04 stranding counterexample: global cap passes (30 <= 0.5 * 220 = 110),
    # yet 30 vaults with opBitmask={0,1} (0b00011) exceed O_0+O_1 remaining rounds (10+10=20)!
    counterex_vaults = [0b00011] * 30
    counterex_rounds = [10, 10, 64, 64, 64]
    assert len(counterex_vaults) <= 0.50 * sum(counterex_rounds)  # Global scalar check falsely passed!
    ok_bad, bad_mask, bad_dem, bad_sup = check_halls_marriage(counterex_vaults, counterex_rounds, headroom_factor=1.0)
    assert not ok_bad and bad_mask == 0b00011 and bad_dem == 30 and bad_sup == 20
    # Valid Stage 1A uniform full-committee cohort passes even at 0.50 headroom:
    ok_good, _, _, _ = check_halls_marriage([0b11111] * 45, [64] * 5, headroom_factor=0.50)
    assert ok_good

    # Verify R8-M03 cyclic permutation has 0% collisions across 1,000 random exitIds for M=3..20:
    for m_act in (3, 5, 10, 20):
        for i in range(200):
            perm = cyclic_exit_priority(f"exit_{m_act}_{i}".encode(), m_act)
            assert len(perm) == m_act and len(set(perm)) == m_act
    print(
        f"  Hall's 2^M counterexample CAUGHT (subset 0b{bad_mask:05b}: demand={bad_dem} > supply={bad_sup}, "
        f"despite global 30 <= 110); uniform 45-vault M=5 cohort PASSES at 0.50 headroom."
    )
    print("  Cyclic priority k_r = (H(exitId) + r) mod M_active: 0.0% collisions verified across 800 tests (M=3,5,10,20).")

    # --------------------------------------------------------------------------
    # 9. STAGE 1A: MULTI-TIER BANK-RUN DURATION (T_cooldown = 13.0d)
    # --------------------------------------------------------------------------
    print("\n=== 9. STAGE 1A: MULTI-TIER VAULTS & 100% BANK-RUN DURATION (T_cooldown = 13.0d) ===")
    cooldown_days = POLICY_T_COOLDOWN / SOURCED_BTC_BLOCKS_PER_DAY
    assert abs(cooldown_days - 13.0) < 1e-9
    avg_multi = (sum(POLICY_VAULT_TIERS_SATS) / len(POLICY_VAULT_TIERS_SATS)) / SAT
    avg_half = (sum(POLICY_VAULT_ALT_SPLIT_SATS) / len(POLICY_VAULT_ALT_SPLIT_SATS)) / SAT
    for label, prof in POLICY_STAGE1A_PROFILES.items():
        m, cap_u, flt = prof["M"], prof["cap_user_btc"], prof["float_btc"]
        v_per_d = m / cooldown_days
        btc_per_d_multi = v_per_d * avg_multi
        btc_per_d_half = v_per_d * avg_half
        cont_multi = (cap_u - flt) / btc_per_d_multi
        cont_half = (cap_u - flt) / btc_per_d_half
        rem_v = int(round(cap_u / avg_multi)) - int(flt // avg_multi)
        batch_multi = math.ceil(rem_v / m) * cooldown_days
        if m == 3:
            assert 101.0 <= cont_multi <= 102.0 and batch_multi == 104.0 and 67.0 <= cont_half <= 68.5
        if m == 5:
            assert 93.0 <= cont_multi <= 94.5 and batch_multi == 104.0 and 62.0 <= cont_half <= 63.0
        print(
            f"  {label:28s}: {v_per_d:.3f} v/d ({btc_per_d_multi:.3f} BTC/d) | "
            f"100% run=~{cont_multi:.1f}d (batch={batch_multi:.0f}d) [~{cont_half:.1f}d w/ {{0.50,0.50}}]"
        )

    # --------------------------------------------------------------------------
    # 10. K >= 18 UNPUBLISHED-FORK HEURISTIC & BUDISH SENSITIVITY (R8-H03)
    # --------------------------------------------------------------------------
    print("\n=== 10. K >= 18 UNPUBLISHED-FORK HEURISTIC (Cap_user + M*B_zbtc) & BUDISH SENSITIVITY ===")
    for cap_u, cap_tot in POLICY_TVL_TIERS_TOTAL_BTC.items():
        k_2024 = POLICY_CONFIGURED_K_BY_ERA["2024-2028"][cap_u]
        assert k_2024 >= POLICY_K_MIN_FLOOR
        row = []
        for era, sub in SOURCED_BTC_SUBSIDY_BY_ERA.items():
            k_min = max(POLICY_K_MIN_FLOOR, int(math.floor((2.0 * cap_tot) / sub)) + 1)
            assert 0.50 * k_min * sub > cap_tot
            if era in POLICY_CONFIGURED_K_BY_ERA:
                k_cfg = POLICY_CONFIGURED_K_BY_ERA[era][cap_u]
                assert k_cfg >= k_min and 0.50 * k_cfg * sub > cap_tot
            row.append(f"{era}:K>={k_min}")
        print(f"  User={cap_u:3d} / Total={cap_tot:6.2f} BTC (2024 K={k_2024:3d}): " + " | ".join(row))
    # Print Budish winning-fork direct net flow-cost sensitivity at K=18, 2024-2028 (56.25 BTC nominal subsidy):
    nom_k18 = 18 * SOURCED_BTC_SUBSIDY_BY_ERA["2024-2028"]
    budish_str = " | ".join(f"kappa={int(k*100)}%:{k*nom_k18:.2f} BTC" for k in (0.05, 0.15, 0.30, 0.50))
    print(f"  Budish winning-fork direct flow-cost @ K=18 (excl. BTC-price crash): {budish_str}")

    # --------------------------------------------------------------------------
    # 11. STAGE 1B (clArk) ALTERNATIVE GATE
    # --------------------------------------------------------------------------
    print("\n=== 11. STAGE 1B (clArk) ALTERNATIVE GATE: LIQUIDITY & log2(N) BRANCH EXIT WEIGHTS ===")
    clark_low, clark_high = PRE_MAINNET_TARGET_CLARK_ACTIVE_LIQ_BTC
    assert clark_high < 14.75
    for n_vtxo in PRE_MAINNET_TARGET_CLARK_VTXO_COUNTS:
        depth = int(math.log2(n_vtxo))
        total_vb = depth * 167.0 + 154.0
        assert total_vb < SOURCED_BIP431_TRUC_MAX_VB
        print(
            f"  N={n_vtxo:4d} (depth={depth:2d}): exit={total_vb:6.0f} vB | "
            f"@100={int(total_vb*100):,} sats | @500={int(total_vb*500):,} sats"
        )

    # --------------------------------------------------------------------------
    # 12. REAL 2,000-STEP STAGE 1A SIMULATION (V = C + L + E + R + A + B)
    # --------------------------------------------------------------------------
    print("\n=== 12. REAL 2,000-STEP STAGE 1A SIMULATION (EXPLICIT A, TICKETS, k=20 GRIEF, REORGS) ===")
    counts = run_stage1a_solvency_sim(seed=20261128, steps=2_000)
    for k, v in counts.items():
        assert v > 0, f"Event type {k} was never exercised: {counts}"
    assert counts["reorg_blocks_reverted"] >= counts["reorg"] > 0 and counts["reorg_events_reverted"] > 0
    print("  Bob, Mike, k=20 grief burst, TransferCredit, Ticket cap race & 2,000 adversarial steps PASSED V=C+L+E+R+A+B:")
    print("  " + ", ".join(f"{k}={v}" for k, v in counts.items()))
    print("\nALL v2 (v3.1.0-rfc R8-HARDENED ZERO-FEDERATION) CONSISTENCY, ERLANG, HALL, EV & SOLVENCY CHECKS PASSED.")


if __name__ == "__main__":
    main()
