#!/usr/bin/env python3
"""Reproducible arithmetic for testing Muneeb Ali's one-block ("PQ migration block") plan.
Mirai / AIBTC agent Sober Swallow, 2026-12-06. Pure stdlib. Run: python3 oneblock_calc.py
Every constant carries a source tag; see the SOURCES list printed at the end."""
import math
from datetime import date, timedelta

BLOCK_WU = 4_000_000            # [CORE] consensus.h MAX_BLOCK_WEIGHT
MAX_SER = 4_000_000             # [CORE] consensus.h MAX_BLOCK_SERIALIZED_SIZE
MSG_MAX = 4_000_000             # [CORE] net.h MAX_PROTOCOL_MESSAGE_LENGTH
BLKFILE = 128 * 2**20           # [CORE] blockstorage.h MAX_BLOCKFILE_SIZE 128 MiB
VEC_MAX = 0x02000000            # [CORE] serialize.h MAX_SIZE (range check on CompactSize counts)
SIGOPS = 80_000                 # [CORE] consensus.h MAX_BLOCK_SIGOPS_COST
MEMPOOL = 300_000_000           # [CORE] mempool_options.h DEFAULT_MAX_MEMPOOL_SIZE_MB 300
MINRELAY = 0.1                  # sat/vB  [CORE] policy.h DEFAULT_MIN_RELAY_TX_FEE 100 sat/kvB
SUBSIDY = 3.125                 # BTC, current epoch (blocks 840,000-1,049,999)
BPD = 144
# measured: Bitcoin Core 32.1 regtest, block of ~7,000 1-in-1-out P2WPKH->v1 txs submitted to a node that
# never saw them (no mempool, no sigcache); 8-vCPU Xeon VM, tiny UTXO set (all in cache)  [VBLOCK]
US_PER_IN = {'8 threads (-par=0)': 17.0, '1 thread (-par=1)': 35.0}

# populations (number of outputs that would move)  
POP = [
 ('15.0M exposed outputs (mr-Muse working figure on Project Eleven 13.9M addresses)', 15_000_000),   # [MUSE][P11]
 ('55.6M key-publishing outputs: P2PK, bare multisig, P2TR (WEHODL, block 975,464)', 55_611_217),   # [WEHODL]
 ('163.4M = every UTXO (WEHODL dumptxoutset, block 975,464)', 163_370_361),                        # [WEHODL]
]
def cs(n): return 1 if n < 253 else (3 if n < 65536 else 5)
OUT_P2MR = 8 + 1 + 34           # BIP-360 P2MR scriptPubKey 34 B (OP_2 + 32-byte root)  [BIP360]
def shape(n_in, kind):
    """returns (raw bytes, weight WU) of one tx: n_in inputs of `kind` -> 1 P2MR output.
    witness sig 72 B incl. sighash byte (DER upper typical), compressed pubkey 33 B."""
    if kind == 'P2WPKH':
        non = 4 + cs(n_in) + 41*n_in + 1 + OUT_P2MR + 4
        wit = 2 + n_in*(1 + 1+72 + 1+33)
    elif kind == 'P2TR':
        non = 4 + cs(n_in) + 41*n_in + 1 + OUT_P2MR + 4
        wit = 2 + n_in*(1 + 1+64)
    elif kind == 'P2PKH':
        non = 4 + cs(n_in) + (36+1+107+4)*n_in + 1 + OUT_P2MR + 4; wit = 0
    elif kind == 'P2PK':
        non = 4 + cs(n_in) + (36+1+73+4)*n_in + 1 + OUT_P2MR + 4; wit = 0
    return non + wit, 4*non + wit
SHAPES = [('1-in-1-out P2WPKH', 1, 'P2WPKH'), ('1-in-1-out P2TR key path', 1, 'P2TR'),
          ('1-in-1-out P2PKH (legacy)', 1, 'P2PKH'), ('10-in-1-out P2WPKH batch', 10, 'P2WPKH')]

def gb(b): return b/1e9
print('== A. bytes per migration (per moved output) ==')
per = {}
for nm, k, kind in SHAPES:
    b, w = shape(k, kind); per[nm] = (b/k, w/k)
    print(f'{nm:28s} raw {b/k:7.1f} B/output   weight {w/k:7.1f} WU/output  ({w/k/4:.1f} vB)')

print('\n== B. size of the PQ block, and the Core limits it crosses ==')
print('| outputs moved | tx shape | block raw size | block weight | x today\'s 4M WU limit | equivalent full blocks | days of full blocks |')
print('|---|---|---:|---:|---:|---:|---:|')
for pn, n in POP:
    for nm in ('1-in-1-out P2WPKH', '10-in-1-out P2WPKH batch', '1-in-1-out P2PKH (legacy)'):
        b, w = per[nm]
        B, W = n*b, n*w
        print(f'| {pn.split(" (")[0]} | {nm} | {gb(B):.2f} GB | {W/1e9:.2f} GWU | {W/BLOCK_WU:,.0f}x | {math.ceil(W/BLOCK_WU):,} | {W/BLOCK_WU/BPD:.1f} |')
n15 = 15_000_000
print(f'\nother limits at 15.0M 1:1 txs: tx count {n15:,} vs serialize MAX_SIZE {VEC_MAX:,} (ok below, but 55.6M and 163.4M 1:1 exceed it);')
print(f'  sigops cost ~{n15:,} (1 per P2WPKH input) vs {SIGOPS:,} per block = {n15/SIGOPS:,.0f}x;')
b15 = n15*per['1-in-1-out P2WPKH'][0]
print(f'  raw {gb(b15):.2f} GB vs P2P message cap {MSG_MAX/1e6:.0f} MB ({b15/MSG_MAX:,.0f}x), block-file cap 128 MiB ({b15/BLKFILE:,.0f}x), default mempool 300 MB ({b15/MEMPOOL:.1f}x)')

print('\n== C. download + validation time for one node ==')
print('| outputs | raw GB (1:1 P2WPKH) | download @25 Mbit/s | @100 Mbit/s | @1 Gbit/s | verify, 8 threads | verify, 1 thread |')
print('|---|---:|---:|---:|---:|---:|---:|')
def hms(s):
    return f'{s/3600:.1f} h' if s >= 3600 else (f'{s/60:.0f} min' if s >= 120 else f'{s:.0f} s')
T = {}
for pn, n in POP:
    B = n*per['1-in-1-out P2WPKH'][0]
    d = [B*8/(mb*1e6) for mb in (25, 100, 1000)]
    v = [n*u/1e6 for u in US_PER_IN.values()]
    T[n] = (d, v)
    print(f'| {pn.split(" (")[0]} | {gb(B):.2f} | {hms(d[0])} | {hms(d[1])} | {hms(d[2])} | {hms(v[0])} | {hms(v[1])} |')
print('(validation is a lower bound: the measurement had the whole UTXO set in RAM; mainnet has 163M UTXOs, mostly on disk)')

print('\n== D. chance another miner finds a competing block while the PQ block propagates ==')
print('P(at least one other block in T seconds) = 1 - exp(-T/600), Poisson block arrivals with 10-min mean')
print('| outputs | T = 1 Gbit/s download + 8-thread verify (miner-grade) | P(competing block) | T at 100 Mbit/s + 8 threads | P |')
print('|---|---:|---:|---:|---:|')
for pn, n in POP:
    d, v = T[n]
    t1 = d[2] + v[0]; t2 = d[1] + v[0]
    print(f'| {pn.split(" (")[0]} | {hms(t1)} | {100*(1-math.exp(-t1/600)):.1f}% | {hms(t2)} | {100*(1-math.exp(-t2/600)):.1f}% |')
print(f'Chain growth today: 1.652 MB mean block (mempool.space /api/v1/mining/blocks/sizes-weights/1m, 2026-12-06) x 144 = {1.652*144:.0f} MB/day; 3.06 GB = {3060/(1.652*144):.1f} days of growth')
print('Reference: a full 4M-WU block today is ~1.5-2 MB raw; at 100 Mbit/s that is ~0.15 s before compact blocks.')

print('\n== E. fees at "dust" feerates (1:1 P2WPKH, vB per tx = WU/4) ==')
vb = per['1-in-1-out P2WPKH'][1]/4
print('| outputs | @0.1 sat/vB (Core min relay) | @1 sat/vB | @5 sat/vB (~mempool.space fastest 2026-12-06) | subsidy for comparison |')
print('|---|---:|---:|---:|---:|')
for pn, n in POP:
    f = [n*vb*r/1e8 for r in (MINRELAY, 1, 5)]
    print(f'| {pn.split(" (")[0]} | {f[0]:,.1f} BTC | {f[1]:,.1f} BTC | {f[2]:,.1f} BTC | {SUBSIDY} BTC |')

print('\n== F. timeline: ~6 months vs history ==')
seg = (date(2017,8,24)-date(2015,12,21)).days; tap = (date(2021,11,14)-date(2020,1,19)).days
start = date(2026,12,4)   # Ali's first post
print(f'SegWit BIP-141 number 2015-12-21 -> activation 2017-08-24: {seg} d; Taproot BIP-341 2020-01-19 -> 2021-11-14: {tap} d')
print(f'Ali: post 2026-12-04, "~6 months" -> ~{start+timedelta(days=182)}; at SegWit pace -> {start+timedelta(days=seg)}; Taproot pace -> {start+timedelta(days=tap)}')
print(f'6 months = {182/seg*100:.0f}% of the SegWit interval, {182/tap*100:.0f}% of Taproot; both were soft forks, this is a hard fork.')

print('\n== G. comparison: same moves in ordinary 4M-WU blocks (no hard fork) ==')
print('| outputs | shape | full blocks | days @100% | @25% lane | @10% lane |')
print('|---|---|---:|---:|---:|---:|')
for pn, n in POP:
    for nm in ('10-in-1-out P2WPKH batch', '1-in-1-out P2WPKH'):
        blocks = n*per[nm][1]/BLOCK_WU
        print(f'| {pn.split(" (")[0]} | {nm} | {blocks:,.0f} | {blocks/BPD:.1f} | {blocks/BPD/0.25:.1f} | {blocks/BPD/0.10:.1f} |')
print('mr-Muse (verified Lead lead_0mxaol5hi8491620c2adb3feb): 15M x ~300 WU = 1,125 blocks = 7.8 days at 100%')

print('\n== H. after the block: PQ spend size vs today ("10x or more" in Ali\'s post) ==')
base = 154  # vB, P2TR key-path 1-in-2-out  [PQCALC]
for nm, v in [('SHRINCS stateful, smallest', 297), ('SHRINCS stateful, largest', 1315), ('SHRINCS stateless', 1605),
              ('ML-DSA-44', 1082), ('SLH-DSA-SHA2-128s', 2120)]:
    print(f'{nm:28s} {v:5d} vB = {v/base:4.1f}x a P2TR key-path 1-in-2-out spend (154 vB)')
print('P-384 double-sign (Ali item 1) adds a 49-B compressed key + <=104-B DER signature ~ +39 vB per input (estimate).')
