#!/usr/bin/env python3
"""Reproducible arithmetic for the Mirai/Sober Swallow Pathways write-ups (2026-12-06).
Pure stdlib. Every constant is tagged with its source in SOURCES below.
Usage: python3 pq_calc.py
"""
from datetime import date, timedelta
import math

# ---------- constants (source tags -> see SOURCES) ----------
BLOCK_WU = 4_000_000                     # BIP-141 weight limit [BIP141]
BLOCKS_PER_DAY = 144                     # nominal 10-minute spacing
SIZES = {                                # bytes: (public key, signature)
 'Schnorr (BIP340)':               (32, 64),     # [BIP340]
 'ML-DSA-44 (FIPS 204)':           (1312, 2420), # [FIPS204 Table 2]
 'ML-DSA-65 (FIPS 204)':           (1952, 3309), # [FIPS204 Table 2]
 'SLH-DSA-SHA2-128s (FIPS 205)':   (32, 7856),   # [FIPS205 Table 2]
 'SLH-DSA-SHA2-128f (FIPS 205)':   (32, 17088),  # [FIPS205 Table 2]
 'SHRINCS stateful, smallest':     (48, 548),    # [SHRINCS-BIP]
 'SHRINCS stateful, largest':      (48, 4619),   # [SHRINCS-BIP]
 'SHRINCS stateless fallback':     (48, 5777),   # [SHRINCS-BIP]
}
def cs(n):  # CompactSize length
    return 1 if n < 253 else 3
def push(n):  # script push of n data bytes
    if n <= 75: return 1 + n
    if n <= 255: return 2 + n
    return 3 + n

# transaction skeleton (non-witness), vout types
OUT = {'P2TR/P2MR': 43, 'P2WPKH': 31}     # 8 value + 1 len + script
def nonwit(n_in, n_out, out_kind='P2TR/P2MR'):
    return 4 + cs(n_in) + 41*n_in + cs(n_out) + OUT[out_kind]*n_out + 4
def vsize(non, wit):  # wit includes marker+flag when >0
    return math.ceil((4*non + wit) / 4)

def p2tr_keypath_wit():           # count + len + 64-byte sig (+2 marker/flag)
    return 2 + 1 + 1 + 64
def p2mr_leaf_wit(pk, sig, algo_flag=False, depth=0):
    """P2MR depth-0 spend: stack = [sig, script, control]; script = push(pk)+1 opcode.
    control block at depth 0 = 1 byte (BIP-360: 1+32m) -> serialized with 1-byte size prefix."""
    pkb = pk + (1 if algo_flag else 0)
    script = push(pkb) + 1
    ctrl = 1 + 32*depth
    items = [sig, script, ctrl]
    return 2 + 1 + sum(cs(i) + i for i in items)

def row(name, wit, n_in=1, n_out=2):
    non = nonwit(n_in, n_out)
    v = vsize(non, wit)
    wu = 4*non + wit
    return name, wit, wu, v, BLOCK_WU // wu

def table(n_in=1, n_out=2):
    base = row('P2TR key-path (Schnorr) baseline', p2tr_keypath_wit(), n_in, n_out)
    rows = [base]
    for k, (pk, sig) in SIZES.items():
        if k.startswith('Schnorr'): continue
        flag = k.startswith('SHRINCS')
        rows.append(row('P2MR depth-1 leaf, ' + k, p2mr_leaf_wit(pk, sig, flag, 1), n_in, n_out))
    # NOTE: BIP-360 treats depth-0 script trees as anyone-can-spend, so every P2MR leaf must be at depth>=1. hybrid trees: a BIP340-signature leaf (daily spend) and a PQ leaf in a depth-1 P2MR tree
    rows.append(row('P2MR depth-1, spend via BIP340-signature leaf (hybrid tree)', p2mr_leaf_wit(32, 64, True, 1), n_in, n_out))
    return base, rows

# ---------- migration arithmetic ----------
N_UTXO_ALL = 163_370_361        # [WEHODL] dumptxoutset block 975,464, 2026-11-11
N_UTXO_EXPOSED = 55_611_217     # [WEHODL] key-publishing outputs (P2PK, bare multisig, P2TR)
N_P2PK = 44_513                 # [WEHODL] P2PK outputs, ~1.71M BTC
VB_IN_P2WPKH = 68               # 41 non-wit + 107 wit/4 (BIP141 typical)
VB_OUT_P2MR = 43/1              # 43 bytes non-witness = 43 vB per output
VB_IN_P2PK = 114                # 41 + scriptSig (1+1+72 sig push ~73)
def mig_days(n, vb_each, lane):
    blocks = n*vb_each/1_000_000   # 1,000,000 vB per block
    return blocks, blocks/BLOCKS_PER_DAY/lane

if __name__ == '__main__':
    for shape in [(1,1),(1,2),(2,3)]:
        base, rows = table(*shape)
        print(f'\n== shape {shape[0]}-in-{shape[1]}-out, outputs P2TR/P2MR-size ==')
        print('| Spend | witness bytes (incl marker/flag) | weight WU | vbytes | tx per 4,000,000 WU block | capacity vs baseline |')
        print('|---|---:|---:|---:|---:|---:|')
        for name, wit, wu, v, n in rows:
            print(f'| {name} | {wit} | {wu} | {v} | {n:,} | {100*n/rows[0][4]:.1f}% |')
    print('\n== migration move (classical-signed inputs -> P2MR outputs) ==')
    for vb_in,label in [(VB_IN_P2WPKH,'P2WPKH input'),(VB_IN_P2PK,'P2PK input')]:
        for consolidate in (False, True):
            each = vb_in + (0 if consolidate else VB_OUT_P2MR)
            for n,nm in [(N_UTXO_ALL,'all 163.37M UTXOs'),(N_UTXO_EXPOSED,'55.61M key-exposed UTXOs'),(N_P2PK,'44,513 P2PK UTXOs')]:
                b,_ = mig_days(n,each,1.0)
                print(f'{label:13s} {"consol" if consolidate else "1:1   "} {nm:26s} {each:6.1f} vB each -> {b:12,.0f} blocks = {b/144:9.1f} days @100%  | @25% {b/144/0.25:9.1f} d | @10% {b/144/0.10:9.1f} d')
    each=VB_IN_P2WPKH+VB_OUT_P2MR
    b,_=mig_days(N_UTXO_ALL,each,1.0)
    print('\nlane share that reproduces Ali "2 years to move" (730 d) for all UTXOs at 1:1 P2WPKH->P2MR: %.1f%%' % (100*b/144/730))
    each=VB_IN_P2WPKH
    b,_=mig_days(N_UTXO_ALL,each,1.0)
    print('   same, fully consolidated (68 vB/input): %.1f%%' % (100*b/144/730))
    # Hourglass V2 arithmetic
    p2pk_btc = 1_714_726
    print('\nHourglass V2: %d BTC at 1 BTC/block = %.1f years (52,560 blocks/yr)' % (p2pk_btc, p2pk_btc/52_560))
    # activation clocks
    d = lambda y,m,dd: date(y,m,dd)
    seg = (d(2017,8,24)-d(2015,12,21)).days
    tap = (d(2021,11,14)-d(2020,1,19)).days
    tap_disc = (d(2021,11,14)-d(2019,5,6)).days
    print('\nSegWit BIP-141 assigned 2015-12-21 -> activated 2017-08-24: %d d (%.1f mo)' % (seg, seg/30.44))
    print('Taproot BIP-341 assigned 2020-01-19 -> activated 2021-11-14: %d d (%.1f mo); from 2019-05-06 mailing-list proposal: %d d (%.1f mo)' % (tap, tap/30.44, tap_disc, tap_disc/30.44))
    drafts = d(2027,1,31)
    for nm,days in [('SegWit pace',seg),('Taproot pace (from BIP number)',tap),('Taproot pace (from first list post)',tap_disc)]:
        act = drafts + timedelta(days=days)
        pa = act + timedelta(days=160_000*10/60/24)
        pb = pa + timedelta(days=730)
        print(f'drafts 2027-01-31 + {nm}: activation {act}; BIP-361 Phase A end (+160,000 blocks={160000*10/60/24/365.25:.2f} y) {pa}; Phase B (+2 y) {pb}')
    # address-level histogram (ChainQuery 2026-11-29)
    addrs = 14_096_812; btc = 7_223_596
    big_share = 29.03+16.60+18.17+30.40
    big_addr = addrs*(0.34+0.03)/100
    print('\nChainQuery histogram: addresses >=10 BTC hold %.2f%% of at-risk BTC (%.0f BTC) in ~%.0f addresses (%.2f%% of addresses)' % (big_share, btc*big_share/100, big_addr, 100*big_addr/addrs))
    for k in (1,5,20):
        b,_=mig_days(big_addr*k, VB_IN_P2WPKH+VB_OUT_P2MR,1.0)
        print('   if each such address holds %2d UTXOs: %.0f blocks (%.2f days at 100%%)' % (k,b,b/144))
    reuse_btc=5_292_781; reuse_addr=3_914_563+3_847_974+1_051_487+94_740
    print('reuse-exposed: %d BTC (%.1f%% of at-risk) in %d addresses' % (reuse_btc,100*reuse_btc/btc,reuse_addr))

def backcast():
    """Latest date to FREEZE the first PQ spec so that activation + migration finish before a given CRQC date."""
    print('\n== back-cast: latest spec-freeze date = CRQC date - activation - migration ==')
    act = {'SegWit 612 d':612,'Taproot 665 d':665,'Taproot from first list post 923 d':923}
    mig = {'0.5 y (assumed, value-first)':183,'2 y (Ali)':730}
    for y in (2029,2030,2032,2035):
        for an,ad in act.items():
            for mn,md in mig.items():
                latest = date(y,1,1)-timedelta(days=ad+md)
                slack=(latest-date(2027,1,31)).days
                print(f'CRQC {y}-01-01 | {an:36s} | migrate {mn:42s} -> freeze by {latest} (slack vs 2027-01-31 drafts: {slack:+d} d)')
if __name__ == '__main__':
    backcast()
