#!/usr/bin/env python3 """Deterministic analytical scenarios for Bitcoin resilience v2.1. Python 3 standard library only; no network. Run beside this file or from any directory. Writes capacity.csv, cpu.csv, results.json and TABLES.md here. Hypothetical transaction encodings, not consensus implementation/benchmarks. """ import csv import itertools import json import math from decimal import Decimal from pathlib import Path OUT = Path(__file__).resolve().parent BLOCK_WEIGHT = 4_000_000 BLOCKS_PER_DAY = 144 SHARES = (.25, .5, 1.0) DISCOUNTS = (4, 2, 1) COUNTS = (10_000_000, 100_000_000) # name, inputs, outputs, per-input witness item lengths, units cleared per tx, # optional per-input scriptSig bytes (default 0) TEMPLATES = [ ('ECC migration 1-in-1-out', 1, 1, [72, 33], 1), ('ECC migration 10-in-1-out', 10, 1, [72, 33], 10), ('ECC migration 50-in-1-out', 50, 1, [72, 33], 50), ('ECC 1-in-2-out (SegWit)', 1, 2, [72, 33], 1), ('ECC migration 1-in-1-out (legacy P2PKH)', 1, 1, [], 1, 107), ('ML-DSA-44 1-in-1-out', 1, 1, [2420, 1312], 1), ('ML-DSA-65 1-in-1-out', 1, 1, [3309, 1952], 1), ('SLH-SHA2-128s 1-in-1-out', 1, 1, [7856, 32], 1), ('SLH-SHA2-192s 1-in-1-out', 1, 1, [16224, 48], 1), ('SLH-SHA2-256s 1-in-1-out', 1, 1, [29792, 64], 1), ('SLH-SHA2-256s 1-in-2-out', 1, 2, [29792, 64], 1), ('ML-DSA-87 AND SLH-256s', 1, 1, [4627, 2592, 29792, 64], 1), ('Recovery 190000-byte proof', 1, 1, [190000], 1), ] def compact_size(n): assert n >= 0 return 1 if n < 253 else 3 if n <= 65535 else 5 if n <= 4294967295 else 9 def serialization(template, discount=4): _, nin, nout, items, units = template[:5] script_sig = template[5] if len(template) > 5 else 0 # Each output is value + length + 34-byte script. Legacy P2PKH uses a # 107-byte scriptSig: one-byte pushes of a 72-byte signature and 33-byte key. base = (4 + compact_size(nin) + (36 + compact_size(script_sig) + script_sig + 4)*nin + compact_size(nout) + 43*nout + 4) witness = (2 + nin*(compact_size(len(items)) + sum(compact_size(n)+n for n in items))) if items else 0 weight = 4*base + (4//discount)*witness return base, witness, weight, units def capacity_rows(): rows = [] for t, d, f, n in itertools.product(TEMPLATES, DISCOUNTS, SHARES, COUNTS): base, witness, weight, units = serialization(t, d) tx_day = BLOCK_WEIGHT*BLOCKS_PER_DAY*f/weight units_day = tx_day*units rows.append(dict(template=t[0], inputs=t[1], outputs=t[2], base_bytes=base, witness_bytes=witness, discount=d, weight_wu=weight, share=f, action_count=n, units_per_tx=units, tx_per_day=tx_day, units_per_day=units_day, days=n/units_day, years=n/units_day/365.25)) return rows def cpu_rows(): """Explicit scenarios, never measured verification performance. Budget B seconds of serial-equivalent validation per block; whole-block ceiling min(4M/w,B/v). Allocate long-run share f to both resources. v includes all per-transaction validation; no parallel-speedup claim. """ rows = [] t = next(t for t in TEMPLATES if t[0] == 'SLH-SHA2-256s 1-in-2-out') w = serialization(t)[2] for budget, cost in itertools.product((1., 10.), (.001, .01, .1)): per_block = min(BLOCK_WEIGHT/w, budget/cost) rows.append(dict(template=t[0], discount=4, share=.25, budget_seconds_per_block=budget, cost_seconds_per_tx=cost, weight_tx_per_block=BLOCK_WEIGHT/w, cpu_tx_per_block=budget/cost, effective_tx_per_day=per_block*144*.25, years_for_100m=100_000_000/(per_block*144*.25)/365.25)) return rows def vault_checks(): schedules = [] delay = 3 for rh, priority in itertools.product((0, 1, 2, 3, 4, math.inf), ('recovery_first','attacker_first')): events = [(delay, 'finalize')] if math.isfinite(rh): events.append((rh, 'recover')) events.sort(key=lambda x:(x[0], 0 if (x[1]=='recover')==(priority=='recovery_first') else 1)) outcome = 'pending' for _, event in events: if outcome == 'pending': outcome = 'recovered' if event == 'recover' else 'stolen' assert rh >= delay or outcome == 'recovered' assert rh <= delay or outcome == 'stolen' schedules.append(dict(recovery_height=rh if math.isfinite(rh) else 'never', order=priority, outcome=outcome)) assert {s['outcome'] for s in schedules if s['recovery_height']==3} == {'recovered','stolen'} # Signatures in this abstraction bind identifiers; no real cryptography. churn = [] for event, refresh, arrival in itertools.product(('replacement','reorg'), (False, True), (2, 4)): canonical_outpoint = 'pending-v2' signed_outpoint = canonical_outpoint if refresh else 'pending-v1' valid = signed_outpoint == canonical_outpoint outcome = 'recovered' if valid and arrival < delay else 'stolen' assert refresh or outcome == 'stolen' churn.append(dict(event=event, refreshed=refresh, arrival=arrival, authorization_matches=valid, outcome=outcome)) return dict(delay=delay, timing_schedules=schedules, outpoint_churn_schedules=churn, direct_locked_recovery='Permitted before a trigger consumes Locked; still an ordering race.') def indistinguishability(): n = 0 for a in range(101): for b in range(101-a): assert (a+b)/200 <= .5 n += 1 return dict(grid_rules=n, equal_prior_success_upper_bound=.5, note='Arithmetic illustration only; arbitrary-distribution proof is in the manuscript.') def finite_size(): b = 256 c2 = b/math.sqrt(math.log2(math.log2(b))) ce = b/math.sqrt(math.log(math.log(b))) return dict(b=b, base2_time_coefficient=c2, natural_time_coefficient=ce, base2_equality_constant=128/c2, natural_equality_constant=128/ce, base2_space_coefficient=b/math.log2(b)**.25, note='Hypothetical 2^(C*g(b)); Big-O is an upper bound, not runtime or a lower bound. Constants change with log convention.') def grover_wall_clock(): """Parametric depth illustration, not a measured quantum runtime.""" return [dict(sequential_steps=2**67, seconds_per_step=seconds, parallel_machines=machines, depth_speedup=math.sqrt(machines), years=(2**67)*seconds/math.sqrt(machines)/(86400*365.25)) for seconds, machines in itertools.product((.001, .000001), (1, 1_000_000))] def csv_write(name, rows): with (OUT/name).open('w', newline='') as f: writer=csv.DictWriter(f,fieldnames=rows[0].keys());writer.writeheader();writer.writerows(rows) def census_arithmetic(): """Reconcile published table, not a Bitcoin chain scan or classifier audit.""" with (OUT.parent/'data'/'census-report.csv').open() as f: rows=list(csv.DictReader(f)) totals={k:sum(Decimal(r[k]) for r in rows) for k in ('all_utxos','all_btc','classified_exposed_utxos','classified_exposed_btc')} assert totals['all_utxos']==163658747 assert totals['all_btc']==Decimal('20109207.36373994') assert totals['classified_exposed_utxos']==100367587 assert totals['classified_exposed_btc']==Decimal('7164754.11893473') return dict(block=975019,snapshot_date='2026-11-09', totals={k:str(v) for k,v in totals.items()}, classified_value_percent=str(100*totals['classified_exposed_btc']/totals['all_btc']), excluded_p2tr_outputs=sum(int(r['classified_exposed_utxos']) for r in rows if r['class']!='P2TR'), excluded_p2tr_btc=str(sum(Decimal(r['classified_exposed_btc']) for r in rows if r['class']!='P2TR')), source_ids=['E01','E02','E03'], note='Publisher-defined mixed key/script classification; not theft-feasibility bound or distinct Grover targets. Chain census not rerun.') def main(): assert [compact_size(n) for n in (252,253,65535,65536)] == [1,3,3,5] assert serialization(TEMPLATES[0])[:3] == (94,110,486) assert serialization(TEMPLATES[1])[2] == 2934 assert serialization(TEMPLATES[-1])[2] == 190384 templates = {t[0]: t for t in TEMPLATES} assert serialization(templates['ECC 1-in-2-out (SegWit)'])[:3] == (137,110,658) assert serialization(templates['ECC migration 1-in-1-out (legacy P2PKH)'])[:3] == (201,0,804) assert (serialization(templates['SLH-SHA2-256s 1-in-2-out'])[2] - serialization(templates['SLH-SHA2-256s 1-in-1-out'])[2]) == 172 rows=capacity_rows();cpu=cpu_rows() assert len(rows)==234 and len(cpu)==6 assert all(r['units_per_day']>0 for r in rows) for t in TEMPLATES: assert serialization(t,1)[2] >= serialization(t,2)[2] >= serialization(t,4)[2] for r in rows: assert math.isclose(r['days']*r['units_per_day'],r['action_count']) csv_write('capacity.csv',rows);csv_write('cpu.csv',cpu) elasticity=[dict(extra_float_ratio=x,elasticity=e,price_ratio=(1/(1+x))**(1/e)) for x,e in itertools.product((.1,.5,1),(.5,1,2))] race=[dict(seconds=s,no_first_block=math.exp(-s/600)) for s in (10,60,600,3600)] grover=[dict(target_bits=m,valid_fraction=alpha,ideal_log2_queries=(160-m-math.log2(alpha))/2) for m,alpha in itertools.product((0,25,26,27), (1,.5))] wall_clock=grover_wall_clock() results=dict(assumptions=dict(block_weight=BLOCK_WEIGHT,expected_blocks_per_day=144, shares=SHARES,discounts=DISCOUNTS,action_counts=COUNTS, empirical_census_used_as_model_input=False, cpu_inputs_are_hypothetical=True,units='inputs cleared for ECC batches; transactions for other rows'), finite_size=finite_size(),vault=vault_checks(), indistinguishability=indistinguishability(),race=race, elasticity=elasticity,hash160_query_scenarios=grover, hash160_wall_clock_scenarios=wall_clock) results['published_census_arithmetic']=census_arithmetic() (OUT/'results.json').write_text(json.dumps(results,indent=2)+'\n') lines=['## Appendix B. Complete numerical sensitivities','', 'All capacity rows use 100 million units. For 10 million, divide days and years by ten. For another count, scale linearly. ECC batch units are input UTXOs cleared; other rows are transactions. A year is 365.25 days. Allocation shares are long-run averages, not hard partitions within each block. Values are rounded only for display.','', '### B.1 Serialization and weight','', '| Template | Base B | Witness W | WU at 4x | WU at 2x | WU at 1x | Units/tx |', '|---|---:|---:|---:|---:|---:|---:|'] for t in TEMPLATES: b,w,_,u=serialization(t) lines.append(f'| {t[0]} | {b} | {w} | {serialization(t,4)[2]} | {serialization(t,2)[2]} | {serialization(t,1)[2]} | {u} |') legacy=next(r for r in rows if r['template']=='ECC migration 1-in-1-out (legacy P2PKH)' and r['discount']==4 and r['share']==.25 and r['action_count']==100_000_000) segwit=next(r for r in rows if r['template']=='ECC migration 1-in-1-out' and r['discount']==4 and r['share']==.25 and r['action_count']==100_000_000) lines+=['', f"At 25% allocation and the current 4x witness discount, 100M legacy P2PKH inputs take {legacy['days']:.2f} days to clear versus {segwit['days']:.2f} days for SegWit. The legacy scriptSig is 107 bytes (72-byte signature and 33-byte key, each with a one-byte push); it has no witness discount."] lines+=['','### B.2 Years for 100 million units: all discount/share combinations','', '| Template | Discount | 25% | 50% | 100% |','|---|---:|---:|---:|---:|'] for t,d in itertools.product(TEMPLATES,DISCOUNTS): rr=[next(r for r in rows if r['template']==t[0] and r['discount']==d and r['share']==f and r['action_count']==100_000_000) for f in SHARES] lines.append(f"| {t[0]} | {d}x | "+' | '.join(f"{r['years']:.4f}" for r in rr)+' |') lines+=['','### B.3 Illustrative CPU ceiling','', 'SLH-SHA2-256s, one input/two outputs, 4x witness discount, 25% long-run share of both resources. B and v below are chosen sensitivity inputs, not verifier benchmarks. A serial-equivalent CPU budget is an accounting abstraction, not a wall-clock block-validation promise.','', '| Budget B seconds/block | Cost v seconds/tx | Effective tx/day | Years/100M |','|---:|---:|---:|---:|'] for r in cpu: lines.append(f"| {r['budget_seconds_per_block']:g} | {r['cost_seconds_per_tx']:g} | {r['effective_tx_per_day']:.2f} | {r['years_for_100m']:.4f} |") lines+=['','### B.4 Fixed-demand float sensitivity','', '| Added float / original float | Demand elasticity | New / old price |','|---:|---:|---:|'] for r in elasticity:lines.append(f"| {r['extra_float_ratio']:g} | {r['elasticity']:g} | {r['price_ratio']:.6f} |") lines+=['','### B.5 First-block timing and ideal HASH160 search','', '| Extraction time (seconds) | Probability no first block yet |','|---:|---:|'] for r in race:lines.append(f"| {r['seconds']} | {r['no_first_block']:.6f} |") lines+=['','This exponential model assumes a 600-second mean; it is not a theft probability. It omits propagation, selection, fees, censorship and reorganizations.','', '| Distinct target count | log2 ideal queries, valid-domain search | log2 queries, half-valid raw domain |','|---:|---:|---:|'] for m in (0,25,26,27): rr=[r for r in grover if r['target_bits']==m] lines.append(f"| 2^{m} | {rr[0]['ideal_log2_queries']:.1f} | {rr[1]['ideal_log2_queries']:.1f} |") lines+=['','The raw-domain column accounts only for a one-half valid-point fraction. Coherent membership, curve validation, hash circuits, DLOG, memory and depth costs are not represented. Counts are scenarios, not census measurements. The valid-domain column is optimistic: curve-point validity checks inside the oracle add cost.','', 'For 2^67 sequential Grover steps, elapsed years = 2^67 * seconds_per_step / sqrt(P) / (86400 * 365.25). A million parallel machines give only sqrt(P) = 1,000 depth speedup. These step times are hypothetical inputs, not hardware estimates.','', '| Assumed time/step | Parallel machines P | Depth speedup | Elapsed years |', '|---|---:|---:|---:|'] for r in wall_clock: step='1 ms' if r['seconds_per_step']==.001 else '1 us' lines.append(f"| {step} | {r['parallel_machines']:,} | {r['depth_speedup']:,.0f} | {r['years']:,.0f} |") lines+=['','At 1 ms/step this is about 4.68 billion years on one machine or 4.68 million years on a million machines; at 1 us/step it is about 4.68 million years or 4,676 years, respectively.',''] (OUT/'TABLES.md').write_text('\n'.join(lines)) print('Generated 234 capacity rows, 6 CPU rows, full tables and JSON; arithmetic, 12 timing and 8 outpoint-churn checks passed.') if __name__=='__main__': main()