v2 (v3.1.0-rfc) · public rfc · zero-federation · not mainnet-active
Deterministic Consistency & Bounds Checker
Checks internal mathematical consistency against explicitly labeled SOURCED_, POLICY_, and PRE_MAINNET_TARGET_ inputs — redlines directly against archived v1 (v3.0.0-rfc).
Showing word-highlighted redline changes from archived v1 (v3.0.0-rfc) to v2 (v3.1.0-rfc). For structured finding-by-finding rationale, see theChangelog.
| @@ -2,1215 +2,1355 @@ | |||
| 2 | 2 | """ | |
| 3 | 3 | Deterministic Consistency & Bounds Checker for the zBTC Protocol Specification | |
| 4 | - | v1 (v3.0.0-rfc — Zero-Federation Phased Architecture: | |
| 5 | - | Stage 0 Verify Bitcoin SPV Oracle + Non-Custodial PTLC/LN | |
| 6 | - | -> Stage 1A Right-Sized BitVMX (n=8, M=3..5, N=7) + Bitcoin-Anchored Sovereign ZK Rollup | |
| 7 | - | | Stage 1B clArk Alternative Gate | |
| 8 | - | -> Stage 2 Zero-TTP Scale & Upgrade). | |
| 9 | - | ||
| 10 | - | SCOPE & HONESTY DISCLOSURE: | |
| 11 | - | This script checks internal mathematical consistency, SHA-256 coinbase midstate | |
| 12 | - | final-block padding across all 64 remainders, go-zenon Dynamic Plasma & wire-size | |
| 13 | - | bounds, PTLC/HTLC slow-block margins, Theorem 2 capital ratios, BIP-431 TRUC v3 | |
| 14 | - | and BIP-342 Tapscript/Lamport weights, simultaneous-window BitVMX timelocks, | |
| 15 | - | colluding-verifier P&L matrices, multi-tier vault bank-run exit bounds, | |
| 16 | - | halving-indexed private-fork K inequalities, clArk tree exit weights, and a | |
| 17 | - | REAL 2,000-step randomized state-machine simulation with genuine Bitcoin reorgs. | |
| 18 | - | ||
| 19 | - | Every modeled constant is explicitly prefixed by provenance: | |
| 20 | - | - SOURCED_ : Bitcoin BIPs, historical chain telemetry, or go-zenon origin/dev | |
| 21 | - | - POLICY_ : Explicit protocol design parameters | |
| 22 | - | - PRE_MAINNET_TARGET_ : BitVMX-CPU / rollup sizing targets to be empirically measured on Signet | |
| 23 | - | ||
| 24 | - | This script is a consistency & bounds checker — NOT an empirical Signet benchmark | |
| 25 | - | and NOT a substitute for independent cryptographic/implementation audits. | |
| 26 | - | ||
| 27 | - | Run: `python3 -I scripts/verify_spec_bounds.py` | |
| 28 | - | """ | |
| 29 | - | import hashlib | |
| 30 | - | import math | |
| 31 | - | import random | |
| 32 | - | import struct | |
| 33 | - | ||
| 34 | - | SAT = 100_000_000 | |
| 35 | - | ||
| 36 | - | # ============================================================================== | |
| 37 | - | # SOURCED CONSTANTS (Bitcoin BIPs, Historical Telemetry, go-zenon origin/dev) | |
| 38 | - | # ============================================================================== | |
| 39 | - | SOURCED_BIP431_TRUC_MAX_VB = 10_000 # BIP-431 TRUC v3 single-tx vByte limit | |
| 40 | - | SOURCED_BIP342_MAX_STACK_ITEMS = 1_000 # BIP-342 Tapscript max stack elements | |
| 41 | - | SOURCED_BIP342_MAX_PUSH_BYTES = 520 # BIP-342 Tapscript max push element size | |
| 42 | - | SOURCED_BIP141_MAX_STRIPPED_BLOCK_BYTES = 1_000_000 # Bitcoin consensus max non-witness block bytes | |
| 43 | - | SOURCED_BTC_TARGET_BLOCK_SECS = 600 # 10 min nominal Bitcoin block interval | |
| 44 | - | SOURCED_BTC_BLOCKS_PER_DAY = 144 # Nominal blocks/day | |
| 45 | - | SOURCED_JUNE2021_SLOW_WEEKLY_MULT = 2.0 # June 2021 China ban: ~1.95-2.0x 7d avg | |
| 46 | - | SOURCED_JUNE2021_SLOW_DAILY_MULT = 2.3 # June 2021 China ban: ~23 min/blk daily peak | |
| 47 | - | SOURCED_APR2024_MEDIAN_FEE_SATVB = 1_805 # April 2024 halving/Runes median peak | |
| 48 | - | ||
| 49 | - | # Bitcoin block subsidy schedule (BTC/block) across halvings | |
| 50 | - | SOURCED_BTC_SUBSIDY_BY_ERA = { | |
| 51 | - | "2024-2028": 3.125, | |
| 52 | - | "2028-2032": 1.5625, | |
| 53 | - | "2032-2036": 0.78125, | |
| 54 | - | "2036-2040": 0.390625, | |
| 55 | - | } | |
| 56 | - | ||
| 57 | - | # ZNN market-cap context (Nov 2026 observed range; 0% ZNN in BTC custody safety!) | |
| 58 | - | SOURCED_ZNN_MCAP_BTC_LOW = 25.0 | |
| 59 | - | SOURCED_ZNN_MCAP_BTC_HIGH = 33.0 | |
| 60 | - | ||
| 61 | - | # go-zenon origin/dev protocol constants | |
| 62 | - | SOURCED_ZNN_MAX_DATA_LENGTH = 16_384 # dev:vm/constants/plasma.go:67 | |
| 63 | - | SOURCED_ZNN_ACCOUNT_BLOCK_BASE_PLASMA = 21_000 # dev:vm/constants/plasma.go | |
| 64 | - | SOURCED_ZNN_AB_BYTE_DATA_PLASMA = 68 # dev:vm/constants/plasma.go (DynamicPlasmaSpork) | |
| 65 | - | SOURCED_ZNN_EMBEDDED_SIMPLE_TIER = 52_500 # 2.5 * 21,000 | |
| 66 | - | SOURCED_ZNN_EMBEDDED_HEAVY_SPV_TIER = 73_500 # 3.5 * 21,000 | |
| 67 | - | SOURCED_ZNN_PLASMA_PER_QSR = 2_100 # 1 QSR = 1 fusion unit = 2,100 Plasma @ price 1,000 | |
| 68 | - | SOURCED_ZNN_POW_DIFF_PER_PLASMA = 1_500 # dev:vm/constants/plasma.go | |
| 69 | - | SOURCED_ZNN_MIN_RESOURCE_PRICE = 1_000 # dev:dp/dp.go | |
| 70 | - | SOURCED_ZNN_DP_DEFAULT_MAX_BASE_PLASMA = 4_200_000 # dev:vm/embedded/definition/plasma.go:97 | |
| 71 | - | SOURCED_ZNN_DP_UPPER_MAX_BASE_PLASMA = 2_100_000_000 # dev:vm/embedded/definition/plasma.go:63 | |
| 72 | - | SOURCED_ZNN_DP_LOWER_MAX_BASE_PLASMA = 210_000 # dev:vm/embedded/definition/plasma.go:66 | |
| 73 | - | SOURCED_ZNN_OBSERVED_MOMENTUM_SECS = 11.4 # dev:vm/embedded/definition/spork.go (11.35-11.46s) | |
| 74 | - | SOURCED_ZNN_CHAIN_BRIDGE_ROLLBACK = 30 # dev:protocol/chain_bridge.go:293 | |
| 75 | - | SOURCED_ZNN_MAX_MOMENTUM_CONTENT_BYTES = 8 * 1024 * 1024 # dev:verifier/momentum.go:93 (8 MiB) | |
| 76 | - | SOURCED_ZNN_PROTOCOL_MAX_MSG_SIZE = 10 * 1024 * 1024 # dev:protocol/protocol.go (10 MiB) | |
| 77 | - | SOURCED_ZNN_SOFT_RESPONSE_LIMIT = 2 * 1024 * 1024 # dev:protocol/protocol.go (2 MiB) | |
| 78 | - | SOURCED_ZNN_MAX_DETAILED_MOMENTUM_WIRE = ( | |
| 79 | - | SOURCED_ZNN_PROTOCOL_MAX_MSG_SIZE - SOURCED_ZNN_SOFT_RESPONSE_LIMIT - 4096 | |
| 80 | - | ) # 8,384,512 B (dev:protocol/protocol.go:70) | |
| 81 | - | SOURCED_ZNN_MIN_ACCOUNT_BLOCK_WIRE_LOW = 300 # Conservative minimal serialized AccountBlock + content header | |
| 82 | - | SOURCED_ZNN_MIN_ACCOUNT_BLOCK_WIRE_HIGH = 350 # Typical minimal signed AccountBlock + 52B header | |
| 83 | - | ||
| 84 | - | # ============================================================================== | |
| 85 | - | # POLICY PARAMETERS (Stage 0, Stage 1A BitVMX, Stage 1B clArk) | |
| 86 | - | # ============================================================================== | |
| 87 | - | POLICY_PINNED_MAX_BASE_PLASMA_FLOOR = 2_100_000 # Pinned >= 2.1M Plasma/Momentum | |
| 88 | - | POLICY_PINNED_MAX_PRICE_CHANGE_PCT = 25 # MaxPriceChangePercent <= 25% | |
| 89 | - | POLICY_PINNED_MIN_TARGET_SHARE_PCT = 25 # Fused/Pow targets >= 25% of 2.1M floor (525,000) | |
| 90 | - | POLICY_PINNED_MIN_PRICE_DENOM = 8 # PriceChangeDenominator >= 8 (spec/05 §2.2) | |
| 91 | - | POLICY_STAGE0_MAX_STRIPPED_TX_BYTES = 6_144 # Stage 0 SPV Event Oracle tx cap | |
| 92 | - | POLICY_STAGE0_MAX_STORAGE_OPS = 24 # Per-call L1 storage op ceiling | |
| 93 | - | ||
| 94 | - | # Stage 0 PTLC / LN non-custodial swap parameters | |
| 95 | - | POLICY_PTLC_BTC_CSV_BLOCKS = 72 | |
| 96 | - | POLICY_PTLC_BOB_CONFIRM_MARGIN_BLOCKS = 6 # Bob confirms <= h_conf + 66 w/ CPFP | |
| 97 | - | POLICY_PTLC_ALICE_RELEASE_MAX_BLOCKS = 6 | |
| 98 | - | POLICY_PTLC_ZNN_DURATION_SECS = 108_000 # 30.0 hours (passed as now + 108_000 Unix ts!) | |
| 99 | - | POLICY_LN_DELTA_SAFETY_BLOCKS = 36 | |
| 100 | - | ||
| 101 | - | # Stage 1A Right-Sized BitVMX (n=8) + Sovereign ZK Rollup parameters | |
| 102 | - | POLICY_BITVMX_N_BRANCH = 8 # n=8 (3 bits/round -> 7 intermediate hashes) | |
| 103 | - | POLICY_BITVMX_SEARCH_ROUNDS = 9 # 8^9 = 2^27 = 134,217,728 RV32IM instructions | |
| 104 | - | POLICY_BITVMX_M_MIN = 3 # Minimal competitive operator count | |
| 105 | - | POLICY_BITVMX_M_MAX = 5 # Pilot operator count | |
| 106 | - | POLICY_BITVMX_L_LANES = 1 # Lanes per operator | |
| 107 | - | POLICY_BITVMX_N_VERIFIERS = 7 # Pre-committed online verifiers | |
| 108 | - | POLICY_BITVMX_R_ROUNDS = 64 # Pre-signed rounds per lane | |
| 109 | - | POLICY_STAGE2_TOTAL_LANES = 40 # Stage 2 scaled lane count (40 * 64 = 2,560 leaves) | |
| 110 | - | ||
| 111 | - | 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 | |
| 112 | - | POLICY_VAULT_ALT_SPLIT_SATS = (50_000_000, 50_000_000) # Optional {0.50, 0.50} split comparison | |
| 113 | - | POLICY_MAX_VAULT_DENOM_SATS = 50_000_000 # 0.50 BTC ceiling per vault UTXO | |
| 114 | - | POLICY_MIN_EXIT_SATS = 100_000 # 0.001 BTC minimum exit | |
| 115 | - | ||
| 116 | - | # Stage 1A Per-Lane Bond & Verifier Economics | |
| 117 | - | POLICY_BOND_BTC_SATS = 200_000_000 # 2.00 BTC L1 Stake_r bond | |
| 118 | - | POLICY_B_ZBTC_CUSTODY_SATS = 50_000_000 # 0.50 BTC maxVaultDenom restitution floor | |
| 119 | - | POLICY_B_ZBTC_EQUIV_BOUNTY_SATS = 5_000_000 # 0.05 BTC Lamport equivocation bounty | |
| 120 | - | POLICY_B_ZBTC_GRIEF_BUFFER_SATS = 5_000_000 # 0.05 BTC ExitSlotUTXO grief buffer | |
| 121 | - | POLICY_B_ZBTC_TOTAL_SATS = ( | |
| 122 | - | POLICY_B_ZBTC_CUSTODY_SATS + POLICY_B_ZBTC_EQUIV_BOUNTY_SATS + POLICY_B_ZBTC_GRIEF_BUFFER_SATS | |
| 123 | - | ) # 0.60 BTC total locked zBTC/lane | |
| 124 | - | POLICY_B_ZBTC_CUSTODY_SLICE_SATS = ( | |
| 125 | - | POLICY_B_ZBTC_CUSTODY_SATS + POLICY_B_ZBTC_EQUIV_BOUNTY_SATS | |
| 126 | - | ) # 0.55 BTC custody slice split across remaining challengers on Disprove | |
| 127 | - | POLICY_LANE_TOTAL_BOND_SATS = POLICY_BOND_BTC_SATS + POLICY_B_ZBTC_TOTAL_SATS # 2.60 BTC/lane | |
| 128 | - | POLICY_F_CHAL_SATS = 40_000_000 # 0.40 BTC verifier challenge escrow | |
| 129 | - | POLICY_WINNING_VERIFIER_L1_SATS = 15_000_000 # 0.15 BTC L1 payout to winning verifier | |
| 130 | - | POLICY_BURNED_BOND_SATS = 185_000_000 # 1.85 BTC burned to OP_RETURN on Disprove/TimeoutSlash | |
| 131 | - | POLICY_EXIT_GRIEF_SLASH_SATS = 1_000_000 # 0.01 BTC non-paying ExitSlotUTXO slash | |
| 132 | - | POLICY_DESIGN_SUSTAINED_FEE_SATVB = 500 # 500 sat/vB sustained across full dispute | |
| 133 | - | ||
| 134 | - | # Stage 1A Simultaneous-Challenge BitVMX Timelocks (blocks) | |
| 135 | - | POLICY_T_CHAL_WINDOW = 144 # Simultaneous [0, 144] challenge window (24h) | |
| 136 | - | POLICY_T_STEP = 48 # 8h per bisection step | |
| 137 | - | POLICY_T_TAKE = 1_152 # 8.0d (> max_dispute_end = 1,104) | |
| 138 | - | POLICY_T_COOLDOWN = 1_296 # 9.0d (1,152 + 144-blk Lamport equivocation slash window) | |
| 139 | - | POLICY_T_RETIRE = 1_440 # 10.0d Stake retirement CSV | |
| 140 | - | POLICY_T_EXIT_CANCEL = 288 # 48h user unilateral EXIT_CANCEL leaf | |
| 141 | - | ||
| 142 | - | # Stage 1A Capital & TVL Profiles | |
| 143 | - | POLICY_STAGE1A_PROFILES = { | |
| 144 | - | "M=3 (<=10 BTC cap)": {"M": 3, "cap_btc": 10.0, "float_btc": 2.20, "K_2024": 14}, | |
| 145 | - | "M=5 (<=15 BTC cap)": {"M": 5, "cap_btc": 15.0, "float_btc": 3.00, "K_2024": 14}, | |
| 146 | - | } | |
| 147 | - | POLICY_TVL_TIERS_BTC = (10, 15, 50, 200) | |
| 148 | - | POLICY_CONFIGURED_K_2024 = {10: 14, 15: 14, 50: 36, 200: 144} | |
| 149 | - | POLICY_CONFIGURED_K_BY_ERA = { | |
| 150 | - | "2024-2028": {10: 14, 15: 14, 50: 36, 200: 144}, | |
| 151 | - | "2028-2032": {10: 14, 15: 20, 50: 66, 200: 260}, | |
| 152 | - | "2032-2036": {10: 28, 15: 40, 50: 130, 200: 516}, | |
| 153 | - | } | |
| 154 | - | ||
| 155 | - | # ============================================================================== | |
| 156 | - | # PRE-MAINNET TARGETS (BitVMX-CPU / Rollup / BitVM2 / clArk — Signet-Gated) | |
| 157 | - | # ============================================================================== | |
| 158 | - | PRE_MAINNET_TARGET_ROLLUP_TX_DATA_BYTES = 110 # Signed rollup transfer in AccountBlock.Data | |
| 159 | - | PRE_MAINNET_TARGET_DEPOSIT_CERTBLOB_BYTES = 104 # Acyclic OP_DROP certBlob <= 520 B | |
| 160 | - | PRE_MAINNET_TARGET_WOTS_DIGIT_WU = 95.5 # Per base-16 W-OTS digit weight (WU) | |
| 161 | - | PRE_MAINNET_TARGET_BISECTION_OVERHEAD_VB = 250.0 # Per prover bisection tx non-WOTS overhead (vB) | |
| 162 | - | PRE_MAINNET_TARGET_START_TX_VB = 3_000.0 # Prover StartTx vBytes | |
| 163 | - | PRE_MAINNET_TARGET_FINAL_TRACE_TX_VB = 5_000.0 # Prover FinalTraceTx vBytes | |
| 164 | - | PRE_MAINNET_TARGET_CHALLENGE_TX_VB = 350.0 # Verifier ChallengeTx vBytes | |
| 165 | - | PRE_MAINNET_TARGET_VERIFIER_CHOICE_VB = 350.0 # Verifier 3-bit interval choice tx vBytes | |
| 166 | - | PRE_MAINNET_TARGET_EXECUTE_OPCODE_VB = 8_000.0 # Verifier final 1-opcode disprove tx vBytes | |
| 167 | - | PRE_MAINNET_TARGET_VERIFIER_CONSERVATIVE_VB = 15_000 # Conservative verifier total dispute budget (vB) | |
| 168 | - | PRE_MAINNET_TARGET_PROVER_CONSERVATIVE_VB = 75_000 # Conservative prover total dispute budget (vB) | |
| 169 | - | PRE_MAINNET_TARGET_BITVM2_LANE_BOND_BTC_LOW = 13.30 # Minimal BitVM2 lane bond @ 200 sat/vB | |
| 170 | - | PRE_MAINNET_TARGET_BITVM2_LANE_BOND_BTC_HIGH = 18.175 # Minimal BitVM2 lane bond @ 500 sat/vB | |
| 171 | - | PRE_MAINNET_TARGET_CLARK_ACTIVE_LIQ_BTC = (2.0, 5.0) # Stage 1B clArk active ASP liquidity range | |
| 172 | - | PRE_MAINNET_TARGET_CLARK_VTXO_COUNTS = (64, 128, 256, 512, 1024) | |
| 173 | - | ||
| 174 | - | ||
| 175 | - | # ============================================================================== | |
| 176 | - | # HELPER FUNCTIONS (Pure Python Stdlib) | |
| 177 | - | # ============================================================================== | |
| 178 | - | def ceil_div(a: int, b: int) -> int: | |
| 179 | - | return (a + b - 1) // b | |
| 180 | - | ||
| 181 | - | ||
| 182 | - | def compact_size_len(n: int) -> int: | |
| 183 | - | if n < 253: | |
| 184 | - | return 1 | |
| 185 | - | if n <= 0xFFFF: | |
| 186 | - | return 3 | |
| 187 | - | if n <= 0xFFFFFFFF: | |
| 188 | - | return 5 | |
| 189 | - | return 9 | |
| 190 | - | ||
| 191 | - | ||
| 192 | - | def abi_single_bytes_call(payload_len: int, static_head_words: int = 1) -> int: | |
| 193 | - | """Exact go-zenon ABI size for fn(static_args..., bytes payload).""" | |
| 194 | - | return 4 + 32 * static_head_words + 32 + 32 + 32 * ceil_div(payload_len, 32) | |
| 195 | - | ||
| 196 | - | ||
| 197 | - | def abi_embedded_plasma(tier: int, abi_len: int) -> int: | |
| 198 | - | assert abi_len <= SOURCED_ZNN_MAX_DATA_LENGTH, f"ABI len {abi_len} exceeds 16 KiB" | |
| 199 | - | return tier + max(0, abi_len - 4) * SOURCED_ZNN_AB_BYTE_DATA_PLASMA | |
| 200 | - | ||
| 201 | - | ||
| 202 | - | # FIPS 180-4 SHA-256 single-block compression (for real coinbase midstate verification) | |
| 203 | - | _SHA256_IV = ( | |
| 204 | - | 0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, | |
| 205 | - | 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19, | |
| 206 | - | ) | |
| 207 | - | _SHA256_K = ( | |
| 208 | - | 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5, | |
| 209 | - | 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3, 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174, | |
| 210 | - | 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC, 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA, | |
| 211 | - | 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7, 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967, | |
| 212 | - | 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13, 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85, | |
| 213 | - | 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3, 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070, | |
| 214 | - | 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5, 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3, | |
| 215 | - | 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208, 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2, | |
| 216 | - | ) | |
| 217 | - | ||
| 218 | - | ||
| 219 | - | def _rotr32(x: int, n: int) -> int: | |
| 220 | - | return ((x >> n) | ((x << (32 - n)) & 0xFFFFFFFF)) & 0xFFFFFFFF | |
| 221 | - | ||
| 222 | - | ||
| 223 | - | def sha256_compress(state: tuple[int, ...], block64: bytes) -> tuple[int, ...]: | |
| 224 | - | assert len(block64) == 64 | |
| 225 | - | w = list(struct.unpack(">16I", block64)) | |
| 226 | - | for i in range(16, 64): | |
| 227 | - | s0 = _rotr32(w[i - 15], 7) ^ _rotr32(w[i - 15], 18) ^ (w[i - 15] >> 3) | |
| 228 | - | s1 = _rotr32(w[i - 2], 17) ^ _rotr32(w[i - 2], 19) ^ (w[i - 2] >> 10) | |
| 229 | - | w.append((w[i - 16] + s0 + w[i - 7] + s1) & 0xFFFFFFFF) | |
| 230 | - | a, b, c, d, e, f, g, h = state | |
| 231 | - | for i in range(64): | |
| 232 | - | S1 = _rotr32(e, 6) ^ _rotr32(e, 11) ^ _rotr32(e, 25) | |
| 233 | - | ch = (e & f) ^ ((~e & 0xFFFFFFFF) & g) | |
| 234 | - | t1 = (h + S1 + ch + _SHA256_K[i] + w[i]) & 0xFFFFFFFF | |
| 235 | - | S0 = _rotr32(a, 2) ^ _rotr32(a, 13) ^ _rotr32(a, 22) | |
| 236 | - | maj = (a & b) ^ (a & c) ^ (b & c) | |
| 237 | - | t2 = (S0 + maj) & 0xFFFFFFFF | |
| 238 | - | h, g, f, e, d, c, b, a = g, f, e, (d + t1) & 0xFFFFFFFF, c, b, a, (t1 + t2) & 0xFFFFFFFF | |
| 239 | - | return tuple((s + x) & 0xFFFFFFFF for s, x in zip(state, (a, b, c, d, e, f, g, h))) | |
| 240 | - | ||
| 241 | - | ||
| 242 | - | def complete_midstate_double_sha256(midstate_bytes: bytes, tail: bytes, total_len: int) -> tuple[bytes, int]: | |
| 243 | - | """ | |
| 244 | - | Normative 1-/2-block coinbase midstate completion (spec/02 §2.3): | |
| 245 | - | - Enforces total_len >= 65 (rejects total_len == 64 CVE-2017-12842 leaf forgery & short txs) | |
| 246 | - | - Enforces len(tail) == total_len % 64 < 64 | |
| 247 | - | - Handles BOTH 1-block (rem < 56) and 2-block (rem in 56..63) final SHA-256 padding. | |
| 248 | - | Returns (double_sha256_digest, final_compression_blocks_used). | |
| 249 | - | """ | |
| 250 | - | assert len(midstate_bytes) == 32 | |
| 251 | - | assert total_len >= 65, "CVE-2017-12842: totalCoinbaseBytes must be >= 65 (64-byte leaf forbidden)" | |
| 252 | - | rem = total_len % 64 | |
| 253 | - | assert len(tail) == rem and len(tail) < 64 | |
| 254 | - | padded = bytearray(tail) | |
| 255 | - | padded.append(0x80) | |
| 256 | - | while len(padded) % 64 != 56: | |
| 257 | - | padded.append(0x00) | |
| 258 | - | padded.extend(struct.pack(">Q", total_len * 8)) | |
| 259 | - | blocks = len(padded) // 64 | |
| 260 | - | assert blocks in (1, 2) | |
| 261 | - | state = struct.unpack(">8I", midstate_bytes) | |
| 262 | - | for idx in range(blocks): | |
| 263 | - | state = sha256_compress(state, bytes(padded[idx * 64 : (idx + 1) * 64])) | |
| 264 | - | first_round = struct.pack(">8I", *state) | |
| 265 | - | return hashlib.sha256(first_round).digest(), blocks | |
| 266 | - | ||
| 267 | - | ||
| 268 | - | def dp_next_price( | |
| 269 | - | current_price: int, | |
| 270 | - | used_plasma: int, | |
| 271 | - | target_plasma: int, | |
| 272 | - | max_change_pct: int, | |
| 273 | - | denom: int, | |
| 274 | - | ) -> int: | |
| 275 | - | """Exact mirror of go-zenon origin/dev:dp/dp.go dynamic price step.""" | |
| 276 | - | delta = used_plasma - target_plasma | |
| 277 | - | # Go big.Int truncation toward zero on division | |
| 278 | - | num = delta * current_price | |
| 279 | - | if num >= 0: | |
| 280 | - | change = (num // target_plasma) // denom | |
| 281 | - | else: | |
| 282 | - | change = -((-num // target_plasma) // denom) | |
| 283 | - | nxt = current_price + change | |
| 284 | - | max_nxt = (current_price * (100 + max_change_pct)) // 100 | |
| 285 | - | min_nxt = (current_price * (100 - max_change_pct)) // 100 | |
| 286 | - | if nxt > max_nxt: | |
| 287 | - | nxt = max_nxt | |
| 288 | - | if nxt < min_nxt: | |
| 289 | - | nxt = min_nxt | |
| 290 | - | if nxt < SOURCED_ZNN_MIN_RESOURCE_PRICE: | |
| 291 | - | nxt = SOURCED_ZNN_MIN_RESOURCE_PRICE | |
| 292 | - | return nxt | |
| 293 | - | ||
| 294 | - | ||
| 295 | - | # ============================================================================== | |
| 296 | - | # REAL, NON-NO-OP 2,000-STEP RANDOMIZED STAGE 1A SOLVENCY SIMULATION | |
| 297 | - | # ============================================================================== | |
| 298 | - | def run_stage1a_solvency_sim(seed: int = 20261128, steps: int = 2_000) -> dict[str, int]: | |
| 299 | - | """ | |
| 300 | - | Adversarial state-machine simulation of the Stage 1A BitVMX (n=8, M=5, N=7) | |
| 301 | - | + Bitcoin-Anchored Sovereign ZK Rollup with: | |
| 302 | - | - Explicit Bob (1 -> 0.5 -> exit 0.5) & Mike (Alice 1 + Bob 1 -> 2 -> exit 0.25) flows | |
| 303 | - | - Real Bitcoin block tip + confirmation depth K=14 | |
| 304 | - | - GENUINE Bitcoin reorgs (popping 1..K-1 unconfirmed blocks & discarding orphaned events!) | |
| 305 | - | - Multi-tier {0.50, 0.25, 0.25} BTC deposits | |
| 306 | - | - Feeless rollup transfers | |
| 307 | - | - ExitSlotUTXO honest fronting + non-paying grief slashes (0.01 BTC + refund + auto-suspend) | |
| 308 | - | - Leaf 2M EXIT_CANCEL user refunds after 288 blocks | |
| 309 | - | - Dual-input Disprove slashes (Stake_r + VaultConnector_r -> 0 vault stolen + 0.55 BTC split) | |
| 310 | - | - Lamport L_{j,l,r} equivocation slashes (D_d burned from B_zbtc -> exact 1:1 solvency!) | |
| 311 | - | Asserts EXACT 1:1 backing conservation at EVERY single step. | |
| 312 | - | """ | |
| 313 | - | rng = random.Random(seed) | |
| 314 | - | K = POLICY_CONFIGURED_K_2024[15] # 14 blocks | |
| 315 | - | cap_sats = int(15.0 * SAT) | |
| 316 | - | ||
| 317 | - | # Canonical K-deep rollup state | |
| 318 | - | users: dict[str, int] = { | |
| 319 | - | "alice": 0, "bob": 0, "mike": 0, "carol": 0, "dave": 0, | |
| 320 | - | "challenger_pool": 0, | |
| 321 | - | } | |
| 322 | - | # Operators O_0 .. O_4 (M = 5) | |
| 323 | - | # Each operator starts with 1.00 BTC deposited (two 0.50 BTC vaults) backing 0.60 B_zbtc + 0.40 liquid zBTC | |
| 324 | - | # so every satoshi of B_zbtc in the rollup is backed 1:1 by real confirmed L1 vault BTC! | |
| 325 | - | confirmed_vaults: dict[int, int] = {} # vault_id -> sats (unassigned & unspent K-deep) | |
| 326 | - | next_vault_id = 1 | |
| 327 | - | operators: dict[int, dict] = {} | |
| 328 | - | for op_id in range(POLICY_BITVMX_M_MAX): | |
| 329 | - | for _ in range(2): | |
| 330 | - | confirmed_vaults[next_vault_id] = 50_000_000 # 0.50 BTC | |
| 331 | - | next_vault_id += 1 | |
| 332 | - | operators[op_id] = { | |
| 333 | - | "b_zbtc": POLICY_B_ZBTC_TOTAL_SATS, # 0.60 BTC locked collateral | |
| 334 | - | "free_zbtc": 40_000_000, # 0.40 BTC operator liquid zBTC (for top-ups) | |
| 335 | - | "credit": 0, # ReimbursementCredit[op] | |
| 336 | - | "suspended": False, | |
| 337 | - | } | |
| 338 | - | ||
| 339 | - | # Pending exits (canonical K-deep): exit_id -> {"user", "gross", "created_h", "state": "OPEN"} | |
| 340 | - | pending_exits: dict[int, dict] = {} | |
| 341 | - | next_exit_id = 1 | |
| 342 | - | ||
| 343 | - | # Unconfirmed Bitcoin tip buffer (heights > finalized_height; reorgable!) | |
| 344 | - | # Each block = {"height": int, "events": list[dict]} | |
| 345 | - | finalized_height = 100 | |
| 346 | - | tip_blocks: list[dict] = [] | |
| 347 | - | ||
| 348 | - | # Track unconfirmed reservations so we don't double-spend same exit/vault inside one fork | |
| 349 | - | unconf_spent_exits: set[int] = set() | |
| 350 | - | unconf_claimed_vaults: set[int] = set() | |
| 351 | - | unconf_pending_credit_used: dict[int, int] = {i: 0 for i in range(POLICY_BITVMX_M_MAX)} | |
| 352 | - | ||
| 353 | - | counts: dict[str, int] = { | |
| 354 | - | k: 0 for k in ( | |
| 355 | - | "deposit", "transfer", "forced_exit", "front_paid", "front_grief", | |
| 356 | - | "exit_cancel", "take_honest", "disprove_dual_slash", | |
| 357 | - | "lamport_equivocation_slash", "topup_op", "mine_block", "reorg", | |
| 358 | - | "reorg_blocks_reverted", "reorg_events_reverted", | |
| 359 | - | ) | |
| 360 | - | } | |
| 361 | - | ||
| 362 | - | def rebuild_unconf_locks() -> None: | |
| 363 | - | unconf_spent_exits.clear() | |
| 364 | - | unconf_claimed_vaults.clear() | |
| 365 | - | for i in unconf_pending_credit_used: | |
| 366 | - | unconf_pending_credit_used[i] = 0 | |
| 367 | - | for blk in tip_blocks: | |
| 368 | - | for ev in blk["events"]: | |
| 369 | - | kind = ev["kind"] | |
| 370 | - | if kind in ("front_paid", "front_grief", "exit_cancel"): | |
| 371 | - | unconf_spent_exits.add(ev["exit_id"]) | |
| 372 | - | elif kind == "take_honest": | |
| 373 | - | unconf_claimed_vaults.add(ev["vault_id"]) | |
| 374 | - | unconf_pending_credit_used[ev["op_id"]] += ev["amount"] | |
| 375 | - | elif kind == "lamport_equivocation_slash": | |
| 376 | - | unconf_claimed_vaults.add(ev["vault_id"]) | |
| 377 | - | ||
| 378 | - | def apply_finalized_event(ev: dict, blk_height: int) -> None: | |
| 379 | - | nonlocal next_vault_id, next_exit_id | |
| 380 | - | kind = ev["kind"] | |
| 381 | - | if kind == "deposit": | |
| 382 | - | # Multi-tier vaults enter confirmed L1 pool AND mint exact 1:1 zBTC | |
| 383 | - | for vid, vamt in ev["vaults"]: | |
| 384 | - | confirmed_vaults[vid] = vamt | |
| 385 | - | users[ev["user"]] += sum(vamt for _, vamt in ev["vaults"]) | |
| 386 | - | counts["deposit"] += 1 | |
| 387 | - | ||
| 388 | - | elif kind == "forced_exit": | |
| 389 | - | u = ev["user"] | |
| 390 | - | amt = ev["gross"] | |
| 391 | - | if users[u] >= amt: | |
| 392 | - | users[u] -= amt | |
| 393 | - | pending_exits[ev["exit_id"]] = { | |
| 394 | - | "user": u, "gross": amt, "created_h": blk_height, | |
| 395 | - | } | |
| 396 | - | counts["forced_exit"] += 1 | |
| 397 | - | ||
| 398 | - | elif kind == "front_paid": | |
| 399 | - | eid = ev["exit_id"] | |
| 400 | - | if eid in pending_exits: | |
| 401 | - | ex = pending_exits.pop(eid) | |
| 402 | - | operators[ev["op_id"]]["credit"] += ex["gross"] | |
| 403 | - | counts["front_paid"] += 1 | |
| 404 | - | ||
| 405 | - | elif kind == "front_grief": | |
| 406 | - | # Non-paying ExitSlotUTXO spend -> cancel + refund + 0.01 BTC slash + auto-suspend! | |
| 407 | - | eid = ev["exit_id"] | |
| 408 | - | op = operators[ev["op_id"]] | |
| 409 | - | if eid in pending_exits and op["b_zbtc"] >= POLICY_B_ZBTC_CUSTODY_SLICE_SATS + POLICY_EXIT_GRIEF_SLASH_SATS: | |
| 410 | - | ex = pending_exits.pop(eid) | |
| 411 | - | users[ex["user"]] += ex["gross"] | |
| 412 | - | op["b_zbtc"] -= POLICY_EXIT_GRIEF_SLASH_SATS | |
| 413 | - | users[ex["user"]] += POLICY_EXIT_GRIEF_SLASH_SATS | |
| 414 | - | op["suspended"] = True | |
| 415 | - | assert op["b_zbtc"] >= POLICY_B_ZBTC_CUSTODY_SLICE_SATS, "Grief slash breached 0.55 BTC custody floor!" | |
| 416 | - | counts["front_grief"] += 1 | |
| 417 | - | ||
| 418 | - | elif kind == "exit_cancel": | |
| 419 | - | eid = ev["exit_id"] | |
| 420 | - | if eid in pending_exits and blk_height >= pending_exits[eid]["created_h"] + POLICY_T_EXIT_CANCEL: | |
| 421 | - | ex = pending_exits.pop(eid) | |
| 422 | - | users[ex["user"]] += ex["gross"] | |
| 423 | - | counts["exit_cancel"] += 1 | |
| 424 | - | ||
| 425 | - | elif kind == "take_honest": | |
| 426 | - | vid = ev["vault_id"] | |
| 427 | - | op = operators[ev["op_id"]] | |
| 428 | - | if vid in confirmed_vaults and op["credit"] >= confirmed_vaults[vid]: | |
| 429 | - | vamt = confirmed_vaults.pop(vid) | |
| 430 | - | op["credit"] -= vamt | |
| 431 | - | counts["take_honest"] += 1 | |
| 432 | - | ||
| 433 | - | elif kind == "disprove_dual_slash": | |
| 434 | - | # Dual-input Disprove spends Stake_r + VaultConnector_r -> 0 vault stolen! | |
| 435 | - | # 0.55 BTC custody slice of B_zbtc splits across remaining challengers; operator paused. | |
| 436 | - | op = operators[ev["op_id"]] | |
| 437 | - | if op["b_zbtc"] >= POLICY_B_ZBTC_CUSTODY_SLICE_SATS: | |
| 438 | - | op["b_zbtc"] -= POLICY_B_ZBTC_CUSTODY_SLICE_SATS | |
| 439 | - | users["challenger_pool"] += POLICY_B_ZBTC_CUSTODY_SLICE_SATS | |
| 440 | - | op["suspended"] = True | |
| 441 | - | counts["disprove_dual_slash"] += 1 | |
| 442 | - | ||
| 443 | - | elif kind == "lamport_equivocation_slash": | |
| 444 | - | # Operator stole vault U_2 != U_1 (D_d <= 0.50 BTC); BurnBondTx burns 2.00 BTC L1, | |
| 445 | - | # STARK atomically burns D_d from op.b_zbtc (1:1 solvency!) + pays 0.05 BTC bounty. | |
| 446 | - | vid = ev["vault_id"] | |
| 447 | - | op = operators[ev["op_id"]] | |
| 448 | - | if vid in confirmed_vaults: | |
| 449 | - | vamt = confirmed_vaults[vid] | |
| 450 | - | if op["b_zbtc"] >= vamt + POLICY_B_ZBTC_EQUIV_BOUNTY_SATS: | |
| 451 | - | confirmed_vaults.pop(vid) | |
| 452 | - | op["b_zbtc"] -= (vamt + POLICY_B_ZBTC_EQUIV_BOUNTY_SATS) | |
| 453 | - | users["challenger_pool"] += POLICY_B_ZBTC_EQUIV_BOUNTY_SATS | |
| 454 | - | op["suspended"] = True | |
| 455 | - | counts["lamport_equivocation_slash"] += 1 | |
| 456 | - | ||
| 457 | - | def assert_solvency(label: str) -> None: | |
| 458 | - | vault_backing = sum(confirmed_vaults.values()) | |
| 459 | - | circ_users = sum(users.values()) | |
| 460 | - | pending_total = sum(ex["gross"] for ex in pending_exits.values()) | |
| 461 | - | credits_total = sum(op["credit"] for op in operators.values()) | |
| 462 | - | op_b_zbtc = sum(op["b_zbtc"] for op in operators.values()) | |
| 463 | - | op_free_zbtc = sum(op["free_zbtc"] for op in operators.values()) | |
| 464 | - | total_liabilities = circ_users + pending_total + credits_total + op_b_zbtc + op_free_zbtc | |
| 465 | - | assert vault_backing == total_liabilities, ( | |
| 466 | - | f"[{label}] Solvency mismatch! vault_backing={vault_backing} != liabilities={total_liabilities}" | |
| 467 | - | ) | |
| 468 | - | # Active non-suspended operators must always maintain full 0.60 BTC B_zbtc floor | |
| 469 | - | for oid, op in operators.items(): | |
| 470 | - | if not op["suspended"]: | |
| 471 | - | assert op["b_zbtc"] >= POLICY_B_ZBTC_TOTAL_SATS, ( | |
| 472 | - | f"[{label}] Active operator {oid} b_zbtc={op['b_zbtc']} < 0.60 BTC floor" | |
| 473 | - | ) | |
| 474 | - | ||
| 475 | - | def mine_one_block(events: list[dict]) -> None: | |
| 476 | - | nonlocal finalized_height | |
| 477 | - | next_h = finalized_height + len(tip_blocks) + 1 | |
| 478 | - | tip_blocks.append({"height": next_h, "events": events}) | |
| 479 | - | counts["mine_block"] += 1 | |
| 480 | - | # Finalize any block now >= K deep (tip_height - blk_height + 1 >= K) | |
| 481 | - | while len(tip_blocks) >= K: | |
| 482 | - | fin_blk = tip_blocks.pop(0) | |
| 483 | - | finalized_height = fin_blk["height"] | |
| 484 | - | for ev in fin_blk["events"]: | |
| 485 | - | apply_finalized_event(ev, finalized_height) | |
| 486 | - | rebuild_unconf_locks() | |
| 487 | - | ||
| 488 | - | def current_tip_height() -> int: | |
| 489 | - | return finalized_height + len(tip_blocks) | |
| 490 | - | ||
| 491 | - | assert_solvency("init") | |
| 492 | - | ||
| 493 | - | # ------------------------------------------------------------------ | |
| 494 | - | # DETERMINISTIC VERIFICATION OF BOB (1 -> 0.5 -> 0.5) & MIKE (1+1 -> 2 -> 0.25) | |
| 495 | - | # ------------------------------------------------------------------ | |
| 496 | - | # Bob deposits 1.0 BTC -> {0.50, 0.25, 0.25} vaults | |
| 497 | - | bob_vaults = [] | |
| 498 | - | for amt in POLICY_VAULT_TIERS_SATS: | |
| 499 | - | bob_vaults.append((next_vault_id, amt)) | |
| 500 | - | next_vault_id += 1 | |
| 501 | - | # Alice deposits 1.0 BTC -> {0.50, 0.25, 0.25} vaults | |
| 502 | - | alice_vaults = [] | |
| 503 | - | for amt in POLICY_VAULT_TIERS_SATS: | |
| 504 | - | alice_vaults.append((next_vault_id, amt)) | |
| 505 | - | next_vault_id += 1 | |
| 506 | - | mine_one_block([ | |
| 507 | - | {"kind": "deposit", "user": "bob", "vaults": bob_vaults}, | |
| 508 | - | {"kind": "deposit", "user": "alice", "vaults": alice_vaults}, | |
| 509 | - | ]) | |
| 510 | - | for _ in range(K - 1): | |
| 511 | - | mine_one_block([]) | |
| 512 | - | assert users["bob"] == SAT and users["alice"] == SAT | |
| 513 | - | assert_solvency("after_bob_alice_deposits") | |
| 514 | - | ||
| 515 | - | # Bob spends 0.5 zBTC to Carol feelessly, then recovers 0.50 BTC via forced exit | |
| 516 | - | users["bob"] -= 50_000_000 | |
| 517 | - | users["carol"] += 50_000_000 | |
| 518 | - | counts["transfer"] += 1 | |
| 519 | - | bob_eid = next_exit_id | |
| 520 | - | next_exit_id += 1 | |
| 521 | - | mine_one_block([{"kind": "forced_exit", "user": "bob", "gross": 50_000_000, "exit_id": bob_eid}]) | |
| 522 | - | for _ in range(K - 1): | |
| 523 | - | mine_one_block([]) | |
| 524 | - | assert bob_eid in pending_exits and users["bob"] == 0 | |
| 525 | - | # Operator 0 fronts Bob's 0.50 BTC and later claims Bob's 0.50 BTC vault | |
| 526 | - | mine_one_block([{"kind": "front_paid", "exit_id": bob_eid, "op_id": 0}]) | |
| 527 | - | for _ in range(K - 1): | |
| 528 | - | mine_one_block([]) | |
| 529 | - | assert bob_eid not in pending_exits and operators[0]["credit"] == 50_000_000 | |
| 530 | - | mine_one_block([{"kind": "take_honest", "op_id": 0, "vault_id": bob_vaults[0][0], "amount": 50_000_000}]) | |
| 531 | - | for _ in range(K - 1): | |
| 532 | - | mine_one_block([]) | |
| 533 | - | assert operators[0]["credit"] == 0 | |
| 534 | - | assert_solvency("after_bob_0.5_recovery") | |
| 535 | - | ||
| 536 | - | # Mike scenario: Alice (1 BTC) + Bob2 (1 BTC -> Carol transfers + new Bob deposit) -> Mike has 2.0 zBTC -> exits 0.25 BTC | |
| 537 | - | bob2_vaults = [] | |
| 538 | - | for amt in POLICY_VAULT_TIERS_SATS: | |
| 539 | - | bob2_vaults.append((next_vault_id, amt)) | |
| 540 | - | next_vault_id += 1 | |
| 541 | - | mine_one_block([{"kind": "deposit", "user": "bob", "vaults": bob2_vaults}]) | |
| 542 | - | for _ in range(K - 1): | |
| 543 | - | mine_one_block([]) | |
| 544 | - | assert users["alice"] == SAT and users["bob"] == SAT | |
| 545 | - | users["alice"] -= SAT | |
| 546 | - | users["bob"] -= SAT | |
| 547 | - | users["mike"] += 2 * SAT | |
| 548 | - | counts["transfer"] += 2 | |
| 549 | - | mike_eid = next_exit_id | |
| 550 | - | next_exit_id += 1 | |
| 551 | - | # Mike posts 0x01 FORCED_EXIT directly on Bitcoin L1 (0 Zenon signer signatures!) | |
| 552 | - | mine_one_block([{"kind": "forced_exit", "user": "mike", "gross": 25_000_000, "exit_id": mike_eid}]) | |
| 553 | - | for _ in range(K - 1): | |
| 554 | - | mine_one_block([]) | |
| 555 | - | assert users["mike"] == 175_000_000 and mike_eid in pending_exits | |
| 556 | - | # Operator 1 fronts Mike's 0.25 BTC and claims a 0.25 BTC vault directly | |
| 557 | - | mine_one_block([{"kind": "front_paid", "exit_id": mike_eid, "op_id": 1}]) | |
| 558 | - | for _ in range(K - 1): | |
| 559 | - | mine_one_block([]) | |
| 560 | - | mine_one_block([{"kind": "take_honest", "op_id": 1, "vault_id": alice_vaults[1][0], "amount": 25_000_000}]) | |
| 561 | - | for _ in range(K - 1): | |
| 562 | - | mine_one_block([]) | |
| 563 | - | assert mike_eid not in pending_exits and operators[1]["credit"] == 0 | |
| 564 | - | assert_solvency("after_mike_0.25_recovery") | |
| 565 | - | ||
| 566 | - | # ------------------------------------------------------------------ | |
| 567 | - | # 2,000-STEP ADVERSARIAL RANDOMIZED SIMULATION (WITH REAL REORGS!) | |
| 568 | - | # ------------------------------------------------------------------ | |
| 569 | - | actions = [ | |
| 570 | - | "deposit", "transfer", "forced_exit", "front_paid", "front_grief", | |
| 571 | - | "exit_cancel", "take_honest", "disprove_dual_slash", | |
| 572 | - | "lamport_equivocation_slash", "topup_op", "mine_block", "reorg", | |
| 573 | - | ] | |
| 574 | - | weights = [10, 18, 12, 12, 6, 8, 10, 5, 5, 10, 26, 10] | |
| 575 | - | normal_users = ["alice", "bob", "mike", "carol", "dave"] | |
| 576 | - | ||
| 577 | - | for step in range(steps): | |
| 578 | - | act = rng.choices(actions, weights=weights, k=1)[0] | |
| 579 | - | ||
| 580 | - | if act == "deposit": | |
| 581 | - | cur_tvl = sum(confirmed_vaults.values()) | |
| 582 | - | if cur_tvl + SAT <= cap_sats: | |
| 583 | - | u = rng.choice(normal_users) | |
| 584 | - | new_vs = [] | |
| 585 | - | for amt in POLICY_VAULT_TIERS_SATS: | |
| 586 | - | new_vs.append((next_vault_id, amt)) | |
| 587 | - | next_vault_id += 1 | |
| 588 | - | mine_one_block([{"kind": "deposit", "user": u, "vaults": new_vs}]) | |
| 589 | - | ||
| 590 | - | elif act == "transfer": | |
| 591 | - | rich = [u for u in normal_users if users[u] >= POLICY_MIN_EXIT_SATS] | |
| 592 | - | if rich: | |
| 593 | - | src = rng.choice(rich) | |
| 594 | - | dst = rng.choice([u for u in normal_users if u != src]) | |
| 595 | - | amt = rng.randint(POLICY_MIN_EXIT_SATS, min(users[src], 50_000_000)) | |
| 596 | - | users[src] -= amt | |
| 597 | - | users[dst] += amt | |
| 598 | - | counts["transfer"] += 1 | |
| 599 | - | ||
| 600 | - | elif act == "forced_exit": | |
| 601 | - | rich = [u for u in normal_users if users[u] >= 25_000_000] | |
| 602 | - | if rich: | |
| 603 | - | u = rng.choice(rich) | |
| 604 | - | amt = rng.choice([25_000_000, 50_000_000]) if users[u] >= 50_000_000 else 25_000_000 | |
| 605 | - | eid = next_exit_id | |
| 606 | - | next_exit_id += 1 | |
| 607 | - | mine_one_block([{"kind": "forced_exit", "user": u, "gross": amt, "exit_id": eid}]) | |
| 608 | - | ||
| 609 | - | elif act == "front_paid": | |
| 610 | - | open_exits = [eid for eid in pending_exits if eid not in unconf_spent_exits] | |
| 611 | - | active_ops = [oid for oid, op in operators.items() if not op["suspended"]] | |
| 612 | - | if open_exits and active_ops: | |
| 613 | - | eid = rng.choice(open_exits) | |
| 614 | - | oid = rng.choice(active_ops) | |
| 615 | - | unconf_spent_exits.add(eid) | |
| 616 | - | mine_one_block([{"kind": "front_paid", "exit_id": eid, "op_id": oid}]) | |
| 617 | - | ||
| 618 | - | elif act == "front_grief": | |
| 619 | - | open_exits = [eid for eid in pending_exits if eid not in unconf_spent_exits] | |
| 620 | - | active_ops = [ | |
| 621 | - | oid for oid, op in operators.items() | |
| 622 | - | if not op["suspended"] and op["b_zbtc"] >= POLICY_B_ZBTC_CUSTODY_SLICE_SATS + POLICY_EXIT_GRIEF_SLASH_SATS | |
| 623 | - | ] | |
| 624 | - | if open_exits and active_ops: | |
| 625 | - | eid = rng.choice(open_exits) | |
| 626 | - | oid = rng.choice(active_ops) | |
| 627 | - | unconf_spent_exits.add(eid) | |
| 628 | - | mine_one_block([{"kind": "front_grief", "exit_id": eid, "op_id": oid}]) | |
| 629 | - | ||
| 630 | - | elif act == "exit_cancel": | |
| 631 | - | # Ensure some exits can reach 288-block cancel age realistically | |
| 632 | - | cur_h = current_tip_height() | |
| 633 | - | expired = [ | |
| 634 | - | eid for eid, ex in pending_exits.items() | |
| 635 | - | if eid not in unconf_spent_exits and cur_h >= ex["created_h"] + POLICY_T_EXIT_CANCEL | |
| 636 | - | ] | |
| 637 | - | if expired: | |
| 638 | - | eid = rng.choice(expired) | |
| 639 | - | unconf_spent_exits.add(eid) | |
| 640 | - | mine_one_block([{"kind": "exit_cancel", "exit_id": eid}]) | |
| 641 | - | ||
| 642 | - | elif act == "take_honest": | |
| 643 | - | free_vaults = [vid for vid in confirmed_vaults if vid not in unconf_claimed_vaults] | |
| 644 | - | eligible = [ | |
| 645 | - | (oid, vid) | |
| 646 | - | for oid, op in operators.items() | |
| 647 | - | for vid in free_vaults | |
| 648 | - | if op["credit"] - unconf_pending_credit_used[oid] >= confirmed_vaults[vid] | |
| 649 | - | ] | |
| 650 | - | if eligible: | |
| 651 | - | oid, vid = rng.choice(eligible) | |
| 652 | - | vamt = confirmed_vaults[vid] | |
| 653 | - | unconf_claimed_vaults.add(vid) | |
| 654 | - | unconf_pending_credit_used[oid] += vamt | |
| 655 | - | mine_one_block([{"kind": "take_honest", "op_id": oid, "vault_id": vid, "amount": vamt}]) | |
| 656 | - | ||
| 657 | - | elif act == "disprove_dual_slash": | |
| 658 | - | active_ops = [ | |
| 659 | - | oid for oid, op in operators.items() | |
| 660 | - | if not op["suspended"] and op["b_zbtc"] >= POLICY_B_ZBTC_CUSTODY_SLICE_SATS | |
| 661 | - | ] | |
| 662 | - | if active_ops: | |
| 663 | - | oid = rng.choice(active_ops) | |
| 664 | - | mine_one_block([{"kind": "disprove_dual_slash", "op_id": oid}]) | |
| 665 | - | ||
| 666 | - | elif act == "lamport_equivocation_slash": | |
| 667 | - | free_vaults = [vid for vid in confirmed_vaults if vid not in unconf_claimed_vaults] | |
| 668 | - | active_ops = [ | |
| 669 | - | oid for oid, op in operators.items() | |
| 670 | - | if not op["suspended"] and op["b_zbtc"] >= POLICY_MAX_VAULT_DENOM_SATS + POLICY_B_ZBTC_EQUIV_BOUNTY_SATS | |
| 671 | - | ] | |
| 672 | - | if free_vaults and active_ops: | |
| 673 | - | oid = rng.choice(active_ops) | |
| 674 | - | vid = rng.choice(free_vaults) | |
| 675 | - | unconf_claimed_vaults.add(vid) | |
| 676 | - | mine_one_block([{"kind": "lamport_equivocation_slash", "op_id": oid, "vault_id": vid}]) | |
| 677 | - | ||
| 678 | - | elif act == "topup_op": | |
| 679 | - | susp = [oid for oid, op in operators.items() if op["suspended"]] | |
| 680 | - | if susp: | |
| 681 | - | oid = rng.choice(susp) | |
| 682 | - | op = operators[oid] | |
| 683 | - | needed = max(0, POLICY_B_ZBTC_TOTAL_SATS - op["b_zbtc"]) | |
| 684 | - | if op["free_zbtc"] >= needed: | |
| 685 | - | op["free_zbtc"] -= needed | |
| 686 | - | op["b_zbtc"] += needed | |
| 687 | - | op["suspended"] = False | |
| 688 | - | counts["topup_op"] += 1 | |
| 689 | - | elif sum(confirmed_vaults.values()) + SAT <= cap_sats: | |
| 690 | - | # Operator deposits fresh BTC to replenish B_zbtc (still 1:1 backed!) | |
| 691 | - | v1, v2 = next_vault_id, next_vault_id + 1 | |
| 692 | - | next_vault_id += 2 | |
| 693 | - | confirmed_vaults[v1] = 50_000_000 | |
| 694 | - | confirmed_vaults[v2] = 50_000_000 | |
| 695 | - | op["free_zbtc"] += SAT | |
| 696 | - | op["free_zbtc"] -= needed | |
| 697 | - | op["b_zbtc"] += needed | |
| 698 | - | op["suspended"] = False | |
| 699 | - | counts["topup_op"] += 1 | |
| 700 | - | ||
| 701 | - | elif act == "mine_block": | |
| 702 | - | mine_one_block([]) | |
| 703 | - | ||
| 704 | - | elif act == "reorg": | |
| 705 | - | # GENUINE Bitcoin tip reorg of depth 1..min(K-1, len(tip_blocks))! | |
| 706 | - | # Actually pops unconfirmed blocks, discards their orphaned events, and mines empty replacement chain. | |
| 707 | - | if tip_blocks: | |
| 708 | - | depth = rng.randint(1, min(K - 1, len(tip_blocks))) | |
| 709 | - | orphaned = tip_blocks[-depth:] | |
| 710 | - | del tip_blocks[-depth:] | |
| 711 | - | ev_reverted = sum(len(b["events"]) for b in orphaned) | |
| 712 | - | counts["reorg"] += 1 | |
| 713 | - | counts["reorg_blocks_reverted"] += depth | |
| 714 | - | counts["reorg_events_reverted"] += ev_reverted | |
| 715 | - | rebuild_unconf_locks() | |
| 716 | - | for _ in range(depth): | |
| 717 | - | mine_one_block([]) | |
| 718 | - | ||
| 719 | - | assert_solvency(f"step_{step}_{act}") | |
| 720 | - | ||
| 721 | - | # Guarantee EXIT_CANCEL path is exercised if random steps didn't hit a 288-block idle exit | |
| 722 | - | if counts["exit_cancel"] == 0: | |
| 723 | - | u = next(u for u in normal_users if users[u] >= 25_000_000) if any(users[u] >= 25_000_000 for u in normal_users) else "challenger_pool" | |
| 724 | - | eid = next_exit_id | |
| 725 | - | next_exit_id += 1 | |
| 726 | - | mine_one_block([{"kind": "forced_exit", "user": u, "gross": 25_000_000, "exit_id": eid}]) | |
| 727 | - | for _ in range(K + POLICY_T_EXIT_CANCEL): | |
| 728 | - | mine_one_block([]) | |
| 729 | - | mine_one_block([{"kind": "exit_cancel", "exit_id": eid}]) | |
| 730 | - | for _ in range(K): | |
| 731 | - | mine_one_block([]) | |
| 732 | - | assert_solvency("post_exit_cancel") | |
| 733 | - | ||
| 734 | - | # Flush remaining tip blocks to K-deep finality | |
| 735 | - | for _ in range(K): | |
| 736 | - | mine_one_block([]) | |
| 737 | - | assert_solvency("final") | |
| 738 | - | return counts | |
| 739 | - | ||
| 740 | - | ||
| 741 | - | # ============================================================================== | |
| 742 | - | # MAIN ASSERTION SUITE | |
| 743 | - | # ============================================================================== | |
| 744 | - | def main() -> None: | |
| 745 | - | print("================================================================================") | |
| 746 | - | print("zBTC v1 (v3.0.0-rfc) ZERO-FEDERATION CONSISTENCY & BOUNDS CHECKER") | |
| 747 | - | print("Note: Checks internal mathematical consistency against SOURCED_, POLICY_, and") | |
| 748 | - | print(" PRE_MAINNET_TARGET_ inputs. Not an empirical Signet benchmark or audit.") | |
| 749 | - | print("================================================================================") | |
| 750 | - | ||
| 751 | - | # -------------------------------------------------------------------------- | |
| 752 | - | # 1. STAGE 0: COINBASE MIDSTATE 1- VS 2-BLOCK FINAL PADDING | |
| 753 | - | # -------------------------------------------------------------------------- | |
| 754 | - | print("\n=== 1. STAGE 0: COINBASE MIDSTATE 1-/2-BLOCK SHA-256 PADDING ===") | |
| 755 | - | one_blk_count = 0 | |
| 756 | - | two_blk_count = 0 | |
| 757 | - | for rem in range(64): | |
| 758 | - | total_len = 128 + rem # 2 full prefix blocks + remainder tail (realistic >= 128 B coinbase) | |
| 759 | - | cb_bytes = bytes((i * 37 + rem) & 0xFF for i in range(total_len)) | |
| 760 | - | # Compute real midstate over first 128 bytes | |
| 761 | - | st = _SHA256_IV | |
| 762 | - | st = sha256_compress(st, cb_bytes[0:64]) | |
| 763 | - | st = sha256_compress(st, cb_bytes[64:128]) | |
| 764 | - | midstate = struct.pack(">8I", *st) | |
| 765 | - | tail = cb_bytes[128:] | |
| 766 | - | got_txid, final_blks = complete_midstate_double_sha256(midstate, tail, total_len) | |
| 767 | - | expected_txid = hashlib.sha256(hashlib.sha256(cb_bytes).digest()).digest() | |
| 768 | - | assert got_txid == expected_txid, f"Midstate mismatch at rem={rem}" | |
| 769 | - | if rem < 56: | |
| 770 | - | assert final_blks == 1 | |
| 771 | - | one_blk_count += 1 | |
| 772 | - | else: | |
| 773 | - | assert final_blks == 2 | |
| 774 | - | two_blk_count += 1 | |
| 775 | - | assert one_blk_count == 56 and two_blk_count == 8 | |
| 776 | - | two_blk_pct = 100.0 * two_blk_count / 64.0 | |
| 777 | - | assert abs(two_blk_pct - 12.5) < 1e-9 | |
| 778 | - | # Verify CVE-2017-12842 64-byte leaf rejection | |
| 779 | - | try: | |
| 780 | - | complete_midstate_double_sha256(b"\x00" * 32, b"", 64) | |
| 781 | - | raise AssertionError("64-byte coinbase length must be rejected!") | |
| 782 | - | except AssertionError as e: | |
| 783 | - | assert "CVE-2017-12842" in str(e) | |
| 784 | - | print( | |
| 785 | - | f" Verified all 64/64 remainders against real hashlib.sha256 double-SHA256: " | |
| 786 | - | f"{one_blk_count} use 1 final block (rem 0..55), {two_blk_count} use 2 final blocks " | |
| 787 | - | f"(rem 56..63 = {two_blk_pct:.1f}% of coinbases); len==64 rejected." | |
| 788 | - | ) | |
| 789 | - | ||
| 790 | - | # -------------------------------------------------------------------------- | |
| 791 | - | # 2. STAGE 0: HONEST go-zenon THROUGHPUT, SPV ORACLE & DYNAMIC PLASMA PINNING | |
| 792 | - | # -------------------------------------------------------------------------- | |
| 793 | - | print("\n=== 2. STAGE 0: go-zenon THROUGHPUT, SPV ORACLE & DYNAMIC PLASMA PINNING ===") | |
| 794 | - | rollup_tx_plasma = ( | |
| 795 | - | SOURCED_ZNN_ACCOUNT_BLOCK_BASE_PLASMA | |
| 796 | - | + PRE_MAINNET_TARGET_ROLLUP_TX_DATA_BYTES * SOURCED_ZNN_AB_BYTE_DATA_PLASMA | |
| 797 | - | ) | |
| 798 | - | assert rollup_tx_plasma == 28_480 | |
| 799 | - | rollup_tx_qsr = ceil_div(rollup_tx_plasma, SOURCED_ZNN_PLASMA_PER_QSR) | |
| 800 | - | assert rollup_tx_qsr == 14 | |
| 801 | - | base_tx_qsr = ceil_div(SOURCED_ZNN_ACCOUNT_BLOCK_BASE_PLASMA, SOURCED_ZNN_PLASMA_PER_QSR) | |
| 802 | - | assert base_tx_qsr == 10 | |
| 803 | - | ||
| 804 | - | tps_floor = (POLICY_PINNED_MAX_BASE_PLASMA_FLOOR / SOURCED_ZNN_ACCOUNT_BLOCK_BASE_PLASMA / 2.0) / SOURCED_ZNN_OBSERVED_MOMENTUM_SECS | |
| 805 | - | tps_default = (SOURCED_ZNN_DP_DEFAULT_MAX_BASE_PLASMA / SOURCED_ZNN_ACCOUNT_BLOCK_BASE_PLASMA / 2.0) / SOURCED_ZNN_OBSERVED_MOMENTUM_SECS | |
| 806 | - | tps_naive_2p1b = (SOURCED_ZNN_DP_UPPER_MAX_BASE_PLASMA / SOURCED_ZNN_ACCOUNT_BLOCK_BASE_PLASMA / 2.0) / SOURCED_ZNN_OBSERVED_MOMENTUM_SECS | |
| 807 | - | # Real wire/protobuf ceiling governed by MaxDetailedMomentumWireSize (~8.38 MB) & MaxMomentumContentBytes (8 MiB) | |
| 808 | - | real_blocks_low = SOURCED_ZNN_MAX_DETAILED_MOMENTUM_WIRE // SOURCED_ZNN_MIN_ACCOUNT_BLOCK_WIRE_HIGH | |
| 809 | - | real_blocks_high = SOURCED_ZNN_MAX_DETAILED_MOMENTUM_WIRE // SOURCED_ZNN_MIN_ACCOUNT_BLOCK_WIRE_LOW | |
| 810 | - | real_tps_low = (real_blocks_low / 2.0) / SOURCED_ZNN_OBSERVED_MOMENTUM_SECS | |
| 811 | - | real_tps_high = (real_blocks_high / 2.0) / SOURCED_ZNN_OBSERVED_MOMENTUM_SECS | |
| 812 | - | assert 4.3 < tps_floor < 4.5 | |
| 813 | - | assert 8.7 < tps_default < 8.9 | |
| 814 | - | assert 4_385 < tps_naive_2p1b < 4_387 | |
| 815 | - | assert 1_000 < real_tps_low < 1_100 and 1_200 < real_tps_high < 1_260 | |
| 816 | - | assert real_tps_high < tps_naive_2p1b / 3.5 | |
| 817 | - | ||
| 818 | - | max_contract_blocks_floor = POLICY_PINNED_MAX_BASE_PLASMA_FLOOR // SOURCED_ZNN_EMBEDDED_SIMPLE_TIER | |
| 819 | - | assert max_contract_blocks_floor == 40 | |
| 820 | - | ||
| 821 | - | # Stage 0 Pure SPV Event Oracle calls matching spec/02 §2.2 byte-for-byte (ZERO custodial minting!): | |
| 822 | - | # - SubmitHeaderBatch(bytes headers): 4 + 32(off) + 32(len) + 160(2*80) = 228 B | |
| 823 | - | # - StepReorg(): 4 B | |
| 824 | - | # - PruneStaleHeaders(bytes hashes): 4 + 32(off) + 32(len) + 64(2*32) = 132 B | |
| 825 | - | # - ProveTxInclusion(u64 blockHeight, u32 txIndex, u32 totalCbBytes, bytes32 midstate, | |
| 826 | - | # bytes strippedTx, bytes32[] txBranch, bytes cbTail, bytes32[] cbBranch): | |
| 827 | - | # payload = 8 + 4 + 4 + 32 + 6,144 + 512 + 63 + 512 = 7,279 B | |
| 828 | - | # ABI = 4 + 8*32 + (32+6144) + (32+512) + (32+64) + (32+512) = 260 + 7,360 = 7,620 B | |
| 829 | - | prove_payload = 8 + 4 + 4 + 32 + POLICY_STAGE0_MAX_STRIPPED_TX_BYTES + 16 * 32 + 63 + 16 * 32 | |
| 830 | - | prove_abi = (4 + 8 * 32) + (32 + POLICY_STAGE0_MAX_STRIPPED_TX_BYTES) + (32 + 16 * 32) + (32 + 64) + (32 + 16 * 32) | |
| 831 | - | assert prove_payload == 7_279 and prove_abi == 7_620 | |
| 832 | - | ||
| 833 | - | stage0_calls = [ | |
| 834 | - | ("SubmitHeaderBatch(1..2 headers)", SOURCED_ZNN_EMBEDDED_SIMPLE_TIER, 160, 4 + 32 + 32 + 160, 8, 1), | |
| 835 | - | ("StepReorg()", SOURCED_ZNN_EMBEDDED_SIMPLE_TIER, 0, 4, 6, 1), | |
| 836 | - | ("PruneStaleHeaders(1..2 hashes)", SOURCED_ZNN_EMBEDDED_SIMPLE_TIER, 64, 4 + 32 + 32 + 64, 4, 1), | |
| 837 | - | ("ProveTxInclusion(<=6KiB tx + midstate)", SOURCED_ZNN_EMBEDDED_HEAVY_SPV_TIER, prove_payload, prove_abi, 8, 1), | |
| 838 | - | ] | |
| 839 | - | max_spv_plasma = 0 | |
| 840 | - | for name, tier, plen, abi_len, storage_ops, cblocks in stage0_calls: | |
| 841 | - | plasma = abi_embedded_plasma(tier, abi_len) | |
| 842 | - | qsr = ceil_div(plasma, SOURCED_ZNN_PLASMA_PER_QSR) | |
| 843 | - | max_spv_plasma = max(max_spv_plasma, plasma) | |
| 844 | - | assert abi_len <= SOURCED_ZNN_MAX_DATA_LENGTH | |
| 845 | - | assert storage_ops <= POLICY_STAGE0_MAX_STORAGE_OPS | |
| 846 | - | assert plasma <= POLICY_PINNED_MAX_BASE_PLASMA_FLOOR | |
| 847 | - | assert 3 * cblocks <= max_contract_blocks_floor | |
| 848 | - | if name.startswith("SubmitHeaderBatch"): | |
| 849 | - | assert abi_len == 228 and plasma == 67_732 and qsr == 33 | |
| 850 | - | elif name.startswith("StepReorg"): | |
| 851 | - | assert abi_len == 4 and plasma == 52_500 and qsr == 25 | |
| 852 | - | elif name.startswith("PruneStaleHeaders"): | |
| 853 | - | assert abi_len == 132 and plasma == 61_204 and qsr == 30 | |
| 854 | - | elif name.startswith("ProveTxInclusion"): | |
| 855 | - | assert abi_len == 7_620 and plasma == 591_388 and qsr == 282 | |
| 856 | - | print( | |
| 857 | - | f" Stage 0 {name:40s}: payload={plen:5d} B | ABI={abi_len:5d} B | " | |
| 858 | - | f"plasma={plasma:7,d} ({qsr:3d} QSR) | ops<={storage_ops:2d} | cblks={cblocks}" | |
| 859 | - | ) | |
| 860 | - | assert POLICY_PINNED_MAX_BASE_PLASMA_FLOOR >= 3 * max_spv_plasma | |
| 861 | - | ||
| 862 | - | # 1-block 110B rollup send throughput (no receive block needed, spec/03 §2.2) | |
| 863 | - | rollup_tps_floor = (POLICY_PINNED_MAX_BASE_PLASMA_FLOOR / rollup_tx_plasma) / SOURCED_ZNN_OBSERVED_MOMENTUM_SECS | |
| 864 | - | rollup_tps_default = (SOURCED_ZNN_DP_DEFAULT_MAX_BASE_PLASMA / rollup_tx_plasma) / SOURCED_ZNN_OBSERVED_MOMENTUM_SECS | |
| 865 | - | assert 6.3 < rollup_tps_floor < 6.6 and 12.8 < rollup_tps_default < 13.1 | |
| 866 | - | ||
| 867 | - | # Dynamic Plasma unpinned target/denominator explosion proof (spec/05 §2.2) | |
| 868 | - | price_unpinned = SOURCED_ZNN_MIN_RESOURCE_PRICE | |
| 869 | - | for _ in range(52): # ~9.9 minutes @ 11.4s/Momentum | |
| 870 | - | price_unpinned = dp_next_price( | |
| 871 | - | price_unpinned, | |
| 872 | - | used_plasma=SOURCED_ZNN_ACCOUNT_BLOCK_BASE_PLASMA, | |
| 873 | - | target_plasma=1, | |
| 874 | - | max_change_pct=POLICY_PINNED_MAX_PRICE_CHANGE_PCT, | |
| 875 | - | denom=1, | |
| 876 | - | ) | |
| 877 | - | explosion_mult = price_unpinned / SOURCED_ZNN_MIN_RESOURCE_PRICE | |
| 878 | - | assert explosion_mult > 100_000, f"Expected >100,000x unpinned explosion, got {explosion_mult:.1f}x" | |
| 879 | - | # Verify pinned targets (>=25% of 2.1M = 525,000) & denom >= 8 stay completely flat under single tx! | |
| 880 | - | price_pinned = SOURCED_ZNN_MIN_RESOURCE_PRICE | |
| 881 | - | pinned_target = (POLICY_PINNED_MAX_BASE_PLASMA_FLOOR * POLICY_PINNED_MIN_TARGET_SHARE_PCT) // 100 | |
| 882 | - | assert pinned_target == 525_000 | |
| 883 | - | for _ in range(52): | |
| 884 | - | price_pinned = dp_next_price( | |
| 885 | - | price_pinned, | |
| 886 | - | used_plasma=SOURCED_ZNN_ACCOUNT_BLOCK_BASE_PLASMA, | |
| 887 | - | target_plasma=pinned_target, | |
| 888 | - | max_change_pct=POLICY_PINNED_MAX_PRICE_CHANGE_PCT, | |
| 889 | - | denom=POLICY_PINNED_MIN_PRICE_DENOM, | |
| 890 | - | ) | |
| 891 | - | assert price_pinned == SOURCED_ZNN_MIN_RESOURCE_PRICE | |
| 892 | - | print( | |
| 893 | - | f" Plasma transfer costs: native=21,000 ({base_tx_qsr} QSR), 110B rollup tx={rollup_tx_plasma:,} ({rollup_tx_qsr} QSR) @ floor 1,000" | |
| 894 | - | ) | |
| 895 | - | print( | |
| 896 | - | f" Throughput @ {SOURCED_ZNN_OBSERVED_MOMENTUM_SECS}s/Mom: 2-blk floor(2.1M)={tps_floor:.1f} / default(4.2M)={tps_default:.1f} tx/s " | |
| 897 | - | f"| 1-blk rollup={rollup_tps_floor:.1f}/{rollup_tps_default:.1f} tx/s | REAL 8 MiB ceiling={real_tps_low:,.0f}-{real_tps_high:,.0f} tx/s (vs naive 2.1B={tps_naive_2p1b:,.0f})" | |
| 898 | - | ) | |
| 899 | - | print( | |
| 900 | - | f" Contract-block cap @ 2.1M floor={max_contract_blocks_floor} | " | |
| 901 | - | f"unpinned DP (target=1,denom=1,52 Moms) price mult={explosion_mult:,.0f}x (>100,000x) vs pinned={price_pinned//1000}x" | |
| 902 | - | ) | |
| 903 | - | ||
| 904 | - | # -------------------------------------------------------------------------- | |
| 905 | - | # 3. STAGE 0: PTLC & LN TIMELOCK SAFETY MARGINS (2.3x SLOW BLOCKS) | |
| 906 | - | # -------------------------------------------------------------------------- | |
| 907 | - | print("\n=== 3. STAGE 0: PTLC & LN TIMELOCK SAFETY MARGINS (2.3x SLOW BLOCKS) ===") | |
| 908 | - | bob_deadline_blks = POLICY_PTLC_BTC_CSV_BLOCKS - POLICY_PTLC_BOB_CONFIRM_MARGIN_BLOCKS | |
| 909 | - | assert bob_deadline_blks == 66 | |
| 910 | - | t_btc_worst_2x = round(POLICY_PTLC_BTC_CSV_BLOCKS * SOURCED_BTC_TARGET_BLOCK_SECS * SOURCED_JUNE2021_SLOW_WEEKLY_MULT) | |
| 911 | - | t_bob_confirm_2p3x = round(bob_deadline_blks * SOURCED_BTC_TARGET_BLOCK_SECS * SOURCED_JUNE2021_SLOW_DAILY_MULT) | |
| 912 | - | t_refund_2p3x = round(POLICY_PTLC_BTC_CSV_BLOCKS * SOURCED_BTC_TARGET_BLOCK_SECS * SOURCED_JUNE2021_SLOW_DAILY_MULT) | |
| 913 | - | alice_margin_2p3x_secs = POLICY_PTLC_ZNN_DURATION_SECS - t_bob_confirm_2p3x | |
| 914 | - | assert t_btc_worst_2x == 86_400 | |
| 915 | - | assert t_bob_confirm_2p3x == 91_080 # 25.3 hours | |
| 916 | - | assert t_refund_2p3x == 99_360 # 27.6 hours | |
| 917 | - | assert POLICY_PTLC_ZNN_DURATION_SECS == 108_000 # 30.0 hours (passed as now + 108_000 Unix ts) | |
| 918 | - | assert alice_margin_2p3x_secs == 16_920 # 4.7 hours > 0 | |
| 919 | - | assert 2 * POLICY_LN_DELTA_SAFETY_BLOCKS <= POLICY_PTLC_BTC_CSV_BLOCKS | |
| 920 | - | # Verify consistent Unix-second conversion for LN HTLC delta (no subtracting blocks from seconds!) | |
| 921 | - | ln_delta_secs_nominal = POLICY_LN_DELTA_SAFETY_BLOCKS * SOURCED_BTC_TARGET_BLOCK_SECS | |
| 922 | - | ln_delta_secs_2x = round(POLICY_LN_DELTA_SAFETY_BLOCKS * SOURCED_BTC_TARGET_BLOCK_SECS * SOURCED_JUNE2021_SLOW_WEEKLY_MULT) | |
| 923 | - | ln_delta_secs_2p3x = round(POLICY_LN_DELTA_SAFETY_BLOCKS * SOURCED_BTC_TARGET_BLOCK_SECS * SOURCED_JUNE2021_SLOW_DAILY_MULT) | |
| 924 | - | assert ln_delta_secs_nominal == 21_600 # 6.0h nominal (spec/03 §1.2) | |
| 925 | - | assert ln_delta_secs_2x == 43_200 # 12.0h @ 2.0x slow blocks | |
| 926 | - | assert ln_delta_secs_2p3x == 49_680 # 13.8h @ 2.3x slow blocks | |
| 927 | - | print( | |
| 928 | - | f" PTLC: CSV={POLICY_PTLC_BTC_CSV_BLOCKS} blks (Bob confirms <= h_conf+{bob_deadline_blks}) | " | |
| 929 | - | f"2.0x=24.0h | 2.3x June-2021 Bob confirm={t_bob_confirm_2p3x/3600:.1f}h < T_znn={POLICY_PTLC_ZNN_DURATION_SECS/3600:.1f}h " | |
| 930 | - | f"(Alice margin={alice_margin_2p3x_secs/3600:.1f}h; absolute Unix ts = now + 108,000)" | |
| 931 | - | ) | |
| 932 | - | ||
| 933 | - | # -------------------------------------------------------------------------- | |
| 934 | - | # 4. STAGE 1A: THEOREM 2 CAPITAL PROOF (BitVM2 vs RIGHT-SIZED BitVMX n=8) | |
| 935 | - | # -------------------------------------------------------------------------- | |
| 936 | - | print("\n=== 4. STAGE 1A: THEOREM 2 CAPITAL PROOF (BitVM2 vs RIGHT-SIZED BitVMX) ===") | |
| 937 | - | bitvm2_m3_low = 3 * PRE_MAINNET_TARGET_BITVM2_LANE_BOND_BTC_LOW | |
| 938 | - | bitvm2_m3_high = 3 * PRE_MAINNET_TARGET_BITVM2_LANE_BOND_BTC_HIGH | |
| 939 | - | bitvm2_m5_low = 5 * PRE_MAINNET_TARGET_BITVM2_LANE_BOND_BTC_LOW | |
| 940 | - | bitvm2_m5_high = 5 * PRE_MAINNET_TARGET_BITVM2_LANE_BOND_BTC_HIGH | |
| 941 | - | assert abs(bitvm2_m3_low - 39.90) < 1e-6 and abs(bitvm2_m5_high - 90.875) < 1e-6 | |
| 942 | - | assert bitvm2_m3_low > SOURCED_ZNN_MCAP_BTC_HIGH, "BitVM2 minimal M=3 exceeds 100% of ZNN mcap!" | |
| 943 | - | ||
| 944 | - | assert POLICY_LANE_TOTAL_BOND_SATS == 260_000_000 # 2.60 BTC/lane | |
| 945 | - | verifier_standby_btc = (POLICY_BITVMX_N_VERIFIERS * POLICY_F_CHAL_SATS) / SAT | |
| 946 | - | assert abs(verifier_standby_btc - 2.80) < 1e-9 | |
| 947 | - | for label, prof in POLICY_STAGE1A_PROFILES.items(): | |
| 948 | - | m = prof["M"] | |
| 949 | - | bonds_btc = (m * POLICY_BITVMX_L_LANES * POLICY_LANE_TOTAL_BOND_SATS) / SAT | |
| 950 | - | total_btc = bonds_btc + prof["float_btc"] + verifier_standby_btc | |
| 951 | - | pct_low = 100.0 * total_btc / SOURCED_ZNN_MCAP_BTC_HIGH | |
| 952 | - | pct_high = 100.0 * total_btc / SOURCED_ZNN_MCAP_BTC_LOW | |
| 953 | - | if m == 3: | |
| 954 | - | assert abs(bonds_btc - 7.80) < 1e-9 and abs(total_btc - 12.80) < 1e-9 | |
| 955 | - | if m == 5: | |
| 956 | - | assert abs(bonds_btc - 13.00) < 1e-9 and abs(total_btc - 18.80) < 1e-9 | |
| 957 | - | assert total_btc < bitvm2_m3_low | |
| 958 | - | print( | |
| 959 | - | f" BitVMX {label:18s}: bonds={bonds_btc:5.2f} + float={prof['float_btc']:4.2f} + " | |
| 960 | - | f"verifiers={verifier_standby_btc:4.2f} = {total_btc:5.2f} BTC ({pct_low:.1f}%-{pct_high:.1f}% of 25-33 BTC ZNN mcap)" | |
| 961 | - | ) | |
| 962 | - | print( | |
| 963 | - | f" BitVM2 contrast (M=3..5, L=1, bonds only): {bitvm2_m3_low:.2f}-{bitvm2_m5_high:.3f} BTC " | |
| 964 | - | f"(>100%-275%+ of ZNN mcap before fronting float!)" | |
| 965 | - | ) | |
| 966 | - | ||
| 967 | - | # -------------------------------------------------------------------------- | |
| 968 | - | # 5. STAGE 1A: BitVMX n=8 BISECTION & 100% BIP-431 TRUC v3 COMPLIANCE | |
| 969 | - | # -------------------------------------------------------------------------- | |
| 970 | - | print("\n=== 5. STAGE 1A: BitVMX-CPU n=8 BISECTION & BIP-431 TRUC v3 COMPLIANCE ===") | |
| 971 | - | interm_hashes_per_tx = POLICY_BITVMX_N_BRANCH - 1 # 7 intermediate 20B OP_HASH160 hashes | |
| 972 | - | data_digits_per_hash = 160 // 4 # 40 base-16 nibbles | |
| 973 | - | max_checksum = data_digits_per_hash * 15 # 600 <= 16^3 - 1 = 4,095 -> 3 checksum digits | |
| 974 | - | assert max_checksum <= 16**3 - 1 | |
| 975 | - | digits_per_hash = data_digits_per_hash + 3 # 43 digits | |
| 976 | - | digits_per_prover_tx = interm_hashes_per_tx * digits_per_hash | |
| 977 | - | assert digits_per_prover_tx == 301 | |
| 978 | - | prover_wots_wu = math.ceil(digits_per_prover_tx * PRE_MAINNET_TARGET_WOTS_DIGIT_WU) | |
| 979 | - | assert prover_wots_wu == 28_746 | |
| 980 | - | prover_wots_vb = prover_wots_wu / 4.0 | |
| 981 | - | assert abs(prover_wots_vb - 7_186.5) < 1e-9 | |
| 982 | - | prover_step_vb = prover_wots_vb + PRE_MAINNET_TARGET_BISECTION_OVERHEAD_VB | |
| 983 | - | assert abs(prover_step_vb - 7_436.5) < 1e-9 | |
| 984 | - | assert prover_step_vb <= SOURCED_BIP431_TRUC_MAX_VB, "n=8 prover bisection tx must fit TRUC v3!" | |
| 985 | - | ||
| 986 | - | # Verify why rejected n=16 failed TRUC v3: | |
| 987 | - | n16_wots_vb = math.ceil(15 * digits_per_hash * PRE_MAINNET_TARGET_WOTS_DIGIT_WU) / 4.0 + PRE_MAINNET_TARGET_BISECTION_OVERHEAD_VB | |
| 988 | - | assert n16_wots_vb > SOURCED_BIP431_TRUC_MAX_VB | |
| 989 | - | ||
| 990 | - | instructions_covered = POLICY_BITVMX_N_BRANCH ** POLICY_BITVMX_SEARCH_ROUNDS | |
| 991 | - | assert instructions_covered == 2**27 == 134_217_728 | |
| 992 | - | seq_steps = 1 + POLICY_BITVMX_SEARCH_ROUNDS + POLICY_BITVMX_SEARCH_ROUNDS + 1 | |
| 993 | - | assert seq_steps == 20 | |
| 994 | - | ||
| 995 | - | prover_total_vb = ( | |
| 996 | - | POLICY_BITVMX_SEARCH_ROUNDS * prover_step_vb | |
| 997 | - | + PRE_MAINNET_TARGET_START_TX_VB | |
| 998 | - | + PRE_MAINNET_TARGET_FINAL_TRACE_TX_VB | |
| 999 | - | ) | |
| 1000 | - | verifier_total_vb = ( | |
| 1001 | - | PRE_MAINNET_TARGET_CHALLENGE_TX_VB | |
| 1002 | - | + POLICY_BITVMX_SEARCH_ROUNDS * PRE_MAINNET_TARGET_VERIFIER_CHOICE_VB | |
| 1003 | - | + PRE_MAINNET_TARGET_EXECUTE_OPCODE_VB | |
| 1004 | - | ) | |
| 1005 | - | assert prover_total_vb <= PRE_MAINNET_TARGET_PROVER_CONSERVATIVE_VB | |
| 1006 | - | assert verifier_total_vb <= PRE_MAINNET_TARGET_VERIFIER_CONSERVATIVE_VB | |
| 1007 | - | ||
| 1008 | - | prover_fee_500 = PRE_MAINNET_TARGET_PROVER_CONSERVATIVE_VB * POLICY_DESIGN_SUSTAINED_FEE_SATVB | |
| 1009 | - | verifier_fee_500 = PRE_MAINNET_TARGET_VERIFIER_CONSERVATIVE_VB * POLICY_DESIGN_SUSTAINED_FEE_SATVB | |
| 1010 | - | prover_breakeven_satvb = POLICY_F_CHAL_SATS // PRE_MAINNET_TARGET_PROVER_CONSERVATIVE_VB | |
| 1011 | - | assert prover_fee_500 == 37_500_000 <= POLICY_F_CHAL_SATS | |
| 1012 | - | assert verifier_fee_500 == 7_500_000 | |
| 1013 | - | assert prover_breakeven_satvb == 533 | |
| 1014 | - | print( | |
| 1015 | - | f" n=8 bisection: {interm_hashes_per_tx} hashes x {digits_per_hash} digits = {digits_per_prover_tx} digits = " | |
| 1016 | - | f"{prover_wots_wu:,} WU ({prover_wots_vb:,.1f} vB) + 250 = {prover_step_vb:,.1f} vB <= 10,000 vB TRUC v3 " | |
| 1017 | - | f"(rejected n=16 = {n16_wots_vb:,.0f} vB > 10,000 vB)" | |
| 1018 | - | ) | |
| 1019 | - | print( | |
| 1020 | - | f" 9 rounds -> 8^9 = 2^27 = {instructions_covered:,} RV32IM ops | {seq_steps} sequential steps | " | |
| 1021 | - | f"Prover={prover_total_vb:,.1f} vB (~75 kvB; {prover_fee_500/SAT:.3f} BTC <= F_chal=0.40 BTC @ 500 sat/vB, " | |
| 1022 | - | f"break-even={prover_breakeven_satvb} sat/vB) | Verifier={verifier_total_vb:,.0f} vB (cap 15 kvB; 0.075 BTC @ 500 sat/vB)" | |
| 1023 | - | ) | |
| 1024 | - | ||
| 1025 | - | # -------------------------------------------------------------------------- | |
| 1026 | - | # 6. STAGE 1A: SIMULTANEOUS TIMELOCKS & 256-BIT LAMPORT TakeTx BOUNDS | |
| 1027 | - | # -------------------------------------------------------------------------- | |
| 1028 | - | print("\n=== 6. STAGE 1A: TIMELOCK ORDERING & 256-BIT LAMPORT TakeTx BIP-342/TRUC BOUNDS ===") | |
| 1029 | - | max_dispute_end = POLICY_T_CHAL_WINDOW + seq_steps * POLICY_T_STEP | |
| 1030 | - | assert max_dispute_end == 1_104 | |
| 1031 | - | assert POLICY_T_CHAL_WINDOW < max_dispute_end < POLICY_T_TAKE < POLICY_T_COOLDOWN < POLICY_T_RETIRE | |
| 1032 | - | assert POLICY_T_COOLDOWN - POLICY_T_TAKE == 144 # 24h Lamport equivocation slash window | |
| 1033 | - | assert PRE_MAINNET_TARGET_DEPOSIT_CERTBLOB_BYTES == 104 <= SOURCED_BIP342_MAX_PUSH_BYTES | |
| 1034 | - | ||
| 1035 | - | # Exact 256-bit Lamport L_{j,l,r} Tapscript leaf: | |
| 1036 | - | # 256 x (OP_HASH160 [1B] + PUSH20 [1B] + 20B hash + OP_EQUALVERIFY [1B]) + PUSH32 [1B] + 32B Q_setup + OP_CHECKSIG [1B] | |
| 1037 | - | lamport_script_bytes = 256 * (1 + 1 + 20 + 1) + (1 + 32 + 1) | |
| 1038 | - | assert lamport_script_bytes == 5_922 | |
| 1039 | - | lamport_preimages_bytes = 256 * (1 + 20) # 256 x (len=0x14 + 20B preimage) | |
| 1040 | - | assert lamport_preimages_bytes == 5_376 | |
| 1041 | - | # Control blocks: Stage 1A (M=5, R=64 -> 320 leaves -> depth 9) & Stage 2 (40 lanes * 64 -> 2,560 leaves -> depth 12) | |
| 1042 | - | leaves_stage1a = POLICY_BITVMX_M_MAX * POLICY_BITVMX_L_LANES * POLICY_BITVMX_R_ROUNDS | |
| 1043 | - | leaves_stage2 = POLICY_STAGE2_TOTAL_LANES * POLICY_BITVMX_R_ROUNDS | |
| 1044 | - | depth_stage1a = math.ceil(math.log2(leaves_stage1a)) | |
| 1045 | - | depth_stage2 = math.ceil(math.log2(leaves_stage2)) | |
| 1046 | - | assert leaves_stage1a == 320 and depth_stage1a == 9 | |
| 1047 | - | assert leaves_stage2 == 2_560 and depth_stage2 == 12 | |
| 1048 | - | cb_stage1a = 1 + 32 + 32 * depth_stage1a | |
| 1049 | - | cb_stage2 = 1 + 32 + 32 * depth_stage2 | |
| 1050 | - | assert cb_stage1a == 321 and cb_stage2 == 417 | |
| 1051 | - | # Peak stack: 256 preimages + 1 Schnorr sig + 1 pushed 20B hash during OP_HASH160 <H> OP_EQUALVERIFY | |
| 1052 | - | lamport_peak_stack = 256 + 1 + 1 | |
| 1053 | - | assert lamport_peak_stack == 258 < SOURCED_BIP342_MAX_STACK_ITEMS | |
| 1054 | - | # Total TakeTx weight (2 inputs: U_d Lamport leaf + VaultConnector_r CSV leaf; 2 outputs: P2TR + P2A) | |
| 1055 | - | take_non_witness = 10 + 2 * 41 + 43 + 13 # 148 B -> 592 WU | |
| 1056 | - | take_wit_ud_s2 = ( | |
| 1057 | - | compact_size_len(259) | |
| 1058 | - | + (1 + 64) | |
| 1059 | - | + lamport_preimages_bytes | |
| 1060 | - | + compact_size_len(lamport_script_bytes) + lamport_script_bytes | |
| 1061 | - | + compact_size_len(cb_stage2) + cb_stage2 | |
| 1062 | - | ) | |
| 1063 | - | take_wit_connector = 110 # Conservative VaultConnector_r CSV tapscript witness | |
| 1064 | - | take_total_wu = take_non_witness * 4 + take_wit_ud_s2 + take_wit_connector | |
| 1065 | - | take_total_vb = take_total_wu / 4.0 | |
| 1066 | - | assert take_total_vb <= 3_200 <= SOURCED_BIP431_TRUC_MAX_VB | |
| 1067 | - | print( | |
| 1068 | - | f" Timelocks: chal=[0,{POLICY_T_CHAL_WINDOW}] | max_dispute={max_dispute_end} < T_take={POLICY_T_TAKE} " | |
| 1069 | - | f"< T_cooldown={POLICY_T_COOLDOWN} < Retire={POLICY_T_RETIRE} (144-blk equivocation margin)" | |
| 1070 | - | ) | |
| 1071 | - | print( | |
| 1072 | - | f" Lamport TakeTx: script={lamport_script_bytes:,} B | preimages={lamport_preimages_bytes:,} B | " | |
| 1073 | - | f"CB(depth 9/12)={cb_stage1a}/{cb_stage2} B | peak_stack={lamport_peak_stack} (<1,000) | " | |
| 1074 | - | f"TakeTx={take_total_vb:,.1f} vB (<=3,200 <=10,000 TRUC v3)" | |
| 1075 | - | ) | |
| 1076 | - | ||
| 1077 | - | # -------------------------------------------------------------------------- | |
| 1078 | - | # 7. STAGE 1A: COLLUDING-VERIFIER POSITIVE-EV MATRIX (k_collude = 0..6 of N=7) | |
| 1079 | - | # -------------------------------------------------------------------------- | |
| 1080 | - | print("\n=== 7. STAGE 1A: COLLUDING-VERIFIER POSITIVE-EV MATRIX (N=7, k_collude=0..6) ===") | |
| 1081 | - | assert POLICY_WINNING_VERIFIER_L1_SATS + POLICY_BURNED_BOND_SATS == POLICY_BOND_BTC_SATS | |
| 1082 | - | other_challenger_share = POLICY_B_ZBTC_CUSTODY_SLICE_SATS // (POLICY_BITVMX_N_VERIFIERS - 1) | |
| 1083 | - | assert other_challenger_share == 9_166_666 # 0.09166666 BTC | |
| 1084 | - | honest_min_net_ev = other_challenger_share - verifier_fee_500 | |
| 1085 | - | assert honest_min_net_ev == 1_666_666 > 0 # +0.01666666 BTC (> +0.0167 rounded) | |
| 1086 | - | ||
| 1087 | - | for k_collude in range(POLICY_BITVMX_N_VERIFIERS): | |
| 1088 | - | honest_count = POLICY_BITVMX_N_VERIFIERS - k_collude | |
| 1089 | - | assert honest_count >= 1 | |
| 1090 | - | vault_stolen = 0 # Dual-input Disprove/TimeoutSlash spends Stake_r AND VaultConnector_r! | |
| 1091 | - | # Worst case for protocol: colluding verifier captures 0.15 BTC L1 win (when k_collude >= 1) | |
| 1092 | - | # AND (k_collude - 1) other colluders each capture 1/6 of 0.55 BTC B_zbtc slice! | |
| 1093 | - | colluder_l1_recapture = POLICY_WINNING_VERIFIER_L1_SATS if k_collude >= 1 else 0 | |
| 1094 | - | colluder_zbtc_recapture = max(0, k_collude - 1) * other_challenger_share | |
| 1095 | - | # Upper-bound attacker P&L (even ignoring attacker's own L1 fees): | |
| 1096 | - | colluder_pnl = ( | |
| 1097 | - | vault_stolen | |
| 1098 | - | - POLICY_BOND_BTC_SATS | |
| 1099 | - | - POLICY_B_ZBTC_CUSTODY_SLICE_SATS | |
| 1100 | - | + colluder_l1_recapture | |
| 1101 | - | + colluder_zbtc_recapture | |
| 1102 | - | ) | |
| 1103 | - | assert colluder_pnl < 0 | |
| 1104 | - | if k_collude == 0: | |
| 1105 | - | assert colluder_pnl == -255_000_000 # -2.55 BTC (O_j alone) | |
| 1106 | - | if k_collude == 1: | |
| 1107 | - | assert colluder_pnl == -240_000_000 # -2.40 BTC (O_j + colluding V_1) | |
| 1108 | - | if k_collude == 6: | |
| 1109 | - | assert colluder_pnl == -194_166_670 # -1.9417 BTC (O_j + 6 of 7 verifiers!) | |
| 1110 | - | print( | |
| 1111 | - | f" k_collude={k_collude} (honest={honest_count}): vault_stolen=0 | " | |
| 1112 | - | f"honest_EV>={honest_min_net_ev/SAT:+.4f} BTC (@500 sat/vB) | " | |
| 1113 | - | f"combined_attacker_PnL={colluder_pnl/SAT:+.4f} BTC" | |
| 1114 | - | ) | |
| 1115 | - | ||
| 1116 | - | # -------------------------------------------------------------------------- | |
| 1117 | - | # 8. STAGE 1A: MULTI-TIER VAULTS {0.50, 0.25, 0.25} & 100% BANK-RUN MATH | |
| 1118 | - | # -------------------------------------------------------------------------- | |
| 1119 | - | print("\n=== 8. STAGE 1A: MULTI-TIER VAULTS & 100% BANK-RUN EXIT DURATION ===") | |
| 1120 | - | cooldown_days = POLICY_T_COOLDOWN / SOURCED_BTC_BLOCKS_PER_DAY | |
| 1121 | - | assert abs(cooldown_days - 9.0) < 1e-9 | |
| 1122 | - | avg_vault_multi_btc = (sum(POLICY_VAULT_TIERS_SATS) / len(POLICY_VAULT_TIERS_SATS)) / SAT | |
| 1123 | - | avg_vault_half_btc = (sum(POLICY_VAULT_ALT_SPLIT_SATS) / len(POLICY_VAULT_ALT_SPLIT_SATS)) / SAT | |
| 1124 | - | assert abs(avg_vault_multi_btc - (1.0 / 3.0)) < 1e-9 | |
| 1125 | - | assert abs(avg_vault_half_btc - 0.50) < 1e-9 | |
| 1126 | - | ||
| 1127 | - | for label, prof in POLICY_STAGE1A_PROFILES.items(): | |
| 1128 | - | m = prof["M"] | |
| 1129 | - | cap_btc = prof["cap_btc"] | |
| 1130 | - | float_btc = prof["float_btc"] | |
| 1131 | - | vaults_per_day = (m * POLICY_BITVMX_L_LANES) / cooldown_days | |
| 1132 | - | btc_per_day_multi = vaults_per_day * avg_vault_multi_btc | |
| 1133 | - | btc_per_day_half = vaults_per_day * avg_vault_half_btc | |
| 1134 | - | # Discrete vault batches remaining after immediate fronting float: | |
| 1135 | - | total_vaults_multi = int(round(cap_btc / avg_vault_multi_btc)) | |
| 1136 | - | fronted_vaults_multi = int(float_btc // avg_vault_multi_btc) | |
| 1137 | - | rem_vaults_multi = total_vaults_multi - fronted_vaults_multi | |
| 1138 | - | bank_run_days_multi = math.ceil(rem_vaults_multi / m) * cooldown_days | |
| 1139 | - | bank_run_days_multi_cont = (cap_btc - float_btc) / btc_per_day_multi | |
| 1140 | - | bank_run_days_half_cont = (cap_btc - float_btc) / btc_per_day_half | |
| 1141 | - | if m == 3: | |
| 1142 | - | assert abs(vaults_per_day - 1.0 / 3.0) < 1e-9 | |
| 1143 | - | assert abs(btc_per_day_multi - 1.0 / 9.0) < 1e-9 | |
| 1144 | - | assert 70.0 <= bank_run_days_multi_cont <= 72.0 and bank_run_days_multi == 72.0 | |
| 1145 | - | assert 46.0 <= bank_run_days_half_cont <= 48.0 | |
| 1146 | - | if m == 5: | |
| 1147 | - | assert abs(vaults_per_day - 5.0 / 9.0) < 1e-9 | |
| 1148 | - | assert abs(btc_per_day_multi - 5.0 / 27.0) < 1e-9 | |
| 1149 | - | assert 64.0 <= bank_run_days_multi_cont <= 66.0 | |
| 1150 | - | assert 42.5 <= bank_run_days_half_cont <= 44.0 | |
| 1151 | - | print( | |
| 1152 | - | f" {label:18s}: {vaults_per_day:.3f} vaults/d ({btc_per_day_multi:.3f} BTC/d @ avg 0.333 BTC) | " | |
| 1153 | - | f"100% bank run = ~{bank_run_days_multi_cont:.1f}d (batch={bank_run_days_multi:.0f}d) " | |
| 1154 | - | f"[~{bank_run_days_half_cont:.1f}d w/ {{0.50,0.50}}]" | |
| 1155 | - | ) | |
| 1156 | - | ||
| 1157 | - | # Finite-round admission cap (spec/01 §6): N_live_vaults <= 0.50 * RemainingTotalRounds | |
| 1158 | - | max_live_vaults_m5 = (POLICY_BITVMX_M_MAX * POLICY_BITVMX_L_LANES * POLICY_BITVMX_R_ROUNDS) // 2 | |
| 1159 | - | assert max_live_vaults_m5 == 160 and max_live_vaults_m5 * avg_vault_multi_btc > 15.0 | |
| 1160 | - | ||
| 1161 | - | # -------------------------------------------------------------------------- | |
| 1162 | - | # 9. HALVING-INDEXED TVL-SCALED K PRIVATE-FORK INEQUALITY | |
| 1163 | - | # -------------------------------------------------------------------------- | |
| 1164 | - | print("\n=== 9. HALVING-INDEXED TVL-SCALED K PRIVATE-FORK INEQUALITY (0.50*K*Sub > Cap) ===") | |
| 1165 | - | for cap_btc in POLICY_TVL_TIERS_BTC: | |
| 1166 | - | k_cfg = POLICY_CONFIGURED_K_2024[cap_btc] | |
| 1167 | - | assert 0.50 * k_cfg * SOURCED_BTC_SUBSIDY_BY_ERA["2024-2028"] > cap_btc | |
| 1168 | - | row_parts = [] | |
| 1169 | - | for era, sub in SOURCED_BTC_SUBSIDY_BY_ERA.items(): | |
| 1170 | - | k_min = int(math.floor((2.0 * cap_btc) / sub)) + 1 | |
| 1171 | - | assert 0.50 * k_min * sub > cap_btc | |
| 1172 | - | assert 0.50 * (k_min - 1) * sub <= cap_btc + 1e-12 | |
| 1173 | - | if era in POLICY_CONFIGURED_K_BY_ERA: | |
| 1174 | - | k_era_cfg = POLICY_CONFIGURED_K_BY_ERA[era][cap_btc] | |
| 1175 | - | assert k_era_cfg >= k_min and 0.50 * k_era_cfg * sub > cap_btc | |
| 1176 | - | row_parts.append(f"{era}:K>={k_min}") | |
| 1177 | - | print(f" Cap={cap_btc:3d} BTC (2024 cfg K={k_cfg:3d}): " + " | ".join(row_parts)) | |
| 1178 | - | ||
| 1179 | - | # -------------------------------------------------------------------------- | |
| 1180 | - | # 10. STAGE 1B (clArk) ALTERNATIVE GATE: LIQUIDITY & log2(N) EXIT WEIGHTS | |
| 1181 | - | # -------------------------------------------------------------------------- | |
| 1182 | - | print("\n=== 10. STAGE 1B (clArk) ALTERNATIVE GATE: LIQUIDITY & log2(N) BRANCH EXIT WEIGHTS ===") | |
| 1183 | - | clark_liq_low, clark_liq_high = PRE_MAINNET_TARGET_CLARK_ACTIVE_LIQ_BTC | |
| 1184 | - | assert clark_liq_low == 2.0 and clark_liq_high == 5.0 | |
| 1185 | - | assert clark_liq_high < 12.80 # Strictly below Stage 1A BitVMX M=3 capital floor | |
| 1186 | - | # Exact BIP-341 P2TR internal branch tx: 10.5 (hdr) + 57.5 (P2TR keypath in) + 2*43 (2 P2TR outs) + 13 (P2A) = 167 vB | |
| 1187 | - | clark_branch_tx_vb = 167.0 | |
| 1188 | - | clark_leaf_tx_vb = 154.0 | |
| 1189 | - | for n_vtxo in PRE_MAINNET_TARGET_CLARK_VTXO_COUNTS: | |
| 1190 | - | depth = int(math.log2(n_vtxo)) | |
| 1191 | - | assert 2**depth == n_vtxo | |
| 1192 | - | total_exit_vb = depth * clark_branch_tx_vb + clark_leaf_tx_vb | |
| 1193 | - | fee_100 = int(total_exit_vb * 100) | |
| 1194 | - | fee_500 = int(total_exit_vb * 500) | |
| 1195 | - | assert total_exit_vb < SOURCED_BIP431_TRUC_MAX_VB | |
| 1196 | - | print( | |
| 1197 | - | f" N={n_vtxo:4d} VTXOs (depth={depth:2d}): unilateral branch exit={total_exit_vb:6.0f} vB | " | |
| 1198 | - | f"@100 sat/vB={fee_100:,} sats | @500 sat/vB={fee_500:,} sats ({fee_500/SAT:.5f} BTC)" | |
| 1199 | - | ) | |
| 1200 | - | print(f" Active ASP liquidity turnover range: {clark_liq_low:.1f}-{clark_liq_high:.1f} BTC (0 operator bonds; expiring VTXOs)") | |
| 1201 | - | ||
| 1202 | - | # -------------------------------------------------------------------------- | |
| 1203 | - | # 11. REAL 2,000-STEP RANDOMIZED STAGE 1A SOLVENCY SIMULATION (ZERO NO-OPS!) | |
| 1204 | - | # -------------------------------------------------------------------------- | |
| 1205 | - | print("\n=== 11. REAL 2,000-STEP STAGE 1A SOLVENCY SIMULATION (WITH GENUINE REORGS) ===") | |
| 1206 | - | counts = run_stage1a_solvency_sim(seed=20261128, steps=2_000) | |
| 1207 | - | for k, v in counts.items(): | |
| 1208 | - | assert v > 0, f"Event type {k} was never exercised: {counts}" | |
| 1209 | - | assert counts["reorg_blocks_reverted"] >= counts["reorg"] > 0 | |
| 1210 | - | assert counts["reorg_events_reverted"] > 0 | |
| 1211 | - | summary = ", ".join(f"{k}={v}" for k, v in counts.items()) | |
| 1212 | - | print(f" Bob (1->0.5->exit 0.5) & Mike (1+1->2->exit 0.25) + 2,000 adversarial steps PASSED 1:1 solvency:") | |
| 1213 | - | print(f" {summary}") | |
| 1214 | - | print("\nALL v1 (v3.0.0-rfc ZERO-FEDERATION) CONSISTENCY, WEIGHT, PLASMA, TIMELOCK & SOLVENCY CHECKS PASSED.") | |
| 4 | + | v2 (v3.1.0-rfc — Zero-Federation Phased Architecture, R8 Hardened: | |
| 5 | + | Stage 0 Verify Bitcoin SPV Oracle + Erlang-Hardened PTLC/LN | |
| 6 | + | -> Stage 1A Right-Sized BitVMX (n=8, M=3..5, N=7, Core >= 29.0) + Sovereign ZK Rollup | |
| 7 | + | | Stage 1B clArk Alternative Gate | |
| 8 | + | -> Stage 2 Zero-TTP Scale & Upgrade). | |
| 9 | + | ||
| 10 | + | SCOPE & HONESTY DISCLOSURE: | |
| 11 | + | This script checks internal mathematical consistency using pure Python 3 stdlib ONLY: | |
| 12 | + | 1. Stage 0 coinbase midstate 1-/2-block SHA-256 final padding across all 64 remainders + >= 65 B filter (R8-M06) | |
| 13 | + | 2. Stage 0 honest go-zenon Plasma/wire ceilings, Dynamic Plasma 5-param pinning, & Bitcoin L1 0x02 DA cap (R8-M08) | |
| 14 | + | 3. Stage 0 exact Erlang/Poisson survival tails for PTLC (>= 48h) & LN HTLC (>= 24h) under 2.3x slowdown (R8-H07) | |
| 15 | + | 4. Proposition 2 complete hard-BTC capital accounting: locked vs operational baseline vs multi-dispute headroom (R8-M09) | |
| 16 | + | 5. Stage 1A BitVMX-CPU n=8 W-OTS + 10x153 vB P2A CPFP & Core >= 29.0 BIP-431 TRUC v3 compliance (R8-H04/H05) | |
| 17 | + | 6. Stage 1A widened timelocks (T_step=72 -> 1,584 < 1,728 < 1,872 < 2,016) & acyclic vault_id Lamport TakeTx (R8-C01) | |
| 18 | + | 7. Stage 1A native-L1 Stake_r ChalPayoutEscrow verifier EV @ 500 & 750 sat/vB, 16.53 kvB, lockup, 30% zBTC discount (R8-H02/N05) | |
| 19 | + | 8. Stage 1A exact 2^M Hall's Marriage Theorem checker + counterexample regression & cyclic (H(exitId)+r) mod M (R8-C04/M03) | |
| 20 | + | 9. Stage 1A multi-tier {0.50, 0.25, 0.25} bank-run exit bounds (T_cooldown=13.0d) & TransferCredit consolidation (R8-M04) | |
| 21 | + | 10. Stage 1A K >= 18 unpublished-fork heuristic (Cap_user + M*B_zbtc) & Budish winning-fork flow-cost sensitivity (R8-H03) | |
| 22 | + | 11. Stage 1B clArk active liquidity & log2(N) branch exit weights | |
| 23 | + | 12. Non-no-op randomized state-machine simulation separating fifo_assign & take_confirmed across T_take with explicit | |
| 24 | + | AssignedObligations (A) conservation (V_unassigned + V_assigned == C + L + E + R + A + B), AdmissionTicketUTXO cap | |
| 25 | + | mutual exclusion, k=20 single-block ExitSlotUTXO grief burst, TransferCredit, real Bitcoin reorgs, and slashes | |
| 26 | + | (R8-C02, R8-C03, R8-H01, R8-N05, R8-M04). | |
| 27 | + | ||
| 28 | + | Every modeled constant is explicitly prefixed by provenance: | |
| 29 | + | - SOURCED_ : Bitcoin BIPs, historical chain telemetry, or go-zenon origin/dev | |
| 30 | + | - POLICY_ : Explicit protocol design parameters | |
| 31 | + | - PRE_MAINNET_TARGET_ : BitVMX-CPU / rollup sizing targets to be empirically measured on Signet (Gates G1-G5) | |
| 32 | + | ||
| 33 | + | This script is a consistency & bounds checker — NOT an empirical Signet benchmark | |
| 34 | + | and NOT a substitute for independent cryptographic/implementation audits. | |
| 35 | + | ||
| 36 | + | Run: `python3 -I scripts/verify_spec_bounds.py` | |
| 37 | + | """ | |
| 38 | + | import hashlib | |
| 39 | + | import math | |
| 40 | + | import random | |
| 41 | + | import struct | |
| 42 | + | ||
| 43 | + | SAT = 100_000_000 | |
| 44 | + | ||
| 45 | + | # ============================================================================== | |
| 46 | + | # SOURCED CONSTANTS (Bitcoin BIPs, Historical Telemetry, go-zenon origin/dev) | |
| 47 | + | # ============================================================================== | |
| 48 | + | SOURCED_BIP431_TRUC_MAX_VB = 10_000 # BIP-431 TRUC v3 parent max vBytes | |
| 49 | + | SOURCED_BIP431_TRUC_CHILD_MAX_VB = 1_000 # BIP-431 TRUC v3 child max vBytes | |
| 50 | + | SOURCED_BTC_CORE_MIN_VERSION_P2A_ZERO = "29.0" # Core >= 29.0 required for 0-sat P2A ephemeral dust (R8-M09) | |
| 51 | + | SOURCED_BIP342_MAX_STACK_ITEMS = 1_000 # BIP-342 Tapscript max stack elements | |
| 52 | + | SOURCED_BIP342_MAX_PUSH_BYTES = 520 # BIP-342 Tapscript max push element size | |
| 53 | + | SOURCED_BIP141_MAX_STRIPPED_BLOCK_BYTES = 1_000_000 # Bitcoin consensus max non-witness block bytes | |
| 54 | + | SOURCED_BTC_MAX_BLOCK_WEIGHT = 4_000_000 # Bitcoin consensus 4 MWU = 1,000,000 vB/block | |
| 55 | + | SOURCED_BTC_TARGET_BLOCK_SECS = 600 # 10 min nominal Bitcoin block interval | |
| 56 | + | SOURCED_BTC_BLOCKS_PER_DAY = 144 # Nominal blocks/day | |
| 57 | + | SOURCED_JUNE2021_SLOW_WEEKLY_MULT = 2.0 # June 2021 China ban: ~1.95-2.0x 7d avg | |
| 58 | + | SOURCED_JUNE2021_SLOW_DAILY_MULT = 2.3 # June 2021 China ban: ~23 min/blk daily peak | |
| 59 | + | SOURCED_APR2024_MEDIAN_FEE_SATVB = 1_805 # April 2024 halving/Runes median peak | |
| 60 | + | SOURCED_P2A_CPFP_CHILD_VB = 153 # Standard 1-in-P2TR + 1-in-P2A -> 1-out-P2TR CPFP child (vB) | |
| 61 | + | ||
| 62 | + | # Bitcoin block subsidy schedule (BTC/block) across halvings | |
| 63 | + | SOURCED_BTC_SUBSIDY_BY_ERA = { | |
| 64 | + | "2024-2028": 3.125, | |
| 65 | + | "2028-2032": 1.5625, | |
| 66 | + | "2032-2036": 0.78125, | |
| 67 | + | "2036-2040": 0.390625, | |
| 68 | + | } | |
| 69 | + | ||
| 70 | + | # ZNN market-cap context (Nov 2026 observed range; 0% ZNN in BTC custody safety!) | |
| 71 | + | SOURCED_ZNN_MCAP_BTC_LOW = 25.0 | |
| 72 | + | SOURCED_ZNN_MCAP_BTC_HIGH = 33.0 | |
| 73 | + | ||
| 74 | + | # go-zenon origin/dev protocol constants | |
| 75 | + | SOURCED_ZNN_MAX_DATA_LENGTH = 16_384 # dev:vm/constants/plasma.go:67 | |
| 76 | + | SOURCED_ZNN_ACCOUNT_BLOCK_BASE_PLASMA = 21_000 # dev:vm/constants/plasma.go | |
| 77 | + | SOURCED_ZNN_AB_BYTE_DATA_PLASMA = 68 # dev:vm/constants/plasma.go (DynamicPlasmaSpork) | |
| 78 | + | SOURCED_ZNN_EMBEDDED_SIMPLE_TIER = 52_500 # 2.5 * 21,000 | |
| 79 | + | SOURCED_ZNN_EMBEDDED_HEAVY_SPV_TIER = 73_500 # 3.5 * 21,000 | |
| 80 | + | SOURCED_ZNN_PLASMA_PER_QSR = 2_100 # 1 QSR = 1 fusion unit = 2,100 Plasma @ price 1,000 | |
| 81 | + | SOURCED_ZNN_POW_DIFF_PER_PLASMA = 1_500 # dev:vm/constants/plasma.go | |
| 82 | + | SOURCED_ZNN_MIN_RESOURCE_PRICE = 1_000 # dev:dp/dp.go | |
| 83 | + | SOURCED_ZNN_DP_DEFAULT_MAX_BASE_PLASMA = 4_200_000 # dev:vm/embedded/definition/plasma.go:97 | |
| 84 | + | SOURCED_ZNN_DP_UPPER_MAX_BASE_PLASMA = 2_100_000_000 # dev:vm/embedded/definition/plasma.go:63 | |
| 85 | + | SOURCED_ZNN_DP_LOWER_MAX_BASE_PLASMA = 210_000 # dev:vm/embedded/definition/plasma.go:66 | |
| 86 | + | SOURCED_ZNN_OBSERVED_MOMENTUM_SECS = 11.4 # dev:vm/embedded/definition/spork.go (11.35-11.46s) | |
| 87 | + | SOURCED_ZNN_CHAIN_BRIDGE_ROLLBACK = 30 # dev:protocol/chain_bridge.go:293 | |
| 88 | + | SOURCED_ZNN_MAX_MOMENTUM_CONTENT_BYTES = 8 * 1024 * 1024 # dev:verifier/momentum.go:93 (8 MiB) | |
| 89 | + | SOURCED_ZNN_PROTOCOL_MAX_MSG_SIZE = 10 * 1024 * 1024 # dev:protocol/protocol.go (10 MiB) | |
| 90 | + | SOURCED_ZNN_SOFT_RESPONSE_LIMIT = 2 * 1024 * 1024 # dev:protocol/protocol.go (2 MiB) | |
| 91 | + | SOURCED_ZNN_MAX_DETAILED_MOMENTUM_WIRE = ( | |
| 92 | + | SOURCED_ZNN_PROTOCOL_MAX_MSG_SIZE - SOURCED_ZNN_SOFT_RESPONSE_LIMIT - 4096 | |
| 93 | + | ) # 8,384,512 B (dev:protocol/protocol.go:70) | |
| 94 | + | SOURCED_ZNN_MIN_ACCOUNT_BLOCK_WIRE_LOW = 300 | |
| 95 | + | SOURCED_ZNN_MIN_ACCOUNT_BLOCK_WIRE_HIGH = 350 | |
| 96 | + | ||
| 97 | + | # ============================================================================== | |
| 98 | + | # POLICY PARAMETERS (Stage 0, Stage 1A BitVMX v3.1.0-rfc, Stage 1B clArk) | |
| 99 | + | # ============================================================================== | |
| 100 | + | POLICY_PINNED_MAX_BASE_PLASMA_FLOOR = 2_100_000 # Pinned >= 2.1M Plasma/Momentum | |
| 101 | + | POLICY_PINNED_MAX_PRICE_CHANGE_PCT = 25 # MaxPriceChangePercent <= 25% | |
| 102 | + | POLICY_PINNED_MIN_TARGET_SHARE_PCT = 25 # Fused/Pow targets >= 25% of 2.1M floor (525,000) | |
| 103 | + | POLICY_PINNED_MIN_PRICE_DENOM = 8 # PriceChangeDenominator >= 8 (spec/05 §2.2) | |
| 104 | + | POLICY_STAGE0_MIN_STRIPPED_TX_BYTES = 65 # Rejects <= 64 B CVE-2017-12842 leaves (R8-M06) | |
| 105 | + | POLICY_STAGE0_MAX_STRIPPED_TX_BYTES = 6_144 # Stage 0 SPV Event Oracle tx cap | |
| 106 | + | POLICY_STAGE0_MAX_STORAGE_OPS = 24 # Per-call L1 storage op ceiling | |
| 107 | + | ||
| 108 | + | # Stage 0 Erlang-Hardened PTLC / LN non-custodial swap parameters (R8-H07) | |
| 109 | + | POLICY_PTLC_BTC_CSV_BLOCKS = 72 # Automated high-fee RBF refund watchtower fires at h_conf + 72 | |
| 110 | + | POLICY_PTLC_ZNN_DURATION_SECS = 172_800 # >= 48.0 hours (P(T_72 > 48h | 2.3x) < 1e-6!) | |
| 111 | + | POLICY_LN_DELTA_SAFETY_BLOCKS = 36 | |
| 112 | + | POLICY_LN_OUTBOUND_DELTA_SAFETY_SECS = 86_400 # >= 24.0 hours (P(T_36 > 24h | 2.3x) < 2e-4!) | |
| 113 | + | ||
| 114 | + | # Stage 1A Right-Sized BitVMX (n=8) + Sovereign ZK Rollup parameters | |
| 115 | + | POLICY_BITVMX_N_BRANCH = 8 # n=8 (3 bits/round -> 7 intermediate hashes) | |
| 116 | + | POLICY_BITVMX_SEARCH_ROUNDS = 9 # 8^9 = 2^27 = 134,217,728 RV32IM wrapped-SNARK verifier ops | |
| 117 | + | POLICY_BITVMX_M_MIN = 3 # Minimal competitive operator count | |
| 118 | + | POLICY_BITVMX_M_MAX = 5 # Pilot operator count | |
| 119 | + | POLICY_BITVMX_L_LANES = 1 # Lanes per operator | |
| 120 | + | POLICY_BITVMX_N_VERIFIERS = 7 # Pre-committed online verifiers | |
| 121 | + | POLICY_BITVMX_R_ROUNDS = 64 # Pre-signed rounds per lane | |
| 122 | + | POLICY_STAGE2_TOTAL_LANES = 40 # Stage 2 scaled lane count (40 * 64 = 2,560 leaves) | |
| 123 | + | ||
| 124 | + | 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 | |
| 125 | + | POLICY_VAULT_ALT_SPLIT_SATS = (50_000_000, 50_000_000) # Optional {0.50, 0.50} split comparison | |
| 126 | + | POLICY_MAX_VAULT_DENOM_SATS = 50_000_000 # 0.50 BTC ceiling per vault UTXO | |
| 127 | + | POLICY_MIN_EXIT_SATS = 100_000 # 0.001 BTC normative dust floor (R8-M05) | |
| 128 | + | POLICY_NEW_LEAF_DEPOSIT_SATS = 500 # Refundable new-SMT-leaf deposit (R8-M01) | |
| 129 | + | POLICY_MAX_NEW_LEAVES_PER_EPOCH = 1_000 # <= 1,000 new SMT leaves per 6-block epoch (R8-M01) | |
| 130 | + | ||
| 131 | + | # Stage 1A Hard-Partitioned Per-Lane Bond & Native-L1 Verifier Economics (R8-H01, R8-H02, R8-N05) | |
| 132 | + | POLICY_BOND_BTC_SATS = 200_000_000 # 2.00 BTC L1 Stake_r bond | |
| 133 | + | POLICY_B_ZBTC_CUSTODY_SATS = 50_000_000 # 0.50 BTC maxVaultDenom Lamport restitution | |
| 134 | + | POLICY_B_ZBTC_EQUIV_BOUNTY_SATS = 5_000_000 # 0.05 BTC Lamport equivocation bounty | |
| 135 | + | POLICY_B_CUSTODY_TOTAL_SATS = ( | |
| 136 | + | POLICY_B_ZBTC_CUSTODY_SATS + POLICY_B_ZBTC_EQUIV_BOUNTY_SATS | |
| 137 | + | ) # 0.55 BTC HARD-PARTITIONED B_custody (NEVER debited by grief!) | |
| 138 | + | POLICY_B_GRIEF_TOTAL_SATS = 5_000_000 # 0.05 BTC HARD-PARTITIONED B_grief (ExitSlotUTXO grief only!) | |
| 139 | + | POLICY_B_ZBTC_TOTAL_SATS = POLICY_B_CUSTODY_TOTAL_SATS + POLICY_B_GRIEF_TOTAL_SATS # 0.60 BTC total/lane | |
| 140 | + | POLICY_LANE_TOTAL_BOND_SATS = POLICY_BOND_BTC_SATS + POLICY_B_ZBTC_TOTAL_SATS # 2.60 BTC/lane | |
| 141 | + | ||
| 142 | + | POLICY_F_CHAL_SATS = 40_000_000 # 0.40 BTC verifier challenge escrow | |
| 143 | + | POLICY_VERIFIER_NATIVE_L1_PAYOUT_SATS = 15_000_000 # 0.15 BTC NATIVE L1 BTC payout per active challenger (R8-H02!) | |
| 144 | + | POLICY_MIN_L1_STAKE_BURN_SATS = ( | |
| 145 | + | POLICY_BOND_BTC_SATS - POLICY_BITVMX_N_VERIFIERS * POLICY_VERIFIER_NATIVE_L1_PAYOUT_SATS | |
| 146 | + | ) # 0.95 BTC minimum immediate OP_RETURN burn when all 7 challenge! | |
| 147 | + | POLICY_EXIT_GRIEF_SLASH_SATS = 1_000_000 # 0.01 BTC per-exit grief penalty (pro-rata capped at B_grief!) | |
| 148 | + | POLICY_DESIGN_SUSTAINED_FEE_SATVB = 500 # 500 sat/vB primary sustained design envelope | |
| 149 | + | POLICY_STRESS_SUSTAINED_FEE_SATVB = 750 # 750 sat/vB stress-test verifier envelope | |
| 150 | + | POLICY_VERIFIER_LOCKUP_COST_SATS = 285_000 # 0.00285 BTC conservative capital lockup cost (R8-H02) | |
| 151 | + | POLICY_CRISIS_ZBTC_DISCOUNT = 0.30 # 30% crisis zBTC discount stress test (0% impact on native L1!) | |
| 152 | + | ||
| 153 | + | # Stage 1A Operational Reserve Accounting (R8-M09) | |
| 154 | + | POLICY_OP_RESERVE_VERIFIER_CPFP_PER_V_BTC = 0.10 # 0.10 BTC * 7 = 0.70 BTC verifier CPFP reserve | |
| 155 | + | POLICY_OP_RESERVE_DA_BATCHER_BTC = 0.50 # 0.50 BTC DA batcher L1 fee float | |
| 156 | + | POLICY_OP_RESERVE_TOPUP_PER_OP_BTC = 0.25 # 0.25 * M BTC operator top-up/CPFP reserve | |
| 157 | + | ||
| 158 | + | # Stage 1A Widened Simultaneous-Challenge BitVMX Timelocks (T_step = 72 blks = 12h, R8-H04) | |
| 159 | + | POLICY_T_CHAL_WINDOW = 144 # Simultaneous [0, 144] challenge window (24h) | |
| 160 | + | POLICY_T_STEP = 72 # 12h per bisection step (widened from 48!) | |
| 161 | + | POLICY_T_TAKE = 1_728 # 12.0d (> max_dispute_end = 1,584; +144 blk margin!) | |
| 162 | + | POLICY_T_COOLDOWN = 1_872 # 13.0d (1,728 + 144-blk Lamport equivocation slash window) | |
| 163 | + | POLICY_T_RETIRE = 2_016 # 14.0d Stake retirement CSV | |
| 164 | + | POLICY_T_EXIT_CANCEL = 288 # 48h user unilateral EXIT_CANCEL leaf (restores zBTC only) | |
| 165 | + | POLICY_K_MIN_FLOOR = 18 # Hard minimum K >= 18 blocks (R8-H03) | |
| 166 | + | ||
| 167 | + | # Stage 1A Capital & TVL Profiles (Cap_TVL_total = Cap_user + M * B_zbtc) | |
| 168 | + | POLICY_STAGE1A_PROFILES = { | |
| 169 | + | "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}, | |
| 170 | + | "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}, | |
| 171 | + | } | |
| 172 | + | # Tiers keyed by Cap_user -> Cap_TVL_total (incl. M * 0.60 BTC B_zbtc: M=3,5,20,40) | |
| 173 | + | POLICY_TVL_TIERS_TOTAL_BTC = { | |
| 174 | + | 10: 11.80, | |
| 175 | + | 15: 18.00, | |
| 176 | + | 50: 62.00, | |
| 177 | + | 200: 224.00, | |
| 178 | + | } | |
| 179 | + | POLICY_CONFIGURED_K_BY_ERA = { | |
| 180 | + | "2024-2028": {10: 18, 15: 18, 50: 42, 200: 144}, | |
| 181 | + | "2028-2032": {10: 18, 15: 24, 50: 80, 200: 288}, | |
| 182 | + | "2032-2036": {10: 32, 15: 48, 50: 160, 200: 576}, | |
| 183 | + | } | |
| 184 | + | ||
| 185 | + | # ============================================================================== | |
| 186 | + | # PRE-MAINNET TARGETS (BitVMX-CPU / Rollup / BitVM2 / clArk — Signet-Gated) | |
| 187 | + | # ============================================================================== | |
| 188 | + | PRE_MAINNET_TARGET_ROLLUP_TX_DATA_BYTES = 110 # Signed rollup transfer in AccountBlock.Data | |
| 189 | + | PRE_MAINNET_TARGET_DEPOSIT_CERTBLOB_BYTES = 104 # Acyclic OP_DROP certBlob <= 520 B | |
| 190 | + | PRE_MAINNET_TARGET_WOTS_DIGIT_WU = 95.5 # Per base-16 W-OTS digit weight (WU) | |
| 191 | + | PRE_MAINNET_TARGET_BISECTION_OVERHEAD_VB = 250.0 # Per prover bisection tx non-WOTS overhead (vB) | |
| 192 | + | PRE_MAINNET_TARGET_START_TX_VB = 3_000.0 # Prover StartTx vBytes | |
| 193 | + | PRE_MAINNET_TARGET_FINAL_TRACE_TX_VB = 5_000.0 # Prover FinalTraceTx vBytes | |
| 194 | + | PRE_MAINNET_TARGET_CHALLENGE_TX_VB = 350.0 # Verifier ChallengeTx vBytes | |
| 195 | + | PRE_MAINNET_TARGET_VERIFIER_CHOICE_VB = 350.0 # Verifier 3-bit interval choice tx vBytes | |
| 196 | + | PRE_MAINNET_TARGET_EXECUTE_OPCODE_VB = 8_000.0 # Verifier final 1-opcode disprove tx vBytes | |
| 197 | + | PRE_MAINNET_TARGET_PROVER_BASE_CAP_VB = 75_000 # Conservative prover base dispute cap (vB) | |
| 198 | + | PRE_MAINNET_TARGET_VERIFIER_BASE_CAP_VB = 15_000 # Conservative verifier base dispute cap (vB) | |
| 199 | + | PRE_MAINNET_TARGET_CPFP_COUNT_PER_SIDE = 10 # 10 P2A CPFP children per side (10 * 153 = 1,530 vB) | |
| 200 | + | PRE_MAINNET_TARGET_BITVM2_LANE_BOND_BTC_LOW = 13.30 | |
| 201 | + | PRE_MAINNET_TARGET_BITVM2_LANE_BOND_BTC_HIGH = 18.175 | |
| 202 | + | PRE_MAINNET_TARGET_CLARK_ACTIVE_LIQ_BTC = (2.0, 5.0) | |
| 203 | + | PRE_MAINNET_TARGET_CLARK_VTXO_COUNTS = (64, 128, 256, 512, 1024) | |
| 204 | + | ||
| 205 | + | ||
| 206 | + | # ============================================================================== | |
| 207 | + | # PURE PYTHON STDLIB MATH, CRYPTO & INVARIANT HELPERS | |
| 208 | + | # ============================================================================== | |
| 209 | + | def ceil_div(a: int, b: int) -> int: | |
| 210 | + | return (a + b - 1) // b | |
| 211 | + | ||
| 212 | + | ||
| 213 | + | def compact_size_len(n: int) -> int: | |
| 214 | + | if n < 253: | |
| 215 | + | return 1 | |
| 216 | + | if n <= 0xFFFF: | |
| 217 | + | return 3 | |
| 218 | + | if n <= 0xFFFFFFFF: | |
| 219 | + | return 5 | |
| 220 | + | return 9 | |
| 221 | + | ||
| 222 | + | ||
| 223 | + | def erlang_survival_prob(k_blocks: int, duration_secs: float, mean_block_secs: float) -> float: | |
| 224 | + | """ | |
| 225 | + | Exact Erlang(shape=k, rate=lambda) survival probability P(T_k > duration_secs) | |
| 226 | + | using pure Python stdlib (zero scipy dependency!): | |
| 227 | + | P(T_k > t) = P(Poisson(lambda * t) <= k - 1) = sum_{j=0}^{k-1} exp(-mu) * mu^j / j! | |
| 228 | + | Computed in log-space per term for full numerical stability. | |
| 229 | + | """ | |
| 230 | + | mu = duration_secs / mean_block_secs | |
| 231 | + | if mu <= 0.0: | |
| 232 | + | return 1.0 | |
| 233 | + | log_mu = math.log(mu) | |
| 234 | + | total = 0.0 | |
| 235 | + | for j in range(k_blocks): | |
| 236 | + | log_term = -mu + j * log_mu - math.lgamma(j + 1) | |
| 237 | + | total += math.exp(log_term) | |
| 238 | + | return min(1.0, max(0.0, total)) | |
| 239 | + | ||
| 240 | + | ||
| 241 | + | def erlang_quantile_hours(k_blocks: int, q: float, mean_block_secs: float) -> float: | |
| 242 | + | """Binary search exact Erlang quantile in hours (P(T_k <= t) = q).""" | |
| 243 | + | lo = 0.0 | |
| 244 | + | hi = k_blocks * mean_block_secs * 5.0 | |
| 245 | + | for _ in range(80): | |
| 246 | + | mid = 0.5 * (lo + hi) | |
| 247 | + | cdf = 1.0 - erlang_survival_prob(k_blocks, mid, mean_block_secs) | |
| 248 | + | if cdf < q: | |
| 249 | + | lo = mid | |
| 250 | + | else: | |
| 251 | + | hi = mid | |
| 252 | + | return (0.5 * (lo + hi)) / 3600.0 | |
| 253 | + | ||
| 254 | + | ||
| 255 | + | def abi_embedded_plasma(tier: int, abi_len: int) -> int: | |
| 256 | + | assert abi_len <= SOURCED_ZNN_MAX_DATA_LENGTH, f"ABI len {abi_len} exceeds 16 KiB" | |
| 257 | + | return tier + max(0, abi_len - 4) * SOURCED_ZNN_AB_BYTE_DATA_PLASMA | |
| 258 | + | ||
| 259 | + | ||
| 260 | + | # FIPS 180-4 SHA-256 single-block compression (for real coinbase midstate verification) | |
| 261 | + | _SHA256_IV = ( | |
| 262 | + | 0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, | |
| 263 | + | 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19, | |
| 264 | + | ) | |
| 265 | + | _SHA256_K = ( | |
| 266 | + | 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5, | |
| 267 | + | 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3, 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174, | |
| 268 | + | 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC, 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA, | |
| 269 | + | 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7, 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967, | |
| 270 | + | 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13, 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85, | |
| 271 | + | 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3, 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070, | |
| 272 | + | 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5, 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3, | |
| 273 | + | 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208, 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2, | |
| 274 | + | ) | |
| 275 | + | ||
| 276 | + | ||
| 277 | + | def _rotr32(x: int, n: int) -> int: | |
| 278 | + | return ((x >> n) | ((x << (32 - n)) & 0xFFFFFFFF)) & 0xFFFFFFFF | |
| 279 | + | ||
| 280 | + | ||
| 281 | + | def sha256_compress(state: tuple[int, ...], block64: bytes) -> tuple[int, ...]: | |
| 282 | + | assert len(block64) == 64 | |
| 283 | + | w = list(struct.unpack(">16I", block64)) | |
| 284 | + | for i in range(16, 64): | |
| 285 | + | s0 = _rotr32(w[i - 15], 7) ^ _rotr32(w[i - 15], 18) ^ (w[i - 15] >> 3) | |
| 286 | + | s1 = _rotr32(w[i - 2], 17) ^ _rotr32(w[i - 2], 19) ^ (w[i - 2] >> 10) | |
| 287 | + | w.append((w[i - 16] + s0 + w[i - 7] + s1) & 0xFFFFFFFF) | |
| 288 | + | a, b, c, d, e, f, g, h = state | |
| 289 | + | for i in range(64): | |
| 290 | + | S1 = _rotr32(e, 6) ^ _rotr32(e, 11) ^ _rotr32(e, 25) | |
| 291 | + | ch = (e & f) ^ ((~e & 0xFFFFFFFF) & g) | |
| 292 | + | t1 = (h + S1 + ch + _SHA256_K[i] + w[i]) & 0xFFFFFFFF | |
| 293 | + | S0 = _rotr32(a, 2) ^ _rotr32(a, 13) ^ _rotr32(a, 22) | |
| 294 | + | maj = (a & b) ^ (a & c) ^ (b & c) | |
| 295 | + | t2 = (S0 + maj) & 0xFFFFFFFF | |
| 296 | + | h, g, f, e, d, c, b, a = g, f, e, (d + t1) & 0xFFFFFFFF, c, b, a, (t1 + t2) & 0xFFFFFFFF | |
| 297 | + | return tuple((s + x) & 0xFFFFFFFF for s, x in zip(state, (a, b, c, d, e, f, g, h))) | |
| 298 | + | ||
| 299 | + | ||
| 300 | + | def complete_midstate_double_sha256(midstate_bytes: bytes, tail: bytes, total_len: int) -> tuple[bytes, int]: | |
| 301 | + | assert len(midstate_bytes) == 32 | |
| 302 | + | assert total_len >= POLICY_STAGE0_MIN_STRIPPED_TX_BYTES, ( | |
| 303 | + | "CVE-2017-12842: totalCoinbaseBytes must be >= 65 (64-byte leaf forbidden)" | |
| 304 | + | ) | |
| 305 | + | rem = total_len % 64 | |
| 306 | + | assert len(tail) == rem and len(tail) < 64 | |
| 307 | + | padded = bytearray(tail) | |
| 308 | + | padded.append(0x80) | |
| 309 | + | while len(padded) % 64 != 56: | |
| 310 | + | padded.append(0x00) | |
| 311 | + | padded.extend(struct.pack(">Q", total_len * 8)) | |
| 312 | + | blocks = len(padded) // 64 | |
| 313 | + | assert blocks in (1, 2) | |
| 314 | + | state = struct.unpack(">8I", midstate_bytes) | |
| 315 | + | for idx in range(blocks): | |
| 316 | + | state = sha256_compress(state, bytes(padded[idx * 64 : (idx + 1) * 64])) | |
| 317 | + | first_round = struct.pack(">8I", *state) | |
| 318 | + | return hashlib.sha256(first_round).digest(), blocks | |
| 319 | + | ||
| 320 | + | ||
| 321 | + | def compute_acyclic_vault_id( | |
| 322 | + | funding_txid: bytes, | |
| 323 | + | funding_vout: int, | |
| 324 | + | vault_vout: int, | |
| 325 | + | amount_sats: int, | |
| 326 | + | op_bitmask: int, | |
| 327 | + | ) -> bytes: | |
| 328 | + | """Normative R8-C01 acyclic vault_id bound strictly to already-confirmed U_dep_wallet.""" | |
| 329 | + | assert len(funding_txid) == 32 | |
| 330 | + | payload = ( | |
| 331 | + | b"zbtc:vault-id:v1" | |
| 332 | + | + funding_txid | |
| 333 | + | + struct.pack(">IIQQ", funding_vout, vault_vout, amount_sats, op_bitmask) | |
| 334 | + | ) | |
| 335 | + | return hashlib.sha256(payload).digest() | |
| 336 | + | ||
| 337 | + | ||
| 338 | + | def check_halls_marriage( | |
| 339 | + | vault_masks: list[int], | |
| 340 | + | usable_rounds_by_op: list[int], | |
| 341 | + | headroom_factor: float = 1.0, | |
| 342 | + | ) -> tuple[bool, int, int, int]: | |
| 343 | + | """ | |
| 344 | + | Exact 2^M Hall's Marriage Theorem verification (R8-C04): | |
| 345 | + | For every non-empty subset T of {0..M-1}: | |
| 346 | + | |{v in V_live : E(v) <= T}| <= floor(headroom_factor * sum_{i in T} r_i^usable) | |
| 347 | + | Returns (passes, failing_subset_mask, demand, supply). | |
| 348 | + | """ | |
| 349 | + | m = len(usable_rounds_by_op) | |
| 350 | + | assert 1 <= m <= 12 | |
| 351 | + | for mask in range(1, 1 << m): | |
| 352 | + | demand = sum(1 for vm in vault_masks if vm != 0 and (vm & ~mask) == 0) | |
| 353 | + | supply_raw = sum(usable_rounds_by_op[i] for i in range(m) if (mask >> i) & 1) | |
| 354 | + | supply = int(math.floor(headroom_factor * supply_raw)) | |
| 355 | + | if demand > supply: | |
| 356 | + | return False, mask, demand, supply | |
| 357 | + | return True, 0, 0, 0 | |
| 358 | + | ||
| 359 | + | ||
| 360 | + | def cyclic_exit_priority(exit_id: bytes, m_active: int) -> list[int]: | |
| 361 | + | """Normative R8-M03 collision-free cyclic priority k_r = (H(exitId) + r) mod M_active.""" | |
| 362 | + | assert m_active >= 1 | |
| 363 | + | h0 = int.from_bytes(hashlib.sha256(exit_id).digest()[:8], "big") | |
| 364 | + | return [(h0 + r) % m_active for r in range(m_active)] | |
| 365 | + | ||
| 366 | + | ||
| 367 | + | def dp_next_price( | |
| 368 | + | current_price: int, | |
| 369 | + | used_plasma: int, | |
| 370 | + | target_plasma: int, | |
| 371 | + | max_change_pct: int, | |
| 372 | + | denom: int, | |
| 373 | + | ) -> int: | |
| 374 | + | delta = used_plasma - target_plasma | |
| 375 | + | num = delta * current_price | |
| 376 | + | if num >= 0: | |
| 377 | + | change = (num // target_plasma) // denom | |
| 378 | + | else: | |
| 379 | + | change = -((-num // target_plasma) // denom) | |
| 380 | + | nxt = current_price + change | |
| 381 | + | max_nxt = (current_price * (100 + max_change_pct)) // 100 | |
| 382 | + | min_nxt = (current_price * (100 - max_change_pct)) // 100 | |
| 383 | + | if nxt > max_nxt: | |
| 384 | + | nxt = max_nxt | |
| 385 | + | if nxt < min_nxt: | |
| 386 | + | nxt = min_nxt | |
| 387 | + | if nxt < SOURCED_ZNN_MIN_RESOURCE_PRICE: | |
| 388 | + | nxt = SOURCED_ZNN_MIN_RESOURCE_PRICE | |
| 389 | + | return nxt | |
| 390 | + | ||
| 391 | + | ||
| 392 | + | # ============================================================================== | |
| 393 | + | # REAL, NON-NO-OP 2,000-STEP STAGE 1A SOLVENCY & ADVERSARIAL SIMULATION (v3.1.0-rfc) | |
| 394 | + | # ============================================================================== | |
| 395 | + | def run_stage1a_solvency_sim(seed: int = 20261128, steps: int = 2_000) -> dict[str, int]: | |
| 396 | + | """ | |
| 397 | + | Adversarial state-machine simulation of Stage 1A BitVMX (n=8, M=5, N=7) v3.1.0-rfc: | |
| 398 | + | - Explicit AssignedObligations (A) namespace separating fifo_assign & take_confirmed across T_take (R8-C02!) | |
| 399 | + | - Exact conservation: V_unassigned + V_assigned == C + L + E + R + A + B at EVERY step! | |
| 400 | + | - Denomination-matched AdmissionTicketUTXO Cap_TVL L1 mutual exclusion + deposit race test (R8-C03!) | |
| 401 | + | - Exact 2^M Hall's Marriage verification on deposit admission & operator slash (R8-C04!) | |
| 402 | + | - Hard-partitioned B_custody (0.55 BTC) vs B_grief (0.05 BTC) + k=20 single-block ExitSlotUTXO grief burst | |
| 403 | + | proving ZERO B_custody overflow & ZERO verifier payout impact (R8-H01, R8-N05!) | |
| 404 | + | - Signed TransferCredit residual consolidation for < 0.25 BTC credits (R8-M04!) | |
| 405 | + | - Explicit 0x07 RELEASE_ASSIGNMENT + Leaf 2M EXIT_CANCEL + dual-input Disprove slash + cross-operator Lamport slash | |
| 406 | + | - Genuine Bitcoin reorgs (popping 1..K-1 unconfirmed blocks & discarding orphaned events!) | |
| 407 | + | """ | |
| 408 | + | rng = random.Random(seed) | |
| 409 | + | K = POLICY_CONFIGURED_K_BY_ERA["2024-2028"][15] # 18 blocks | |
| 410 | + | cap_user_sats = int(15.0 * SAT) | |
| 411 | + | cap_total_sats = int(18.0 * SAT) # 15.0 user + 3.0 operator B_zbtc (plus operator free_zbtc buffer) | |
| 412 | + | all_ops_mask = (1 << POLICY_BITVMX_M_MAX) - 1 # 0b11111 | |
| 413 | + | ||
| 414 | + | # Denomination-matched AdmissionTicketUTXO pool (R8-C03): | |
| 415 | + | # Genesis tickets strictly cap total live vaults <= 20.0 BTC (15 user + 5 operator initial 1.0 BTC vaults) | |
| 416 | + | ticket_pool = {50_000_000: 20, 25_000_000: 40} # 20*0.50 + 40*0.25 = 20.0 BTC exact L1 consensus cap! | |
| 417 | + | ||
| 418 | + | # Canonical K-deep rollup state | |
| 419 | + | users: dict[str, int] = { | |
| 420 | + | "alice": 0, "bob": 0, "mike": 0, "carol": 0, "dave": 0, | |
| 421 | + | "insurance_pool": 0, "challenger_bounty_pool": 0, | |
| 422 | + | } | |
| 423 | + | rollup_locks: dict[int, int] = {} # L namespace | |
| 424 | + | unassigned_vaults: dict[int, dict] = {} # vault_id -> {"sats", "mask"} | |
| 425 | + | assigned_vaults: dict[int, dict] = {} # vault_id -> {"sats", "mask", "op_id", "assigned_h"} | |
| 426 | + | assigned_obligations: dict[int, int] = {} # A namespace: vault_id -> sats | |
| 427 | + | next_vault_id = 1 | |
| 428 | + | ||
| 429 | + | operators: dict[int, dict] = {} | |
| 430 | + | for op_id in range(POLICY_BITVMX_M_MAX): | |
| 431 | + | # Each operator deposits 1.00 BTC (consuming 2 x Ticket_050) -> 0.55 B_custody + 0.05 B_grief + 0.40 free_zbtc | |
| 432 | + | for _ in range(2): | |
| 433 | + | assert ticket_pool[50_000_000] >= 1 | |
| 434 | + | ticket_pool[50_000_000] -= 1 | |
| 435 | + | unassigned_vaults[next_vault_id] = {"sats": 50_000_000, "mask": all_ops_mask} | |
| 436 | + | next_vault_id += 1 | |
| 437 | + | operators[op_id] = { | |
| 438 | + | "b_custody": POLICY_B_CUSTODY_TOTAL_SATS, # 0.55 BTC hard-partitioned | |
| 439 | + | "b_grief": POLICY_B_GRIEF_TOTAL_SATS, # 0.05 BTC hard-partitioned | |
| 440 | + | "free_zbtc": 40_000_000, | |
| 441 | + | "credit": 0, | |
| 442 | + | "rounds_left": POLICY_BITVMX_R_ROUNDS, | |
| 443 | + | "suspended": False, | |
| 444 | + | } | |
| 445 | + | ||
| 446 | + | pending_exits: dict[int, dict] = {} | |
| 447 | + | next_exit_id = 1 | |
| 448 | + | ||
| 449 | + | finalized_height = 100 | |
| 450 | + | tip_blocks: list[dict] = [] | |
| 451 | + | unconf_spent_exits: set[int] = set() | |
| 452 | + | unconf_taken_vaults: set[int] = set() | |
| 453 | + | unconf_released_vaults: set[int] = set() | |
| 454 | + | ||
| 455 | + | counts: dict[str, int] = { | |
| 456 | + | k: 0 for k in ( | |
| 457 | + | "deposit", "deposit_race_blocked_by_ticket", "transfer", "forced_exit", | |
| 458 | + | "front_paid", "front_grief", "front_grief_burst_k20", "exit_cancel", | |
| 459 | + | "fifo_assign", "take_confirmed", "release_assignment", "transfer_credit", | |
| 460 | + | "disprove_dual_slash", "lamport_equivocation_slash", "topup_op", | |
| 461 | + | "mine_block", "reorg", "reorg_blocks_reverted", "reorg_events_reverted", | |
| 462 | + | ) | |
| 463 | + | } | |
| 464 | + | ||
| 465 | + | def rebuild_unconf_locks() -> None: | |
| 466 | + | unconf_spent_exits.clear() | |
| 467 | + | unconf_taken_vaults.clear() | |
| 468 | + | unconf_released_vaults.clear() | |
| 469 | + | for blk in tip_blocks: | |
| 470 | + | for ev in blk["events"]: | |
| 471 | + | kind = ev["kind"] | |
| 472 | + | if kind in ("front_paid", "front_grief", "exit_cancel"): | |
| 473 | + | unconf_spent_exits.add(ev["exit_id"]) | |
| 474 | + | elif kind == "front_grief_burst": | |
| 475 | + | for eid in ev["exit_ids"]: | |
| 476 | + | unconf_spent_exits.add(eid) | |
| 477 | + | elif kind in ("take_confirmed", "lamport_equivocation_slash"): | |
| 478 | + | unconf_taken_vaults.add(ev["vault_id"]) | |
| 479 | + | elif kind == "release_assignment": | |
| 480 | + | unconf_released_vaults.add(ev["vault_id"]) | |
| 481 | + | ||
| 482 | + | def run_deterministic_fifo_assign(blk_height: int) -> None: | |
| 483 | + | """ | |
| 484 | + | Deterministically moves R[op] -> A[v] and V_unassigned -> V_assigned (R8-C02), | |
| 485 | + | keeping V_unassigned + V_assigned == C + L + E + R + A + B invariant across T_take! | |
| 486 | + | """ | |
| 487 | + | for oid in sorted(operators.keys()): | |
| 488 | + | op = operators[oid] | |
| 489 | + | if op["rounds_left"] <= 0: | |
| 490 | + | continue | |
| 491 | + | # Assign oldest eligible vault while credit covers it | |
| 492 | + | while True: | |
| 493 | + | eligible_vids = [ | |
| 494 | + | vid for vid in sorted(unassigned_vaults.keys()) | |
| 495 | + | if ((unassigned_vaults[vid]["mask"] >> oid) & 1) | |
| 496 | + | and op["credit"] >= unassigned_vaults[vid]["sats"] | |
| 497 | + | and op["rounds_left"] > 0 | |
| 498 | + | ] | |
| 499 | + | if not eligible_vids: | |
| 500 | + | break | |
| 501 | + | vid = eligible_vids[0] | |
| 502 | + | vinfo = unassigned_vaults.pop(vid) | |
| 503 | + | vamt = vinfo["sats"] | |
| 504 | + | op["credit"] -= vamt | |
| 505 | + | assigned_vaults[vid] = { | |
| 506 | + | "sats": vamt, | |
| 507 | + | "mask": vinfo["mask"], | |
| 508 | + | "op_id": oid, | |
| 509 | + | "assigned_h": blk_height, | |
| 510 | + | } | |
| 511 | + | assigned_obligations[vid] = vamt | |
| 512 | + | counts["fifo_assign"] += 1 | |
| 513 | + | ||
| 514 | + | def apply_finalized_event(ev: dict, blk_height: int) -> None: | |
| 515 | + | kind = ev["kind"] | |
| 516 | + | if kind == "deposit": | |
| 517 | + | # Enforce L1 AdmissionTicketUTXO mutual exclusion (R8-C03) | |
| 518 | + | needed = {50_000_000: 0, 25_000_000: 0} | |
| 519 | + | for _, vamt in ev["vaults"]: | |
| 520 | + | needed[vamt] += 1 | |
| 521 | + | if ticket_pool[50_000_000] < needed[50_000_000] or ticket_pool[25_000_000] < needed[25_000_000]: | |
| 522 | + | # Loser deposit rejected at L1 consensus before U_dep_wallet is spent! | |
| 523 | + | counts["deposit_race_blocked_by_ticket"] += 1 | |
| 524 | + | return | |
| 525 | + | for denom, qty in needed.items(): | |
| 526 | + | ticket_pool[denom] -= qty | |
| 527 | + | for vid, vamt in ev["vaults"]: | |
| 528 | + | unassigned_vaults[vid] = {"sats": vamt, "mask": ev["mask"]} | |
| 529 | + | users[ev["user"]] += sum(vamt for _, vamt in ev["vaults"]) | |
| 530 | + | counts["deposit"] += 1 | |
| 531 | + | ||
| 532 | + | elif kind == "forced_exit": | |
| 533 | + | u = ev["user"] | |
| 534 | + | amt = ev["gross"] | |
| 535 | + | assert amt >= POLICY_MIN_EXIT_SATS | |
| 536 | + | if users[u] >= amt: | |
| 537 | + | users[u] -= amt | |
| 538 | + | pending_exits[ev["exit_id"]] = {"user": u, "gross": amt, "created_h": blk_height} | |
| 539 | + | counts["forced_exit"] += 1 | |
| 540 | + | ||
| 541 | + | elif kind == "front_paid": | |
| 542 | + | eid = ev["exit_id"] | |
| 543 | + | if eid in pending_exits: | |
| 544 | + | ex = pending_exits.pop(eid) | |
| 545 | + | operators[ev["op_id"]]["credit"] += ex["gross"] | |
| 546 | + | counts["front_paid"] += 1 | |
| 547 | + | run_deterministic_fifo_assign(blk_height) | |
| 548 | + | ||
| 549 | + | elif kind == "front_grief": | |
| 550 | + | eid = ev["exit_id"] | |
| 551 | + | op = operators[ev["op_id"]] | |
| 552 | + | if eid in pending_exits: | |
| 553 | + | ex = pending_exits.pop(eid) | |
| 554 | + | users[ex["user"]] += ex["gross"] | |
| 555 | + | # Hard-partitioned B_grief penalty: NEVER touches B_custody (R8-H01 / R8-N05)! | |
| 556 | + | pen = min(POLICY_EXIT_GRIEF_SLASH_SATS, op["b_grief"]) | |
| 557 | + | op["b_grief"] -= pen | |
| 558 | + | users[ex["user"]] += pen | |
| 559 | + | op["suspended"] = True | |
| 560 | + | assert op["b_custody"] == POLICY_B_CUSTODY_TOTAL_SATS or op["suspended"] | |
| 561 | + | counts["front_grief"] += 1 | |
| 562 | + | ||
| 563 | + | elif kind == "front_grief_burst": | |
| 564 | + | # Concurrent k-exit grief burst in ONE Bitcoin block (R8-H01 / R8-N05 proof!) | |
| 565 | + | op = operators[ev["op_id"]] | |
| 566 | + | b_custody_before = op["b_custody"] | |
| 567 | + | live_eids = [eid for eid in ev["exit_ids"] if eid in pending_exits] | |
| 568 | + | if live_eids: | |
| 569 | + | per_victim = min(POLICY_EXIT_GRIEF_SLASH_SATS, op["b_grief"] // len(live_eids)) | |
| 570 | + | for eid in live_eids: | |
| 571 | + | ex = pending_exits.pop(eid) | |
| 572 | + | users[ex["user"]] += ex["gross"] + per_victim | |
| 573 | + | op["b_grief"] -= per_victim | |
| 574 | + | op["suspended"] = True | |
| 575 | + | assert op["b_custody"] == b_custody_before, "B_custody touched by ExitSlotUTXO grief burst!" | |
| 576 | + | assert op["b_grief"] >= 0 | |
| 577 | + | counts["front_grief_burst_k20"] += 1 | |
| 578 | + | ||
| 579 | + | elif kind == "exit_cancel": | |
| 580 | + | eid = ev["exit_id"] | |
| 581 | + | if eid in pending_exits and blk_height >= pending_exits[eid]["created_h"] + POLICY_T_EXIT_CANCEL: | |
| 582 | + | ex = pending_exits.pop(eid) | |
| 583 | + | users[ex["user"]] += ex["gross"] | |
| 584 | + | counts["exit_cancel"] += 1 | |
| 585 | + | ||
| 586 | + | elif kind == "take_confirmed": | |
| 587 | + | # Separate from fifo_assign! Confirms after T_take gap, retiring V_assigned & A AND recycling ticket! | |
| 588 | + | vid = ev["vault_id"] | |
| 589 | + | if vid in assigned_vaults and assigned_vaults[vid]["op_id"] == ev["op_id"]: | |
| 590 | + | vinfo = assigned_vaults.pop(vid) | |
| 591 | + | vamt = assigned_obligations.pop(vid) | |
| 592 | + | assert vamt == vinfo["sats"] | |
| 593 | + | ticket_pool[vamt] += 1 # Recycle denomination-matched AdmissionTicketUTXO! | |
| 594 | + | operators[ev["op_id"]]["rounds_left"] = max(0, operators[ev["op_id"]]["rounds_left"] - 1) | |
| 595 | + | counts["take_confirmed"] += 1 | |
| 596 | + | ||
| 597 | + | elif kind == "release_assignment": | |
| 598 | + | # 0x07 RELEASE_ASSIGNMENT: V_assigned -> V_unassigned, A[v] -> R[op] | |
| 599 | + | vid = ev["vault_id"] | |
| 600 | + | if vid in assigned_vaults and assigned_vaults[vid]["op_id"] == ev["op_id"]: | |
| 601 | + | vinfo = assigned_vaults.pop(vid) | |
| 602 | + | vamt = assigned_obligations.pop(vid) | |
| 603 | + | unassigned_vaults[vid] = {"sats": vamt, "mask": vinfo["mask"]} | |
| 604 | + | operators[ev["op_id"]]["credit"] += vamt | |
| 605 | + | counts["release_assignment"] += 1 | |
| 606 | + | ||
| 607 | + | elif kind == "transfer_credit": | |
| 608 | + | src, dst, amt = ev["from_op"], ev["to_op"], ev["amount"] | |
| 609 | + | if operators[src]["credit"] >= amt: | |
| 610 | + | operators[src]["credit"] -= amt | |
| 611 | + | operators[dst]["credit"] += amt | |
| 612 | + | counts["transfer_credit"] += 1 | |
| 613 | + | run_deterministic_fifo_assign(blk_height) | |
| 614 | + | ||
| 615 | + | elif kind == "disprove_dual_slash": | |
| 616 | + | # Dual-input Disprove spends Stake_r + VaultConnector_r -> 0 BTC leaves vault! | |
| 617 | + | # Native L1 verifier bounties paid from Stake_r; L2 B_custody slashed to insurance_pool. | |
| 618 | + | op = operators[ev["op_id"]] | |
| 619 | + | if op["b_custody"] >= POLICY_B_CUSTODY_TOTAL_SATS: | |
| 620 | + | # If any vault was assigned to this op's challenged round, return V_assigned -> V_unassigned & A -> R | |
| 621 | + | for vid in [v for v, info in assigned_vaults.items() if info["op_id"] == ev["op_id"]][:1]: | |
| 622 | + | vinfo = assigned_vaults.pop(vid) | |
| 623 | + | vamt = assigned_obligations.pop(vid) | |
| 624 | + | unassigned_vaults[vid] = {"sats": vamt, "mask": vinfo["mask"]} | |
| 625 | + | op["credit"] += vamt | |
| 626 | + | op["b_custody"] -= POLICY_B_CUSTODY_TOTAL_SATS | |
| 627 | + | users["insurance_pool"] += POLICY_B_CUSTODY_TOTAL_SATS | |
| 628 | + | op["suspended"] = True | |
| 629 | + | counts["disprove_dual_slash"] += 1 | |
| 630 | + | ||
| 631 | + | elif kind == "lamport_equivocation_slash": | |
| 632 | + | # Rogue operator stole vault v (either unassigned OR assigned to innocent O_k!) | |
| 633 | + | vid = ev["vault_id"] | |
| 634 | + | op = operators[ev["op_id"]] | |
| 635 | + | if vid in unassigned_vaults: | |
| 636 | + | vamt = unassigned_vaults[vid]["sats"] | |
| 637 | + | if op["b_custody"] >= vamt + POLICY_B_ZBTC_EQUIV_BOUNTY_SATS: | |
| 638 | + | unassigned_vaults.pop(vid) | |
| 639 | + | ticket_pool[vamt] += 1 | |
| 640 | + | op["b_custody"] -= (vamt + POLICY_B_ZBTC_EQUIV_BOUNTY_SATS) | |
| 641 | + | users["challenger_bounty_pool"] += POLICY_B_ZBTC_EQUIV_BOUNTY_SATS | |
| 642 | + | op["suspended"] = True | |
| 643 | + | counts["lamport_equivocation_slash"] += 1 | |
| 644 | + | elif vid in assigned_vaults: | |
| 645 | + | vinfo = assigned_vaults[vid] | |
| 646 | + | vamt = vinfo["sats"] | |
| 647 | + | if op["b_custody"] >= vamt + POLICY_B_ZBTC_EQUIV_BOUNTY_SATS: | |
| 648 | + | assigned_vaults.pop(vid) | |
| 649 | + | assigned_obligations.pop(vid) | |
| 650 | + | ticket_pool[vamt] += 1 | |
| 651 | + | # Restore innocent assignee O_k 100% whole via R[O_k] += vamt! | |
| 652 | + | operators[vinfo["op_id"]]["credit"] += vamt | |
| 653 | + | op["b_custody"] -= (vamt + POLICY_B_ZBTC_EQUIV_BOUNTY_SATS) | |
| 654 | + | users["challenger_bounty_pool"] += POLICY_B_ZBTC_EQUIV_BOUNTY_SATS | |
| 655 | + | op["suspended"] = True | |
| 656 | + | counts["lamport_equivocation_slash"] += 1 | |
| 657 | + | ||
| 658 | + | def assert_solvency(label: str) -> None: | |
| 659 | + | v_unassigned = sum(v["sats"] for v in unassigned_vaults.values()) | |
| 660 | + | v_assigned = sum(v["sats"] for v in assigned_vaults.values()) | |
| 661 | + | lhs = v_unassigned + v_assigned | |
| 662 | + | ||
| 663 | + | c_total = sum(users.values()) + sum(op["free_zbtc"] for op in operators.values()) | |
| 664 | + | l_total = sum(rollup_locks.values()) | |
| 665 | + | e_total = sum(ex["gross"] for ex in pending_exits.values()) | |
| 666 | + | r_total = sum(op["credit"] for op in operators.values()) | |
| 667 | + | a_total = sum(assigned_obligations.values()) | |
| 668 | + | b_total = sum(op["b_custody"] + op["b_grief"] for op in operators.values()) | |
| 669 | + | rhs = c_total + l_total + e_total + r_total + a_total + b_total | |
| 670 | + | ||
| 671 | + | assert lhs == rhs, f"[{label}] Conservation mismatch! V={lhs} != C+L+E+R+A+B={rhs}" | |
| 672 | + | assert v_assigned == a_total, f"[{label}] V_assigned={v_assigned} != A={a_total}" | |
| 673 | + | # Ticket + live vault conservation: total minted tickets == 20*0.50 + 40*0.25 = 20.0 BTC ALWAYS! | |
| 674 | + | ticket_value = ticket_pool[50_000_000] * 50_000_000 + ticket_pool[25_000_000] * 25_000_000 | |
| 675 | + | assert lhs + ticket_value == 20 * SAT, f"[{label}] Ticket conservation broken: {lhs} + {ticket_value}" | |
| 676 | + | for oid, op in operators.items(): | |
| 677 | + | assert op["b_custody"] >= 0 and op["b_grief"] >= 0 | |
| 678 | + | if not op["suspended"]: | |
| 679 | + | assert op["b_custody"] == POLICY_B_CUSTODY_TOTAL_SATS | |
| 680 | + | assert op["b_grief"] == POLICY_B_GRIEF_TOTAL_SATS | |
| 681 | + | ||
| 682 | + | def mine_one_block(events: list[dict]) -> None: | |
| 683 | + | nonlocal finalized_height | |
| 684 | + | next_h = finalized_height + len(tip_blocks) + 1 | |
| 685 | + | tip_blocks.append({"height": next_h, "events": events}) | |
| 686 | + | counts["mine_block"] += 1 | |
| 687 | + | while len(tip_blocks) >= K: | |
| 688 | + | fin_blk = tip_blocks.pop(0) | |
| 689 | + | finalized_height = fin_blk["height"] | |
| 690 | + | for ev in fin_blk["events"]: | |
| 691 | + | apply_finalized_event(ev, finalized_height) | |
| 692 | + | rebuild_unconf_locks() | |
| 693 | + | ||
| 694 | + | def current_tip_height() -> int: | |
| 695 | + | return finalized_height + len(tip_blocks) | |
| 696 | + | ||
| 697 | + | assert_solvency("init") | |
| 698 | + | ||
| 699 | + | # ------------------------------------------------------------------ | |
| 700 | + | # 1. DETERMINISTIC BOB & MIKE TRACES WITH EXPLICIT T_take GAP (A > 0!) | |
| 701 | + | # ------------------------------------------------------------------ | |
| 702 | + | bob_vaults = [(next_vault_id + i, amt) for i, amt in enumerate(POLICY_VAULT_TIERS_SATS)] | |
| 703 | + | next_vault_id += 3 | |
| 704 | + | alice_vaults = [(next_vault_id + i, amt) for i, amt in enumerate(POLICY_VAULT_TIERS_SATS)] | |
| 705 | + | next_vault_id += 3 | |
| 706 | + | mine_one_block([ | |
| 707 | + | {"kind": "deposit", "user": "bob", "vaults": bob_vaults, "mask": all_ops_mask}, | |
| 708 | + | {"kind": "deposit", "user": "alice", "vaults": alice_vaults, "mask": all_ops_mask}, | |
| 709 | + | ]) | |
| 710 | + | for _ in range(K - 1): | |
| 711 | + | mine_one_block([]) | |
| 712 | + | assert users["bob"] == SAT and users["alice"] == SAT | |
| 713 | + | assert_solvency("after_bob_alice_deposits") | |
| 714 | + | ||
| 715 | + | # Bob spends 0.50 zBTC to Carol, exits 0.50 BTC -> FIFO assigns (A = 0.50 BTC!) -> TakeTx confirms later! | |
| 716 | + | users["bob"] -= 50_000_000 | |
| 717 | + | users["carol"] += 50_000_000 | |
| 718 | + | counts["transfer"] += 1 | |
| 719 | + | bob_eid = next_exit_id | |
| 720 | + | next_exit_id += 1 | |
| 721 | + | mine_one_block([{"kind": "forced_exit", "user": "bob", "gross": 50_000_000, "exit_id": bob_eid}]) | |
| 722 | + | for _ in range(K - 1): | |
| 723 | + | mine_one_block([]) | |
| 724 | + | mine_one_block([{"kind": "front_paid", "exit_id": bob_eid, "op_id": 0}]) | |
| 725 | + | for _ in range(K - 1): | |
| 726 | + | mine_one_block([]) | |
| 727 | + | # Verify R8-C02: during the T_take gap, A == 0.50 BTC > 0 AND V == C+L+E+R+A+B holds! | |
| 728 | + | assert sum(assigned_obligations.values()) == 50_000_000 | |
| 729 | + | assert_solvency("bob_mid_T_take_gap_A_nonzero") | |
| 730 | + | assigned_bob_vid = next(iter(assigned_vaults.keys())) | |
| 731 | + | mine_one_block([{"kind": "take_confirmed", "op_id": 0, "vault_id": assigned_bob_vid}]) | |
| 732 | + | for _ in range(K - 1): | |
| 733 | + | mine_one_block([]) | |
| 734 | + | assert sum(assigned_obligations.values()) == 0 | |
| 735 | + | assert_solvency("after_bob_0.5_take_confirmed") | |
| 736 | + | ||
| 737 | + | # Mike scenario (Alice 1 + Bob2 1 -> Mike 2 -> Mike exits 0.25 BTC) | |
| 738 | + | bob2_vaults = [(next_vault_id + i, amt) for i, amt in enumerate(POLICY_VAULT_TIERS_SATS)] | |
| 739 | + | next_vault_id += 3 | |
| 740 | + | mine_one_block([{"kind": "deposit", "user": "bob", "vaults": bob2_vaults, "mask": all_ops_mask}]) | |
| 741 | + | for _ in range(K - 1): | |
| 742 | + | mine_one_block([]) | |
| 743 | + | users["alice"] -= SAT | |
| 744 | + | users["bob"] -= SAT | |
| 745 | + | users["mike"] += 2 * SAT | |
| 746 | + | counts["transfer"] += 2 | |
| 747 | + | mike_eid = next_exit_id | |
| 748 | + | next_exit_id += 1 | |
| 749 | + | mine_one_block([{"kind": "forced_exit", "user": "mike", "gross": 25_000_000, "exit_id": mike_eid}]) | |
| 750 | + | for _ in range(K - 1): | |
| 751 | + | mine_one_block([]) | |
| 752 | + | mine_one_block([{"kind": "front_paid", "exit_id": mike_eid, "op_id": 1}]) | |
| 753 | + | for _ in range(K - 1): | |
| 754 | + | mine_one_block([]) | |
| 755 | + | assert sum(assigned_obligations.values()) == 25_000_000 | |
| 756 | + | assert_solvency("mike_mid_T_take_gap_A_nonzero") | |
| 757 | + | assigned_mike_vid = next(iter(assigned_vaults.keys())) | |
| 758 | + | mine_one_block([{"kind": "take_confirmed", "op_id": 1, "vault_id": assigned_mike_vid}]) | |
| 759 | + | for _ in range(K - 1): | |
| 760 | + | mine_one_block([]) | |
| 761 | + | assert users["mike"] == 175_000_000 and sum(assigned_obligations.values()) == 0 | |
| 762 | + | assert_solvency("after_mike_0.25_take_confirmed") | |
| 763 | + | ||
| 764 | + | # ------------------------------------------------------------------ | |
| 765 | + | # 2. DETERMINISTIC R8-H01 / R8-N05 k=20 CONCURRENT GRIEF BURST TEST | |
| 766 | + | # ------------------------------------------------------------------ | |
| 767 | + | burst_eids = [] | |
| 768 | + | for _ in range(20): | |
| 769 | + | eid = next_exit_id | |
| 770 | + | next_exit_id += 1 | |
| 771 | + | burst_eids.append(eid) | |
| 772 | + | mine_one_block([{"kind": "forced_exit", "user": "mike", "gross": 5_000_000, "exit_id": eid}]) | |
| 773 | + | for _ in range(K): | |
| 774 | + | mine_one_block([]) | |
| 775 | + | b_cust_before = operators[2]["b_custody"] | |
| 776 | + | mine_one_block([{"kind": "front_grief_burst", "op_id": 2, "exit_ids": burst_eids}]) | |
| 777 | + | for _ in range(K): | |
| 778 | + | mine_one_block([]) | |
| 779 | + | assert operators[2]["b_custody"] == b_cust_before == POLICY_B_CUSTODY_TOTAL_SATS | |
| 780 | + | assert operators[2]["b_grief"] == 0 and operators[2]["suspended"] | |
| 781 | + | assert_solvency("after_k20_grief_burst") | |
| 782 | + | ||
| 783 | + | # ------------------------------------------------------------------ | |
| 784 | + | # 3. DETERMINISTIC R8-M04 TRANSFER_CREDIT RESIDUAL CONSOLIDATION TEST | |
| 785 | + | # ------------------------------------------------------------------ | |
| 786 | + | # Give ops 3 & 4 each 0.15 BTC (< 0.25 BTC min vault), then consolidate via TransferCredit -> triggers FIFO assign! | |
| 787 | + | e_res1, e_res2 = next_exit_id, next_exit_id + 1 | |
| 788 | + | next_exit_id += 2 | |
| 789 | + | mine_one_block([ | |
| 790 | + | {"kind": "forced_exit", "user": "mike", "gross": 15_000_000, "exit_id": e_res1}, | |
| 791 | + | {"kind": "forced_exit", "user": "mike", "gross": 15_000_000, "exit_id": e_res2}, | |
| 792 | + | ]) | |
| 793 | + | for _ in range(K): | |
| 794 | + | mine_one_block([]) | |
| 795 | + | mine_one_block([ | |
| 796 | + | {"kind": "front_paid", "exit_id": e_res1, "op_id": 3}, | |
| 797 | + | {"kind": "front_paid", "exit_id": e_res2, "op_id": 4}, | |
| 798 | + | ]) | |
| 799 | + | for _ in range(K): | |
| 800 | + | mine_one_block([]) | |
| 801 | + | assert operators[3]["credit"] == 15_000_000 and operators[4]["credit"] == 15_000_000 | |
| 802 | + | mine_one_block([{"kind": "transfer_credit", "from_op": 3, "to_op": 4, "amount": 15_000_000}]) | |
| 803 | + | for _ in range(K): | |
| 804 | + | mine_one_block([]) | |
| 805 | + | assert operators[3]["credit"] == 0 and operators[4]["credit"] == 5_000_000 # 0.30 -> assigned 0.25 vault, 0.05 left! | |
| 806 | + | assert_solvency("after_transfer_credit") | |
| 807 | + | ||
| 808 | + | # ------------------------------------------------------------------ | |
| 809 | + | # 4. 2,000-STEP ADVERSARIAL RANDOMIZED SIMULATION (WITH REAL REORGS!) | |
| 810 | + | # ------------------------------------------------------------------ | |
| 811 | + | actions = [ | |
| 812 | + | "deposit", "transfer", "forced_exit", "front_paid", "front_grief", | |
| 813 | + | "exit_cancel", "take_confirmed", "release_assignment", "transfer_credit", | |
| 814 | + | "disprove_dual_slash", "lamport_equivocation_slash", "topup_op", "mine_block", "reorg", | |
| 815 | + | ] | |
| 816 | + | weights = [12, 16, 12, 12, 5, 6, 12, 5, 5, 4, 4, 10, 24, 10] | |
| 817 | + | normal_users = ["alice", "bob", "mike", "carol", "dave"] | |
| 818 | + | ||
| 819 | + | for step in range(steps): | |
| 820 | + | act = rng.choices(actions, weights=weights, k=1)[0] | |
| 821 | + | ||
| 822 | + | if act == "deposit": | |
| 823 | + | # Deliberately allow attempting deposits even near cap to exercise ticket mutual-exclusion rejection! | |
| 824 | + | u = rng.choice(normal_users) | |
| 825 | + | new_vs = [(next_vault_id + i, amt) for i, amt in enumerate(POLICY_VAULT_TIERS_SATS)] | |
| 826 | + | next_vault_id += 3 | |
| 827 | + | mine_one_block([{"kind": "deposit", "user": u, "vaults": new_vs, "mask": all_ops_mask}]) | |
| 828 | + | ||
| 829 | + | elif act == "transfer": | |
| 830 | + | rich = [u for u in normal_users if users[u] >= POLICY_MIN_EXIT_SATS] | |
| 831 | + | if rich: | |
| 832 | + | src = rng.choice(rich) | |
| 833 | + | dst = rng.choice([u for u in normal_users if u != src]) | |
| 834 | + | amt = rng.randint(POLICY_MIN_EXIT_SATS, min(users[src], 50_000_000)) | |
| 835 | + | users[src] -= amt | |
| 836 | + | users[dst] += amt | |
| 837 | + | counts["transfer"] += 1 | |
| 838 | + | ||
| 839 | + | elif act == "forced_exit": | |
| 840 | + | rich = [u for u in normal_users if users[u] >= 10_000_000] | |
| 841 | + | if rich: | |
| 842 | + | u = rng.choice(rich) | |
| 843 | + | choices = [10_000_000, 25_000_000, 50_000_000] | |
| 844 | + | valid = [c for c in choices if users[u] >= c] | |
| 845 | + | amt = rng.choice(valid) | |
| 846 | + | eid = next_exit_id | |
| 847 | + | next_exit_id += 1 | |
| 848 | + | mine_one_block([{"kind": "forced_exit", "user": u, "gross": amt, "exit_id": eid}]) | |
| 849 | + | ||
| 850 | + | elif act == "front_paid": | |
| 851 | + | open_exits = [eid for eid in pending_exits if eid not in unconf_spent_exits] | |
| 852 | + | active_ops = [oid for oid, op in operators.items() if not op["suspended"]] | |
| 853 | + | if open_exits and active_ops: | |
| 854 | + | eid = rng.choice(open_exits) | |
| 855 | + | oid = rng.choice(active_ops) | |
| 856 | + | unconf_spent_exits.add(eid) | |
| 857 | + | mine_one_block([{"kind": "front_paid", "exit_id": eid, "op_id": oid}]) | |
| 858 | + | ||
| 859 | + | elif act == "front_grief": | |
| 860 | + | open_exits = [eid for eid in pending_exits if eid not in unconf_spent_exits] | |
| 861 | + | active_ops = [oid for oid, op in operators.items() if not op["suspended"] and op["b_grief"] > 0] | |
| 862 | + | if open_exits and active_ops: | |
| 863 | + | eid = rng.choice(open_exits) | |
| 864 | + | oid = rng.choice(active_ops) | |
| 865 | + | unconf_spent_exits.add(eid) | |
| 866 | + | mine_one_block([{"kind": "front_grief", "exit_id": eid, "op_id": oid}]) | |
| 867 | + | ||
| 868 | + | elif act == "exit_cancel": | |
| 869 | + | cur_h = current_tip_height() | |
| 870 | + | expired = [ | |
| 871 | + | eid for eid, ex in pending_exits.items() | |
| 872 | + | if eid not in unconf_spent_exits and cur_h >= ex["created_h"] + POLICY_T_EXIT_CANCEL | |
| 873 | + | ] | |
| 874 | + | if expired: | |
| 875 | + | eid = rng.choice(expired) | |
| 876 | + | unconf_spent_exits.add(eid) | |
| 877 | + | mine_one_block([{"kind": "exit_cancel", "exit_id": eid}]) | |
| 878 | + | ||
| 879 | + | elif act == "take_confirmed": | |
| 880 | + | ready = [ | |
| 881 | + | (vid, info["op_id"]) for vid, info in assigned_vaults.items() | |
| 882 | + | if vid not in unconf_taken_vaults and vid not in unconf_released_vaults | |
| 883 | + | ] | |
| 884 | + | if ready: | |
| 885 | + | vid, oid = rng.choice(ready) | |
| 886 | + | unconf_taken_vaults.add(vid) | |
| 887 | + | mine_one_block([{"kind": "take_confirmed", "op_id": oid, "vault_id": vid}]) | |
| 888 | + | ||
| 889 | + | elif act == "release_assignment": | |
| 890 | + | ready = [ | |
| 891 | + | (vid, info["op_id"]) for vid, info in assigned_vaults.items() | |
| 892 | + | if vid not in unconf_taken_vaults and vid not in unconf_released_vaults | |
| 893 | + | ] | |
| 894 | + | if ready: | |
| 895 | + | vid, oid = rng.choice(ready) | |
| 896 | + | unconf_released_vaults.add(vid) | |
| 897 | + | mine_one_block([{"kind": "release_assignment", "op_id": oid, "vault_id": vid}]) | |
| 898 | + | ||
| 899 | + | elif act == "transfer_credit": | |
| 900 | + | donors = [oid for oid, op in operators.items() if 0 < op["credit"] < 25_000_000] | |
| 901 | + | if donors: | |
| 902 | + | src = rng.choice(donors) | |
| 903 | + | dst = rng.choice([i for i in operators if i != src]) | |
| 904 | + | mine_one_block([{"kind": "transfer_credit", "from_op": src, "to_op": dst, "amount": operators[src]["credit"]}]) | |
| 905 | + | ||
| 906 | + | elif act == "disprove_dual_slash": | |
| 907 | + | active_ops = [oid for oid, op in operators.items() if not op["suspended"]] | |
| 908 | + | if active_ops: | |
| 909 | + | oid = rng.choice(active_ops) | |
| 910 | + | mine_one_block([{"kind": "disprove_dual_slash", "op_id": oid}]) | |
| 911 | + | ||
| 912 | + | elif act == "lamport_equivocation_slash": | |
| 913 | + | all_vids = [ | |
| 914 | + | vid for vid in list(unassigned_vaults.keys()) + list(assigned_vaults.keys()) | |
| 915 | + | if vid not in unconf_taken_vaults | |
| 916 | + | ] | |
| 917 | + | active_ops = [ | |
| 918 | + | oid for oid, op in operators.items() | |
| 919 | + | if not op["suspended"] and op["b_custody"] >= POLICY_B_CUSTODY_TOTAL_SATS | |
| 920 | + | ] | |
| 921 | + | if all_vids and active_ops: | |
| 922 | + | oid = rng.choice(active_ops) | |
| 923 | + | vid = rng.choice(all_vids) | |
| 924 | + | unconf_taken_vaults.add(vid) | |
| 925 | + | mine_one_block([{"kind": "lamport_equivocation_slash", "op_id": oid, "vault_id": vid}]) | |
| 926 | + | ||
| 927 | + | elif act == "topup_op": | |
| 928 | + | susp = [oid for oid, op in operators.items() if op["suspended"]] | |
| 929 | + | if susp: | |
| 930 | + | oid = rng.choice(susp) | |
| 931 | + | op = operators[oid] | |
| 932 | + | need_c = max(0, POLICY_B_CUSTODY_TOTAL_SATS - op["b_custody"]) | |
| 933 | + | need_g = max(0, POLICY_B_GRIEF_TOTAL_SATS - op["b_grief"]) | |
| 934 | + | needed = need_c + need_g | |
| 935 | + | if op["free_zbtc"] >= needed: | |
| 936 | + | op["free_zbtc"] -= needed | |
| 937 | + | op["b_custody"] += need_c | |
| 938 | + | op["b_grief"] += need_g | |
| 939 | + | op["suspended"] = False | |
| 940 | + | counts["topup_op"] += 1 | |
| 941 | + | elif ticket_pool[50_000_000] >= 2: | |
| 942 | + | ticket_pool[50_000_000] -= 2 | |
| 943 | + | for _ in range(2): | |
| 944 | + | unassigned_vaults[next_vault_id] = {"sats": 50_000_000, "mask": all_ops_mask} | |
| 945 | + | next_vault_id += 1 | |
| 946 | + | op["free_zbtc"] += SAT - needed | |
| 947 | + | op["b_custody"] += need_c | |
| 948 | + | op["b_grief"] += need_g | |
| 949 | + | op["suspended"] = False | |
| 950 | + | counts["topup_op"] += 1 | |
| 951 | + | ||
| 952 | + | elif act == "mine_block": | |
| 953 | + | mine_one_block([]) | |
| 954 | + | ||
| 955 | + | elif act == "reorg": | |
| 956 | + | if tip_blocks: | |
| 957 | + | depth = rng.randint(1, min(K - 1, len(tip_blocks))) | |
| 958 | + | orphaned = tip_blocks[-depth:] | |
| 959 | + | del tip_blocks[-depth:] | |
| 960 | + | ev_reverted = sum(len(b["events"]) for b in orphaned) | |
| 961 | + | counts["reorg"] += 1 | |
| 962 | + | counts["reorg_blocks_reverted"] += depth | |
| 963 | + | counts["reorg_events_reverted"] += ev_reverted | |
| 964 | + | rebuild_unconf_locks() | |
| 965 | + | for _ in range(depth): | |
| 966 | + | mine_one_block([]) | |
| 967 | + | ||
| 968 | + | assert_solvency(f"step_{step}_{act}") | |
| 969 | + | ||
| 970 | + | # Guarantee EXIT_CANCEL path is exercised if random steps didn't hit a 288-block idle exit | |
| 971 | + | if counts["exit_cancel"] == 0: | |
| 972 | + | u = next((u for u in normal_users if users[u] >= 25_000_000), "insurance_pool") | |
| 973 | + | eid = next_exit_id | |
| 974 | + | next_exit_id += 1 | |
| 975 | + | mine_one_block([{"kind": "forced_exit", "user": u, "gross": 25_000_000, "exit_id": eid}]) | |
| 976 | + | for _ in range(K + POLICY_T_EXIT_CANCEL): | |
| 977 | + | mine_one_block([]) | |
| 978 | + | mine_one_block([{"kind": "exit_cancel", "exit_id": eid}]) | |
| 979 | + | for _ in range(K): | |
| 980 | + | mine_one_block([]) | |
| 981 | + | assert_solvency("post_exit_cancel") | |
| 982 | + | ||
| 983 | + | # Guarantee ticket-cap deposit-race rejection was exercised | |
| 984 | + | if counts["deposit_race_blocked_by_ticket"] == 0: | |
| 985 | + | # Attempt a massive burst of deposits past the remaining ticket cap | |
| 986 | + | for _ in range(25): | |
| 987 | + | new_vs = [(next_vault_id + i, amt) for i, amt in enumerate(POLICY_VAULT_TIERS_SATS)] | |
| 988 | + | next_vault_id += 3 | |
| 989 | + | mine_one_block([{"kind": "deposit", "user": "alice", "vaults": new_vs, "mask": all_ops_mask}]) | |
| 990 | + | for _ in range(K): | |
| 991 | + | mine_one_block([]) | |
| 992 | + | assert_solvency("post_ticket_race") | |
| 993 | + | ||
| 994 | + | # Flush remaining tip blocks to K-deep finality | |
| 995 | + | for _ in range(K): | |
| 996 | + | mine_one_block([]) | |
| 997 | + | assert_solvency("final") | |
| 998 | + | return counts | |
| 999 | + | ||
| 1000 | + | ||
| 1001 | + | # ============================================================================== | |
| 1002 | + | # MAIN ASSERTION SUITE | |
| 1003 | + | # ============================================================================== | |
| 1004 | + | def main() -> None: | |
| 1005 | + | print("================================================================================") | |
| 1006 | + | print("zBTC v2 (v3.1.0-rfc — R8 HARDENED) ZERO-FEDERATION CONSISTENCY & BOUNDS CHECKER") | |
| 1007 | + | print("Note: Pure Python 3 stdlib. Checks internal consistency against SOURCED_,") | |
| 1008 | + | print(" POLICY_, and PRE_MAINNET_TARGET_ inputs. Not an empirical Signet benchmark.") | |
| 1009 | + | print("================================================================================") | |
| 1010 | + | ||
| 1011 | + | # -------------------------------------------------------------------------- | |
| 1012 | + | # 1. STAGE 0: COINBASE MIDSTATE 1-/2-BLOCK PADDING & >= 65 B FILTER (R8-M06) | |
| 1013 | + | # -------------------------------------------------------------------------- | |
| 1014 | + | print("\n=== 1. STAGE 0: COINBASE MIDSTATE 1-/2-BLOCK SHA-256 PADDING & >= 65 B FILTER ===") | |
| 1015 | + | one_blk_count, two_blk_count = 0, 0 | |
| 1016 | + | for rem in range(64): | |
| 1017 | + | total_len = 128 + rem | |
| 1018 | + | cb_bytes = bytes((i * 37 + rem) & 0xFF for i in range(total_len)) | |
| 1019 | + | st = sha256_compress(sha256_compress(_SHA256_IV, cb_bytes[0:64]), cb_bytes[64:128]) | |
| 1020 | + | midstate = struct.pack(">8I", *st) | |
| 1021 | + | got_txid, final_blks = complete_midstate_double_sha256(midstate, cb_bytes[128:], total_len) | |
| 1022 | + | assert got_txid == hashlib.sha256(hashlib.sha256(cb_bytes).digest()).digest() | |
| 1023 | + | if rem < 56: | |
| 1024 | + | assert final_blks == 1 | |
| 1025 | + | one_blk_count += 1 | |
| 1026 | + | else: | |
| 1027 | + | assert final_blks == 2 | |
| 1028 | + | two_blk_count += 1 | |
| 1029 | + | assert one_blk_count == 56 and two_blk_count == 8 | |
| 1030 | + | for bad_len in (0, 32, 63, 64): | |
| 1031 | + | try: | |
| 1032 | + | complete_midstate_double_sha256(b"\x00" * 32, b"\x00" * (bad_len % 64), bad_len) | |
| 1033 | + | raise AssertionError(f"Length {bad_len} must be rejected!") | |
| 1034 | + | except AssertionError as e: | |
| 1035 | + | assert "CVE-2017-12842" in str(e) | |
| 1036 | + | print( | |
| 1037 | + | f" Verified 64/64 remainders vs hashlib double-SHA256 ({one_blk_count} 1-blk, {two_blk_count} 2-blk = 12.5%); " | |
| 1038 | + | f"all len <= 64 rejected (min strippedTx = {POLICY_STAGE0_MIN_STRIPPED_TX_BYTES} B)." | |
| 1039 | + | ) | |
| 1040 | + | ||
| 1041 | + | # -------------------------------------------------------------------------- | |
| 1042 | + | # 2. STAGE 0: go-zenon THROUGHPUT, SPV ORACLE & BITCOIN L1 0x02 DA CEILING (R8-M08) | |
| 1043 | + | # -------------------------------------------------------------------------- | |
| 1044 | + | print("\n=== 2. STAGE 0: go-zenon PLASMA / 8 MiB CEILING vs BITCOIN L1 0x02 DA CAP ===") | |
| 1045 | + | rollup_tx_plasma = SOURCED_ZNN_ACCOUNT_BLOCK_BASE_PLASMA + PRE_MAINNET_TARGET_ROLLUP_TX_DATA_BYTES * SOURCED_ZNN_AB_BYTE_DATA_PLASMA | |
| 1046 | + | assert rollup_tx_plasma == 28_480 | |
| 1047 | + | assert ceil_div(rollup_tx_plasma, SOURCED_ZNN_PLASMA_PER_QSR) == 14 | |
| 1048 | + | ||
| 1049 | + | tps_floor_2blk = (POLICY_PINNED_MAX_BASE_PLASMA_FLOOR / SOURCED_ZNN_ACCOUNT_BLOCK_BASE_PLASMA / 2.0) / SOURCED_ZNN_OBSERVED_MOMENTUM_SECS | |
| 1050 | + | tps_default_2blk = (SOURCED_ZNN_DP_DEFAULT_MAX_BASE_PLASMA / SOURCED_ZNN_ACCOUNT_BLOCK_BASE_PLASMA / 2.0) / SOURCED_ZNN_OBSERVED_MOMENTUM_SECS | |
| 1051 | + | rollup_tps_floor_114 = (POLICY_PINNED_MAX_BASE_PLASMA_FLOOR / rollup_tx_plasma) / SOURCED_ZNN_OBSERVED_MOMENTUM_SECS | |
| 1052 | + | rollup_tps_default_114 = (SOURCED_ZNN_DP_DEFAULT_MAX_BASE_PLASMA / rollup_tx_plasma) / SOURCED_ZNN_OBSERVED_MOMENTUM_SECS | |
| 1053 | + | rollup_tps_floor_10s = (POLICY_PINNED_MAX_BASE_PLASMA_FLOOR / rollup_tx_plasma) / 10.0 | |
| 1054 | + | real_tps_low = ((SOURCED_ZNN_MAX_DETAILED_MOMENTUM_WIRE // SOURCED_ZNN_MIN_ACCOUNT_BLOCK_WIRE_HIGH) / 2.0) / SOURCED_ZNN_OBSERVED_MOMENTUM_SECS | |
| 1055 | + | real_tps_high = ((SOURCED_ZNN_MAX_DETAILED_MOMENTUM_WIRE // SOURCED_ZNN_MIN_ACCOUNT_BLOCK_WIRE_LOW) / 2.0) / SOURCED_ZNN_OBSERVED_MOMENTUM_SECS | |
| 1056 | + | assert 4.3 < tps_floor_2blk < 4.5 and 8.7 < tps_default_2blk < 8.9 | |
| 1057 | + | assert 6.3 < rollup_tps_floor_114 < 6.6 and 12.8 < rollup_tps_default_114 < 13.1 | |
| 1058 | + | assert 7.36 < rollup_tps_floor_10s < 7.38 | |
| 1059 | + | assert 1_000 < real_tps_low < 1_100 and 1_200 < real_tps_high < 1_260 | |
| 1060 | + | ||
| 1061 | + | # Bitcoin L1 physical 0x02 mutated-leaf DA ceilings (R8-M08) | |
| 1062 | + | btc_max_vb_per_sec = (SOURCED_BTC_MAX_BLOCK_WEIGHT / 4.0) / SOURCED_BTC_TARGET_BLOCK_SECS # 1,666.67 vB/s | |
| 1063 | + | da_blended_10vb_100pct = btc_max_vb_per_sec / 10.0 # 166.67 leaves/s @ 100% Bitcoin blockspace | |
| 1064 | + | da_existing_4vb_100pct = btc_max_vb_per_sec / 4.0 # 416.67 existing 16B leaves/s @ 100% | |
| 1065 | + | da_new_12vb_100pct = btc_max_vb_per_sec / 12.0 # 138.89 new 48B leaves/s @ 100% | |
| 1066 | + | da_epoch_new_leaf_cap_per_sec = POLICY_MAX_NEW_LEAVES_PER_EPOCH / (6.0 * SOURCED_BTC_TARGET_BLOCK_SECS) | |
| 1067 | + | assert abs(da_blended_10vb_100pct - 166.6666667) < 1e-4 | |
| 1068 | + | assert abs(da_existing_4vb_100pct - 416.6666667) < 1e-4 | |
| 1069 | + | assert da_epoch_new_leaf_cap_per_sec < 0.30 | |
| 1070 | + | ||
| 1071 | + | # Stage 0 SPV Oracle ABI + Dynamic Plasma 5-param pinning | |
| 1072 | + | prove_payload = 8 + 4 + 4 + 32 + POLICY_STAGE0_MAX_STRIPPED_TX_BYTES + 16 * 32 + 63 + 16 * 32 | |
| 1073 | + | prove_abi = (4 + 8 * 32) + (32 + POLICY_STAGE0_MAX_STRIPPED_TX_BYTES) + (32 + 16 * 32) + (32 + 64) + (32 + 16 * 32) | |
| 1074 | + | assert prove_payload == 7_279 and prove_abi == 7_620 | |
| 1075 | + | prove_plasma = abi_embedded_plasma(SOURCED_ZNN_EMBEDDED_HEAVY_SPV_TIER, prove_abi) | |
| 1076 | + | assert prove_plasma == 591_388 and POLICY_PINNED_MAX_BASE_PLASMA_FLOOR >= 3 * prove_plasma | |
| 1077 | + | assert POLICY_PINNED_MAX_BASE_PLASMA_FLOOR // SOURCED_ZNN_EMBEDDED_SIMPLE_TIER == 40 | |
| 1078 | + | ||
| 1079 | + | price_unpinned, price_pinned = SOURCED_ZNN_MIN_RESOURCE_PRICE, SOURCED_ZNN_MIN_RESOURCE_PRICE | |
| 1080 | + | pinned_target = (POLICY_PINNED_MAX_BASE_PLASMA_FLOOR * POLICY_PINNED_MIN_TARGET_SHARE_PCT) // 100 | |
| 1081 | + | assert pinned_target == 525_000 | |
| 1082 | + | for _ in range(52): | |
| 1083 | + | price_unpinned = dp_next_price(price_unpinned, 21_000, 1, POLICY_PINNED_MAX_PRICE_CHANGE_PCT, 1) | |
| 1084 | + | price_pinned = dp_next_price(price_pinned, 21_000, pinned_target, POLICY_PINNED_MAX_PRICE_CHANGE_PCT, POLICY_PINNED_MIN_PRICE_DENOM) | |
| 1085 | + | assert price_unpinned / 1_000 > 100_000 and price_pinned == 1_000 | |
| 1086 | + | print( | |
| 1087 | + | f" Zenon @ 11.4s: 2-blk={tps_floor_2blk:.1f}/{tps_default_2blk:.1f} tx/s | " | |
| 1088 | + | f"1-blk rollup={rollup_tps_floor_114:.1f}/{rollup_tps_default_114:.1f} tx/s ({rollup_tps_floor_10s:.2f} @ 10s) | " | |
| 1089 | + | f"8 MiB cap={real_tps_low:,.0f}-{real_tps_high:,.0f} tx/s" | |
| 1090 | + | ) | |
| 1091 | + | print( | |
| 1092 | + | f" Bitcoin L1 0x02 DA cap @ 100% blockspace: blended(10vB)={da_blended_10vb_100pct:.1f} leaves/s " | |
| 1093 | + | f"(1%={da_blended_10vb_100pct/100:.2f}/s) | existing(4vB)={da_existing_4vb_100pct:.1f}/s | " | |
| 1094 | + | 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)" | |
| 1095 | + | ) | |
| 1096 | + | ||
| 1097 | + | # -------------------------------------------------------------------------- | |
| 1098 | + | # 3. STAGE 0: EXACT ERLANG TAILS FOR PTLC (>= 48h) & LN HTLC (>= 24h) (R8-H07) | |
| 1099 | + | # -------------------------------------------------------------------------- | |
| 1100 | + | print("\n=== 3. STAGE 0: EXACT STDLIB ERLANG TAILS FOR PTLC (>= 48h) & LN HTLC (>= 24h) ===") | |
| 1101 | + | mean_1x = SOURCED_BTC_TARGET_BLOCK_SECS | |
| 1102 | + | mean_2p3x = SOURCED_BTC_TARGET_BLOCK_SECS * SOURCED_JUNE2021_SLOW_DAILY_MULT # 1,380 s/blk | |
| 1103 | + | # Regression-verify R8-H07's exact failure probabilities on old v3.0.0 values: | |
| 1104 | + | old_ptlc_fail = erlang_survival_prob(72, 30 * 3600, mean_2p3x) | |
| 1105 | + | old_ln_fail = erlang_survival_prob(36, 6 * 3600, mean_1x) | |
| 1106 | + | assert abs(old_ptlc_fail - 0.2234) < 0.002, f"Expected ~22.34%, got {old_ptlc_fail:.4%}" | |
| 1107 | + | assert abs(old_ln_fail - 0.4778) < 0.002, f"Expected ~47.78%, got {old_ln_fail:.4%}" | |
| 1108 | + | # Verify hardened v3.1.0-rfc margins: | |
| 1109 | + | new_ptlc_fail = erlang_survival_prob(POLICY_PTLC_BTC_CSV_BLOCKS, POLICY_PTLC_ZNN_DURATION_SECS, mean_2p3x) | |
| 1110 | + | ptlc_p999_h = erlang_quantile_hours(POLICY_PTLC_BTC_CSV_BLOCKS, 0.999, mean_2p3x) | |
| 1111 | + | new_ln_fail_2p3x = erlang_survival_prob(POLICY_LN_DELTA_SAFETY_BLOCKS, POLICY_LN_OUTBOUND_DELTA_SAFETY_SECS, mean_2p3x) | |
| 1112 | + | new_ln_fail_1x = erlang_survival_prob(POLICY_LN_DELTA_SAFETY_BLOCKS, POLICY_LN_OUTBOUND_DELTA_SAFETY_SECS, mean_1x) | |
| 1113 | + | ln_p999_h = erlang_quantile_hours(POLICY_LN_DELTA_SAFETY_BLOCKS, 0.999, mean_2p3x) | |
| 1114 | + | assert new_ptlc_fail < 1e-6 and ptlc_p999_h < 39.0 | |
| 1115 | + | assert new_ln_fail_2p3x < 2e-4 and new_ln_fail_1x < 1e-18 and ln_p999_h < 22.5 | |
| 1116 | + | print( | |
| 1117 | + | f" PTLC (72 blks @ 2.3x): old 30h fail={old_ptlc_fail:.2%} -> NEW 48h fail={new_ptlc_fail:.2e} " | |
| 1118 | + | f"(p99.9={ptlc_p999_h:.2f}h, margin={48.0 - ptlc_p999_h:.2f}h; block-72 RBF watchtower)" | |
| 1119 | + | ) | |
| 1120 | + | print( | |
| 1121 | + | f" LN Outbound (36 blks): old 6h@1x fail={old_ln_fail:.2%} -> NEW 24h@2.3x fail={new_ln_fail_2p3x:.2e} " | |
| 1122 | + | f"(p99.9={ln_p999_h:.2f}h, @1x fail={new_ln_fail_1x:.2e})" | |
| 1123 | + | ) | |
| 1124 | + | ||
| 1125 | + | # -------------------------------------------------------------------------- | |
| 1126 | + | # 4. STAGE 1A: COMPLETE HARD-BTC CAPITAL ACCOUNTING (R8-M09, R8-H02) | |
| 1127 | + | # -------------------------------------------------------------------------- | |
| 1128 | + | print("\n=== 4. STAGE 1A: COMPLETE HARD-BTC CAPITAL (LOCKED vs OPERATIONAL vs MULTI-DISPUTE) ===") | |
| 1129 | + | bitvm2_m3_low = 3 * PRE_MAINNET_TARGET_BITVM2_LANE_BOND_BTC_LOW | |
| 1130 | + | bitvm2_m5_high = 5 * PRE_MAINNET_TARGET_BITVM2_LANE_BOND_BTC_HIGH | |
| 1131 | + | assert bitvm2_m3_low > SOURCED_ZNN_MCAP_BTC_HIGH | |
| 1132 | + | verifier_standby_btc = (POLICY_BITVMX_N_VERIFIERS * POLICY_F_CHAL_SATS) / SAT | |
| 1133 | + | verifier_cpfp_res_btc = POLICY_BITVMX_N_VERIFIERS * POLICY_OP_RESERVE_VERIFIER_CPFP_PER_V_BTC | |
| 1134 | + | assert abs(verifier_standby_btc - 2.80) < 1e-9 and abs(verifier_cpfp_res_btc - 0.70) < 1e-9 | |
| 1135 | + | ||
| 1136 | + | for label, prof in POLICY_STAGE1A_PROFILES.items(): | |
| 1137 | + | m = prof["M"] | |
| 1138 | + | bonds_btc = (m * POLICY_BITVMX_L_LANES * POLICY_LANE_TOTAL_BOND_SATS) / SAT | |
| 1139 | + | locked_btc = bonds_btc + prof["float_btc"] + verifier_standby_btc | |
| 1140 | + | op_reserves = verifier_cpfp_res_btc + POLICY_OP_RESERVE_DA_BATCHER_BTC + m * POLICY_OP_RESERVE_TOPUP_PER_OP_BTC | |
| 1141 | + | op_baseline = locked_btc + op_reserves | |
| 1142 | + | per_verifier_m_disputes = m * ((POLICY_F_CHAL_SATS / SAT) + 0.08265) | |
| 1143 | + | pct_low = 100.0 * op_baseline / SOURCED_ZNN_MCAP_BTC_HIGH | |
| 1144 | + | pct_high = 100.0 * op_baseline / SOURCED_ZNN_MCAP_BTC_LOW | |
| 1145 | + | if m == 3: | |
| 1146 | + | assert abs(locked_btc - 12.80) < 1e-9 and abs(op_baseline - 14.75) < 1e-9 | |
| 1147 | + | if m == 5: | |
| 1148 | + | assert abs(locked_btc - 18.80) < 1e-9 and abs(op_baseline - 21.25) < 1e-9 | |
| 1149 | + | print( | |
| 1150 | + | f" {label:28s}: locked={locked_btc:5.2f} + op_res={op_reserves:4.2f} = {op_baseline:5.2f} BTC " | |
| 1151 | + | f"({pct_low:.1f}%-{pct_high:.1f}% ZNN mcap) | M-dispute/honest-V={per_verifier_m_disputes:.2f} BTC" | |
| 1152 | + | ) | |
| 1153 | + | 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}") | |
| 1154 | + | ||
| 1155 | + | # -------------------------------------------------------------------------- | |
| 1156 | + | # 5. STAGE 1A: BitVMX n=8 BISECTION, 10x153 vB CPFP & TRUC v3 (R8-H04/H05) | |
| 1157 | + | # -------------------------------------------------------------------------- | |
| 1158 | + | print("\n=== 5. STAGE 1A: BitVMX-CPU n=8 WRAPPED-SNARK VERIFIER & P2A CPFP TRUC v3 ===") | |
| 1159 | + | digits_per_prover_tx = (POLICY_BITVMX_N_BRANCH - 1) * (40 + 3) | |
| 1160 | + | assert digits_per_prover_tx == 301 | |
| 1161 | + | prover_step_vb = math.ceil(digits_per_prover_tx * PRE_MAINNET_TARGET_WOTS_DIGIT_WU) / 4.0 + PRE_MAINNET_TARGET_BISECTION_OVERHEAD_VB | |
| 1162 | + | assert abs(prover_step_vb - 7_436.5) < 1e-9 | |
| 1163 | + | assert prover_step_vb <= SOURCED_BIP431_TRUC_MAX_VB | |
| 1164 | + | assert prover_step_vb > SOURCED_BIP431_TRUC_CHILD_MAX_VB # Confirms zero unconfirmed TRUC child chaining! | |
| 1165 | + | ||
| 1166 | + | cpfp_side_vb = PRE_MAINNET_TARGET_CPFP_COUNT_PER_SIDE * SOURCED_P2A_CPFP_CHILD_VB | |
| 1167 | + | assert cpfp_side_vb == 1_530 and SOURCED_P2A_CPFP_CHILD_VB <= SOURCED_BIP431_TRUC_CHILD_MAX_VB | |
| 1168 | + | prover_total_with_cpfp_vb = PRE_MAINNET_TARGET_PROVER_BASE_CAP_VB + cpfp_side_vb # 76,530 vB | |
| 1169 | + | verifier_total_with_cpfp_vb = PRE_MAINNET_TARGET_VERIFIER_BASE_CAP_VB + cpfp_side_vb # 16,530 vB | |
| 1170 | + | assert prover_total_with_cpfp_vb == 76_530 and verifier_total_with_cpfp_vb == 16_530 | |
| 1171 | + | ||
| 1172 | + | prover_fee_500 = prover_total_with_cpfp_vb * POLICY_DESIGN_SUSTAINED_FEE_SATVB | |
| 1173 | + | prover_breakeven = POLICY_F_CHAL_SATS // prover_total_with_cpfp_vb | |
| 1174 | + | verifier_fee_500 = verifier_total_with_cpfp_vb * POLICY_DESIGN_SUSTAINED_FEE_SATVB | |
| 1175 | + | verifier_fee_750 = verifier_total_with_cpfp_vb * POLICY_STRESS_SUSTAINED_FEE_SATVB | |
| 1176 | + | assert prover_fee_500 == 38_265_000 <= POLICY_F_CHAL_SATS and prover_breakeven == 522 | |
| 1177 | + | assert verifier_fee_500 == 8_265_000 and verifier_fee_750 == 12_397_500 | |
| 1178 | + | seq_steps = 1 + 2 * POLICY_BITVMX_SEARCH_ROUNDS + 1 | |
| 1179 | + | assert seq_steps == 20 and POLICY_BITVMX_N_BRANCH ** POLICY_BITVMX_SEARCH_ROUNDS == 134_217_728 | |
| 1180 | + | print( | |
| 1181 | + | f" Prover step={prover_step_vb:,.1f} vB <= 10k TRUC parent (>1k child -> confirmed parents only!) | " | |
| 1182 | + | f"Prover w/ 10x153 CPFP={prover_total_with_cpfp_vb:,} vB ({prover_fee_500/SAT:.5f} BTC <= 0.40, BE={prover_breakeven} sat/vB)" | |
| 1183 | + | ) | |
| 1184 | + | print( | |
| 1185 | + | 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" | |
| 1186 | + | ) | |
| 1187 | + | ||
| 1188 | + | # -------------------------------------------------------------------------- | |
| 1189 | + | # 6. STAGE 1A: WIDENED TIMELOCKS & ACYCLIC vault_id LAMPORT TakeTx (R8-C01) | |
| 1190 | + | # -------------------------------------------------------------------------- | |
| 1191 | + | print("\n=== 6. STAGE 1A: WIDENED TIMELOCKS (T_step=72) & ACYCLIC vault_id LAMPORT TakeTx ===") | |
| 1192 | + | max_dispute_end = POLICY_T_CHAL_WINDOW + seq_steps * POLICY_T_STEP | |
| 1193 | + | assert max_dispute_end == 1_584 | |
| 1194 | + | assert POLICY_T_TAKE == 1_728 and POLICY_T_TAKE - max_dispute_end == 144 | |
| 1195 | + | assert POLICY_T_COOLDOWN == 1_872 and POLICY_T_COOLDOWN - POLICY_T_TAKE == 144 | |
| 1196 | + | assert POLICY_T_RETIRE == 2_016 and POLICY_T_RETIRE - POLICY_T_COOLDOWN == 144 | |
| 1197 | + | ||
| 1198 | + | # Acyclic vault_id determinism & uniqueness across distinct vouts of same confirmed U_dep_wallet: | |
| 1199 | + | funding_txid = hashlib.sha256(b"confirmed_U_dep_wallet_txid").digest() | |
| 1200 | + | vid_0 = compute_acyclic_vault_id(funding_txid, 0, 0, 50_000_000, 0b11111) | |
| 1201 | + | vid_1 = compute_acyclic_vault_id(funding_txid, 0, 1, 25_000_000, 0b11111) | |
| 1202 | + | vid_2 = compute_acyclic_vault_id(funding_txid, 0, 2, 25_000_000, 0b11111) | |
| 1203 | + | assert len({vid_0, vid_1, vid_2}) == 3 and all(len(v) == 32 for v in (vid_0, vid_1, vid_2)) | |
| 1204 | + | ||
| 1205 | + | # Exact Lamport TakeTx size INCLUDING recycled AdmissionTicketUTXO at vout[1]! | |
| 1206 | + | lamport_script_bytes = 256 * 23 + 34 # 5,922 B | |
| 1207 | + | lamport_preimages_bytes = 256 * 21 # 5,376 B | |
| 1208 | + | cb_stage1a, cb_stage2 = 1 + 32 + 32 * 9, 1 + 32 + 32 * 12 # 321 / 417 B | |
| 1209 | + | assert lamport_script_bytes == 5_922 and lamport_preimages_bytes == 5_376 and cb_stage1a == 321 and cb_stage2 == 417 | |
| 1210 | + | # Non-witness: 10 + 2*41 (U_d + VaultConnector) + 43 (P_Op) + 43 (recycled Ticket) + 13 (P2A) = 191 B | |
| 1211 | + | take_non_wit = 10 + 2 * 41 + 43 + 43 + 13 | |
| 1212 | + | 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 | |
| 1213 | + | 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 | |
| 1214 | + | take_vb_s1 = (take_non_wit * 4 + take_wit_s1) / 4.0 | |
| 1215 | + | take_vb_s2 = (take_non_wit * 4 + take_wit_s2) / 4.0 | |
| 1216 | + | assert take_vb_s1 <= 3_200 and take_vb_s2 <= 3_200 <= SOURCED_BIP431_TRUC_MAX_VB | |
| 1217 | + | assert take_vb_s1 > SOURCED_BIP431_TRUC_CHILD_MAX_VB # Confirmed VaultConnector_r only! | |
| 1218 | + | print( | |
| 1219 | + | f" Timelocks: [0,{POLICY_T_CHAL_WINDOW}] -> max_dispute={max_dispute_end} < T_take={POLICY_T_TAKE} (12d) " | |
| 1220 | + | f"< T_cool={POLICY_T_COOLDOWN} (13d) < Retire={POLICY_T_RETIRE} (14d)" | |
| 1221 | + | ) | |
| 1222 | + | print( | |
| 1223 | + | f" Acyclic vault_id Lamport TakeTx (w/ recycled Ticket): depth9={take_vb_s1:,.2f} vB / depth12={take_vb_s2:,.2f} vB " | |
| 1224 | + | f"(<=3,200 <=10,000 TRUC parent; peak_stack=258 < 1,000)" | |
| 1225 | + | ) | |
| 1226 | + | ||
| 1227 | + | # -------------------------------------------------------------------------- | |
| 1228 | + | # 7. STAGE 1A: NATIVE-L1 Stake_r VERIFIER EV MATRIX (R8-H02, R8-N05 CLOSED!) | |
| 1229 | + | # -------------------------------------------------------------------------- | |
| 1230 | + | print("\n=== 7. STAGE 1A: NATIVE-L1 Stake_r VERIFIER EV MATRIX (0% zBTC CRISIS DISCOUNT) ===") | |
| 1231 | + | assert POLICY_BITVMX_N_VERIFIERS * POLICY_VERIFIER_NATIVE_L1_PAYOUT_SATS + POLICY_MIN_L1_STAKE_BURN_SATS == POLICY_BOND_BTC_SATS | |
| 1232 | + | assert POLICY_MIN_L1_STAKE_BURN_SATS == 95_000_000 # 0.95 BTC min burn! | |
| 1233 | + | # Native L1 payout = 0.15 BTC -> 0% haircut even at 30% (or 100%) zBTC crisis discount! | |
| 1234 | + | ev_500 = POLICY_VERIFIER_NATIVE_L1_PAYOUT_SATS - verifier_fee_500 - POLICY_VERIFIER_LOCKUP_COST_SATS | |
| 1235 | + | ev_750 = POLICY_VERIFIER_NATIVE_L1_PAYOUT_SATS - verifier_fee_750 - POLICY_VERIFIER_LOCKUP_COST_SATS | |
| 1236 | + | verifier_breakeven_satvb = (POLICY_VERIFIER_NATIVE_L1_PAYOUT_SATS - POLICY_VERIFIER_LOCKUP_COST_SATS) // verifier_total_with_cpfp_vb | |
| 1237 | + | assert ev_500 == 6_450_000 > 0 # +0.06450 BTC @ 500 sat/vB! | |
| 1238 | + | assert ev_750 == 2_317_500 > 0 # +0.023175 BTC @ 750 sat/vB! | |
| 1239 | + | assert verifier_breakeven_satvb == 890 | |
| 1240 | + | for k_collude in range(POLICY_BITVMX_N_VERIFIERS): | |
| 1241 | + | honest_n = POLICY_BITVMX_N_VERIFIERS - k_collude | |
| 1242 | + | l1_recapture = k_collude * POLICY_VERIFIER_NATIVE_L1_PAYOUT_SATS | |
| 1243 | + | l1_only_pnl = -POLICY_BOND_BTC_SATS + l1_recapture # -2.00 to -1.10 BTC on L1 ALONE! | |
| 1244 | + | total_pnl = l1_only_pnl - POLICY_B_CUSTODY_TOTAL_SATS | |
| 1245 | + | assert l1_only_pnl <= -110_000_000 and total_pnl <= -165_000_000 | |
| 1246 | + | if k_collude == 0: | |
| 1247 | + | assert l1_only_pnl == -200_000_000 and total_pnl == -255_000_000 | |
| 1248 | + | if k_collude == 6: | |
| 1249 | + | assert l1_only_pnl == -110_000_000 and total_pnl == -165_000_000 | |
| 1250 | + | print( | |
| 1251 | + | f" k_collude={k_collude} (honest={honest_n}): L1_payout=0.1500 BTC (0% zBTC discount!) | " | |
| 1252 | + | f"EV@500={ev_500/SAT:+.5f}, EV@750={ev_750/SAT:+.5f} (BE={verifier_breakeven_satvb} sat/vB) | " | |
| 1253 | + | f"Cartel L1={l1_only_pnl/SAT:+.2f} / Tot={total_pnl/SAT:+.2f} BTC" | |
| 1254 | + | ) | |
| 1255 | + | ||
| 1256 | + | # -------------------------------------------------------------------------- | |
| 1257 | + | # 8. STAGE 1A: EXACT 2^M HALL'S MARRIAGE & CYCLIC PRIORITY (R8-C04, R8-M03) | |
| 1258 | + | # -------------------------------------------------------------------------- | |
| 1259 | + | print("\n=== 8. STAGE 1A: 2^M HALL'S MARRIAGE CHECKER & CYCLIC EXIT PRIORITY ===") | |
| 1260 | + | # Demonstrate R8-C04 stranding counterexample: global cap passes (30 <= 0.5 * 220 = 110), | |
| 1261 | + | # yet 30 vaults with opBitmask={0,1} (0b00011) exceed O_0+O_1 remaining rounds (10+10=20)! | |
| 1262 | + | counterex_vaults = [0b00011] * 30 | |
| 1263 | + | counterex_rounds = [10, 10, 64, 64, 64] | |
| 1264 | + | assert len(counterex_vaults) <= 0.50 * sum(counterex_rounds) # Global scalar check falsely passed! | |
| 1265 | + | ok_bad, bad_mask, bad_dem, bad_sup = check_halls_marriage(counterex_vaults, counterex_rounds, headroom_factor=1.0) | |
| 1266 | + | assert not ok_bad and bad_mask == 0b00011 and bad_dem == 30 and bad_sup == 20 | |
| 1267 | + | # Valid Stage 1A uniform full-committee cohort passes even at 0.50 headroom: | |
| 1268 | + | ok_good, _, _, _ = check_halls_marriage([0b11111] * 45, [64] * 5, headroom_factor=0.50) | |
| 1269 | + | assert ok_good | |
| 1270 | + | ||
| 1271 | + | # Verify R8-M03 cyclic permutation has 0% collisions across 1,000 random exitIds for M=3..20: | |
| 1272 | + | for m_act in (3, 5, 10, 20): | |
| 1273 | + | for i in range(200): | |
| 1274 | + | perm = cyclic_exit_priority(f"exit_{m_act}_{i}".encode(), m_act) | |
| 1275 | + | assert len(perm) == m_act and len(set(perm)) == m_act | |
| 1276 | + | print( | |
| 1277 | + | f" Hall's 2^M counterexample CAUGHT (subset 0b{bad_mask:05b}: demand={bad_dem} > supply={bad_sup}, " | |
| 1278 | + | f"despite global 30 <= 110); uniform 45-vault M=5 cohort PASSES at 0.50 headroom." | |
| 1279 | + | ) | |
| 1280 | + | print(" Cyclic priority k_r = (H(exitId) + r) mod M_active: 0.0% collisions verified across 800 tests (M=3,5,10,20).") | |
| 1281 | + | ||
| 1282 | + | # -------------------------------------------------------------------------- | |
| 1283 | + | # 9. STAGE 1A: MULTI-TIER BANK-RUN DURATION (T_cooldown = 13.0d) | |
| 1284 | + | # -------------------------------------------------------------------------- | |
| 1285 | + | print("\n=== 9. STAGE 1A: MULTI-TIER VAULTS & 100% BANK-RUN DURATION (T_cooldown = 13.0d) ===") | |
| 1286 | + | cooldown_days = POLICY_T_COOLDOWN / SOURCED_BTC_BLOCKS_PER_DAY | |
| 1287 | + | assert abs(cooldown_days - 13.0) < 1e-9 | |
| 1288 | + | avg_multi = (sum(POLICY_VAULT_TIERS_SATS) / len(POLICY_VAULT_TIERS_SATS)) / SAT | |
| 1289 | + | avg_half = (sum(POLICY_VAULT_ALT_SPLIT_SATS) / len(POLICY_VAULT_ALT_SPLIT_SATS)) / SAT | |
| 1290 | + | for label, prof in POLICY_STAGE1A_PROFILES.items(): | |
| 1291 | + | m, cap_u, flt = prof["M"], prof["cap_user_btc"], prof["float_btc"] | |
| 1292 | + | v_per_d = m / cooldown_days | |
| 1293 | + | btc_per_d_multi = v_per_d * avg_multi | |
| 1294 | + | btc_per_d_half = v_per_d * avg_half | |
| 1295 | + | cont_multi = (cap_u - flt) / btc_per_d_multi | |
| 1296 | + | cont_half = (cap_u - flt) / btc_per_d_half | |
| 1297 | + | rem_v = int(round(cap_u / avg_multi)) - int(flt // avg_multi) | |
| 1298 | + | batch_multi = math.ceil(rem_v / m) * cooldown_days | |
| 1299 | + | if m == 3: | |
| 1300 | + | assert 101.0 <= cont_multi <= 102.0 and batch_multi == 104.0 and 67.0 <= cont_half <= 68.5 | |
| 1301 | + | if m == 5: | |
| 1302 | + | assert 93.0 <= cont_multi <= 94.5 and batch_multi == 104.0 and 62.0 <= cont_half <= 63.0 | |
| 1303 | + | print( | |
| 1304 | + | f" {label:28s}: {v_per_d:.3f} v/d ({btc_per_d_multi:.3f} BTC/d) | " | |
| 1305 | + | f"100% run=~{cont_multi:.1f}d (batch={batch_multi:.0f}d) [~{cont_half:.1f}d w/ {{0.50,0.50}}]" | |
| 1306 | + | ) | |
| 1307 | + | ||
| 1308 | + | # -------------------------------------------------------------------------- | |
| 1309 | + | # 10. K >= 18 UNPUBLISHED-FORK HEURISTIC & BUDISH SENSITIVITY (R8-H03) | |
| 1310 | + | # -------------------------------------------------------------------------- | |
| 1311 | + | print("\n=== 10. K >= 18 UNPUBLISHED-FORK HEURISTIC (Cap_user + M*B_zbtc) & BUDISH SENSITIVITY ===") | |
| 1312 | + | for cap_u, cap_tot in POLICY_TVL_TIERS_TOTAL_BTC.items(): | |
| 1313 | + | k_2024 = POLICY_CONFIGURED_K_BY_ERA["2024-2028"][cap_u] | |
| 1314 | + | assert k_2024 >= POLICY_K_MIN_FLOOR | |
| 1315 | + | row = [] | |
| 1316 | + | for era, sub in SOURCED_BTC_SUBSIDY_BY_ERA.items(): | |
| 1317 | + | k_min = max(POLICY_K_MIN_FLOOR, int(math.floor((2.0 * cap_tot) / sub)) + 1) | |
| 1318 | + | assert 0.50 * k_min * sub > cap_tot | |
| 1319 | + | if era in POLICY_CONFIGURED_K_BY_ERA: | |
| 1320 | + | k_cfg = POLICY_CONFIGURED_K_BY_ERA[era][cap_u] | |
| 1321 | + | assert k_cfg >= k_min and 0.50 * k_cfg * sub > cap_tot | |
| 1322 | + | row.append(f"{era}:K>={k_min}") | |
| 1323 | + | print(f" User={cap_u:3d} / Total={cap_tot:6.2f} BTC (2024 K={k_2024:3d}): " + " | ".join(row)) | |
| 1324 | + | # Print Budish winning-fork direct net flow-cost sensitivity at K=18, 2024-2028 (56.25 BTC nominal subsidy): | |
| 1325 | + | nom_k18 = 18 * SOURCED_BTC_SUBSIDY_BY_ERA["2024-2028"] | |
| 1326 | + | budish_str = " | ".join(f"kappa={int(k*100)}%:{k*nom_k18:.2f} BTC" for k in (0.05, 0.15, 0.30, 0.50)) | |
| 1327 | + | print(f" Budish winning-fork direct flow-cost @ K=18 (excl. BTC-price crash): {budish_str}") | |
| 1328 | + | ||
| 1329 | + | # -------------------------------------------------------------------------- | |
| 1330 | + | # 11. STAGE 1B (clArk) ALTERNATIVE GATE | |
| 1331 | + | # -------------------------------------------------------------------------- | |
| 1332 | + | print("\n=== 11. STAGE 1B (clArk) ALTERNATIVE GATE: LIQUIDITY & log2(N) BRANCH EXIT WEIGHTS ===") | |
| 1333 | + | clark_low, clark_high = PRE_MAINNET_TARGET_CLARK_ACTIVE_LIQ_BTC | |
| 1334 | + | assert clark_high < 14.75 | |
| 1335 | + | for n_vtxo in PRE_MAINNET_TARGET_CLARK_VTXO_COUNTS: | |
| 1336 | + | depth = int(math.log2(n_vtxo)) | |
| 1337 | + | total_vb = depth * 167.0 + 154.0 | |
| 1338 | + | assert total_vb < SOURCED_BIP431_TRUC_MAX_VB | |
| 1339 | + | print( | |
| 1340 | + | f" N={n_vtxo:4d} (depth={depth:2d}): exit={total_vb:6.0f} vB | " | |
| 1341 | + | f"@100={int(total_vb*100):,} sats | @500={int(total_vb*500):,} sats" | |
| 1342 | + | ) | |
| 1343 | + | ||
| 1344 | + | # -------------------------------------------------------------------------- | |
| 1345 | + | # 12. REAL 2,000-STEP STAGE 1A SIMULATION (V = C + L + E + R + A + B) | |
| 1346 | + | # -------------------------------------------------------------------------- | |
| 1347 | + | print("\n=== 12. REAL 2,000-STEP STAGE 1A SIMULATION (EXPLICIT A, TICKETS, k=20 GRIEF, REORGS) ===") | |
| 1348 | + | counts = run_stage1a_solvency_sim(seed=20261128, steps=2_000) | |
| 1349 | + | for k, v in counts.items(): | |
| 1350 | + | assert v > 0, f"Event type {k} was never exercised: {counts}" | |
| 1351 | + | assert counts["reorg_blocks_reverted"] >= counts["reorg"] > 0 and counts["reorg_events_reverted"] > 0 | |
| 1352 | + | print(" Bob, Mike, k=20 grief burst, TransferCredit, Ticket cap race & 2,000 adversarial steps PASSED V=C+L+E+R+A+B:") | |
| 1353 | + | print(" " + ", ".join(f"{k}={v}" for k, v in counts.items())) | |
| 1354 | + | print("\nALL v2 (v3.1.0-rfc R8-HARDENED ZERO-FEDERATION) CONSISTENCY, ERLANG, HALL, EV & SOLVENCY CHECKS PASSED.") | |
| 1215 | 1355 | ||
| 1216 | 1356 | ||
Run Locally
Requires only standard-library Python 3 (zero external dependencies). GitHub Actions CI executes this checker plus both archived v1 and v0 checkers on every pull request:
python3 -I scripts/verify_spec_bounds.pyDownload raw source: verify_spec_bounds.py ·oracle-output.txt ·v2 SHA256SUMS.txt ·archived v1 checker ·archived v0 oracle.
Verified Output (v2 / v3.1.0-rfc)
================================================================================
zBTC v2 (v3.1.0-rfc — R8 HARDENED) ZERO-FEDERATION CONSISTENCY & BOUNDS CHECKER
Note: Pure Python 3 stdlib. Checks internal consistency against SOURCED_,
POLICY_, and PRE_MAINNET_TARGET_ inputs. Not an empirical Signet benchmark.
================================================================================
=== 1. STAGE 0: COINBASE MIDSTATE 1-/2-BLOCK SHA-256 PADDING & >= 65 B FILTER ===
Verified 64/64 remainders vs hashlib double-SHA256 (56 1-blk, 8 2-blk = 12.5%); all len <= 64 rejected (min strippedTx = 65 B).
=== 2. STAGE 0: go-zenon PLASMA / 8 MiB CEILING vs BITCOIN L1 0x02 DA CAP ===
Zenon @ 11.4s: 2-blk=4.4/8.8 tx/s | 1-blk rollup=6.5/12.9 tx/s (7.37 @ 10s) | 8 MiB cap=1,051-1,226 tx/s
Bitcoin L1 0x02 DA cap @ 100% blockspace: blended(10vB)=166.7 leaves/s (1%=1.67/s) | existing(4vB)=416.7/s | new(12vB)=138.9/s | spam cap=1000/6-blk (0.28/s, 500-sat deposit)
=== 3. STAGE 0: EXACT STDLIB ERLANG TAILS FOR PTLC (>= 48h) & LN HTLC (>= 24h) ===
PTLC (72 blks @ 2.3x): old 30h fail=22.47% -> NEW 48h fail=9.49e-08 (p99.9=38.75h, margin=9.25h; block-72 RBF watchtower)
LN Outbound (36 blks): old 6h@1x fail=47.78% -> NEW 24h@2.3x fail=1.04e-04 (p99.9=22.01h, @1x fail=1.29e-27)
=== 4. STAGE 1A: COMPLETE HARD-BTC CAPITAL (LOCKED vs OPERATIONAL vs MULTI-DISPUTE) ===
M=3 (<=10 user / 11.8 tot) : locked=12.80 + op_res=1.95 = 14.75 BTC (44.7%-59.0% ZNN mcap) | M-dispute/honest-V=1.45 BTC
M=5 (<=15 user / 18.0 tot) : locked=18.80 + op_res=2.45 = 21.25 BTC (64.4%-85.0% ZNN mcap) | M-dispute/honest-V=2.41 BTC
BitVM2 bonds-only contrast (M=3..5): 39.90-90.875 BTC | Core floor >= 29.0
=== 5. STAGE 1A: BitVMX-CPU n=8 WRAPPED-SNARK VERIFIER & P2A CPFP TRUC v3 ===
Prover step=7,436.5 vB <= 10k TRUC parent (>1k child -> confirmed parents only!) | Prover w/ 10x153 CPFP=76,530 vB (0.38265 BTC <= 0.40, BE=522 sat/vB)
Verifier w/ 10x153 CPFP=16,530 vB: @500=0.08265 BTC, @750=0.12398 BTC
=== 6. STAGE 1A: WIDENED TIMELOCKS (T_step=72) & ACYCLIC vault_id LAMPORT TakeTx ===
Timelocks: [0,144] -> max_dispute=1584 < T_take=1728 (12d) < T_cool=1872 (13d) < Retire=2016 (14d)
Acyclic vault_id Lamport TakeTx (w/ recycled Ticket): depth9=3,141.75 vB / depth12=3,165.75 vB (<=3,200 <=10,000 TRUC parent; peak_stack=258 < 1,000)
=== 7. STAGE 1A: NATIVE-L1 Stake_r VERIFIER EV MATRIX (0% zBTC CRISIS DISCOUNT) ===
k_collude=0 (honest=7): L1_payout=0.1500 BTC (0% zBTC discount!) | EV@500=+0.06450, EV@750=+0.02318 (BE=890 sat/vB) | Cartel L1=-2.00 / Tot=-2.55 BTC
k_collude=1 (honest=6): L1_payout=0.1500 BTC (0% zBTC discount!) | EV@500=+0.06450, EV@750=+0.02318 (BE=890 sat/vB) | Cartel L1=-1.85 / Tot=-2.40 BTC
k_collude=2 (honest=5): L1_payout=0.1500 BTC (0% zBTC discount!) | EV@500=+0.06450, EV@750=+0.02318 (BE=890 sat/vB) | Cartel L1=-1.70 / Tot=-2.25 BTC
k_collude=3 (honest=4): L1_payout=0.1500 BTC (0% zBTC discount!) | EV@500=+0.06450, EV@750=+0.02318 (BE=890 sat/vB) | Cartel L1=-1.55 / Tot=-2.10 BTC
k_collude=4 (honest=3): L1_payout=0.1500 BTC (0% zBTC discount!) | EV@500=+0.06450, EV@750=+0.02318 (BE=890 sat/vB) | Cartel L1=-1.40 / Tot=-1.95 BTC
k_collude=5 (honest=2): L1_payout=0.1500 BTC (0% zBTC discount!) | EV@500=+0.06450, EV@750=+0.02318 (BE=890 sat/vB) | Cartel L1=-1.25 / Tot=-1.80 BTC
k_collude=6 (honest=1): L1_payout=0.1500 BTC (0% zBTC discount!) | EV@500=+0.06450, EV@750=+0.02318 (BE=890 sat/vB) | Cartel L1=-1.10 / Tot=-1.65 BTC
=== 8. STAGE 1A: 2^M HALL'S MARRIAGE CHECKER & CYCLIC EXIT PRIORITY ===
Hall's 2^M counterexample CAUGHT (subset 0b00011: demand=30 > supply=20, despite global 30 <= 110); uniform 45-vault M=5 cohort PASSES at 0.50 headroom.
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 VAULTS & 100% BANK-RUN DURATION (T_cooldown = 13.0d) ===
M=3 (<=10 user / 11.8 tot) : 0.231 v/d (0.077 BTC/d) | 100% run=~101.4d (batch=104d) [~67.6d w/ {0.50,0.50}]
M=5 (<=15 user / 18.0 tot) : 0.385 v/d (0.128 BTC/d) | 100% run=~93.6d (batch=104d) [~62.4d w/ {0.50,0.50}]
=== 10. K >= 18 UNPUBLISHED-FORK HEURISTIC (Cap_user + M*B_zbtc) & BUDISH SENSITIVITY ===
User= 10 / Total= 11.80 BTC (2024 K= 18): 2024-2028:K>=18 | 2028-2032:K>=18 | 2032-2036:K>=31 | 2036-2040:K>=61
User= 15 / Total= 18.00 BTC (2024 K= 18): 2024-2028:K>=18 | 2028-2032:K>=24 | 2032-2036:K>=47 | 2036-2040:K>=93
User= 50 / Total= 62.00 BTC (2024 K= 42): 2024-2028:K>=40 | 2028-2032:K>=80 | 2032-2036:K>=159 | 2036-2040:K>=318
User=200 / Total=224.00 BTC (2024 K=144): 2024-2028:K>=144 | 2028-2032:K>=287 | 2032-2036:K>=574 | 2036-2040:K>=1147
Budish winning-fork direct flow-cost @ K=18 (excl. BTC-price crash): kappa=5%:2.81 BTC | kappa=15%:8.44 BTC | kappa=30%:16.88 BTC | kappa=50%:28.12 BTC
=== 11. STAGE 1B (clArk) ALTERNATIVE GATE: LIQUIDITY & log2(N) BRANCH EXIT WEIGHTS ===
N= 64 (depth= 6): exit= 1156 vB | @100=115,600 sats | @500=578,000 sats
N= 128 (depth= 7): exit= 1323 vB | @100=132,300 sats | @500=661,500 sats
N= 256 (depth= 8): exit= 1490 vB | @100=149,000 sats | @500=745,000 sats
N= 512 (depth= 9): exit= 1657 vB | @100=165,700 sats | @500=828,500 sats
N=1024 (depth=10): exit= 1824 vB | @100=182,400 sats | @500=912,000 sats
=== 12. REAL 2,000-STEP STAGE 1A SIMULATION (EXPLICIT A, TICKETS, k=20 GRIEF, REORGS) ===
Bob, Mike, k=20 grief burst, TransferCredit, Ticket cap race & 2,000 adversarial steps PASSED V=C+L+E+R+A+B:
deposit=15, deposit_race_blocked_by_ticket=39, transfer=254, forced_exit=59, front_paid=19, front_grief=7, front_grief_burst_k20=1, exit_cancel=2, fifo_assign=21, take_confirmed=14, release_assignment=4, transfer_credit=14, disprove_dual_slash=6, lamport_equivocation_slash=3, topup_op=10, mine_block=2551, reorg=145, reorg_blocks_reverted=1319, reorg_events_reverted=439
ALL v2 (v3.1.0-rfc R8-HARDENED ZERO-FEDERATION) CONSISTENCY, ERLANG, HALL, EV & SOLVENCY CHECKS PASSED.
Checker Source (verify_spec_bounds.py)
#!/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()
Attack this spec & submit feedback
This is a Public RFC updated to v2 (v3.1.0-rfc) in response to Consolidated Hostile Review R8 (redlining against archived v1 / v3.0.0-rfc). Humans and AI review agents are invited to run python3 -I scripts/verify_spec_bounds.py, inspect the v1 → v2 changelog & redlines, file findings, or open pull requests.