#!/usr/bin/env python3
"""Regtest measurement: how long does Bitcoin Core 32.1 take to validate a full block of 1-in-1-out
migration-shaped transactions (P2WPKH in -> v1 witness out, signed with the old ECDSA key) when the
validating node has NEVER seen the transactions (no mempool, no signature cache), i.e. the PQ-block case.
Node A builds the block; node B (offline from A) receives it via submitblock; B's -debug=bench log gives
ms per txin. Usage: python3 vblock.py [N_TX]   (default 9000 ~ one full 4M-WU block)"""
import subprocess, json, time, os, shutil, sys, base64, http.client, re
BIN = '/workspace/miri-earn/aibtc-pathways/regtest/bitcoin-32.1/bin'
N = int(sys.argv[1]) if len(sys.argv) > 1 else 9000
DA, DB = '/tmp/vblock-A', '/tmp/vblock-B'
PA, PB = 18643, 18653
for d in (DA, DB): shutil.rmtree(d, ignore_errors=True); os.makedirs(d)
def start(dd, rpc, p2p, extra):
    subprocess.Popen([BIN+'/bitcoind', '-regtest', '-datadir='+dd, '-daemon', f'-rpcport={rpc}', f'-port={p2p}',
                      '-fallbackfee=0.0001', '-listen=1', '-maxmempool=1000', '-dbcache=2000']+extra, stdout=subprocess.DEVNULL)
start(DA, PA, PA+1, [])
PAR = os.environ.get('PAR', '0')  # 0 = all cores, 1 = no extra script threads
start(DB, PB, PB+1, ['-debug=bench', '-par='+PAR])
print('node B -par='+PAR)
class RPC:
    def __init__(s, dd, port): s.dd, s.port = dd, port
    def call(s, method, *params, wallet=None, batch=None):
        ck = open(s.dd+'/regtest/.cookie').read().strip()
        h = http.client.HTTPConnection('127.0.0.1', s.port, timeout=3600)
        body = batch if batch is not None else {'jsonrpc': '1.0', 'id': 1, 'method': method, 'params': list(params)}
        h.request('POST', '/wallet/'+wallet if wallet else '/', json.dumps(body),
                  {'Authorization': 'Basic '+base64.b64encode(ck.encode()).decode()})
        r = json.loads(h.getresponse().read())
        if batch is not None: return r
        if r.get('error'): raise RuntimeError(r['error'])
        return r['result']
A, B = RPC(DA, PA), RPC(DB, PB)
for r in (A, B):
    for _ in range(60):
        try: r.call('getblockcount'); break
        except Exception: time.sleep(1)
print('node', A.call('getnetworkinfo')['subversion'], 'nproc', os.cpu_count())
A.call('createwallet', 'w')
mine = A.call('getnewaddress', wallet='w')
A.call('generatetoaddress', 101 + N // 2000 + 2, mine)
src = [A.call('getnewaddress', '', 'bech32', wallet='w') for _ in range(50)]
left = N
while left > 0:
    k = min(2000, left)
    A.call('sendmany', '', {src[i % 50] if False else A.call('getnewaddress', '', 'bech32', wallet='w'): 0.001 for i in range(k)}, wallet='w') if False else None
    outs = {}
    for i in range(k): outs.setdefault(src[i % 50], 0)
    # one output per UTXO: use createrawtransaction-free sendmany with distinct addresses
    addrs = A.call('getnewaddress', '', 'bech32', wallet='w', batch=None) if False else None
    batch = [{'jsonrpc': '1.0', 'id': i, 'method': 'getnewaddress', 'params': ['', 'bech32']} for i in range(k)]
    addrs = [x['result'] for x in A.call(None, wallet='w', batch=batch)]
    A.call('sendmany', '', {a: 0.001 for a in addrs}, wallet='w')
    A.call('generatetoaddress', 1, mine)
    left -= k
# sync B, then cut it off
A.call('addnode', f'127.0.0.1:{PB+1}', 'onetry')
for _ in range(120):
    if B.call('getblockcount') == A.call('getblockcount'): break
    time.sleep(1)
B.call('setnetworkactive', False); A.call('setnetworkactive', False)
utxos = [u for u in A.call('listunspent', 1, 9999999, wallet='w') if abs(u['amount'] - 0.001) < 1e-12][:N]
print('utxos', len(utxos))
dest = [x['result'] for x in A.call(None, wallet='w', batch=[{'jsonrpc': '1.0', 'id': i, 'method': 'getnewaddress', 'params': ['', 'bech32m']} for i in range(len(utxos))])]
raws = [x['result'] for x in A.call(None, batch=[{'jsonrpc': '1.0', 'id': i, 'method': 'createrawtransaction',
        'params': [[{'txid': u['txid'], 'vout': u['vout']}], {d: 0.00099}]} for i, (u, d) in enumerate(zip(utxos, dest))])]
signed = [x['result']['hex'] for x in A.call(None, wallet='w', batch=[{'jsonrpc': '1.0', 'id': i, 'method': 'signrawtransactionwithwallet', 'params': [r]} for i, r in enumerate(raws)])]
res = A.call(None, batch=[{'jsonrpc': '1.0', 'id': i, 'method': 'sendrawtransaction', 'params': [h]} for i, h in enumerate(signed)])
print('sent', sum(1 for x in res if not x.get('error')), 'errors', sum(1 for x in res if x.get('error')))
bh = A.call('generatetoaddress', 1, mine)[0]
blk = A.call('getblock', bh, 1)
print(f"block: {blk['nTx']} tx, weight {blk['weight']} WU, size {blk['size']} B")
hexblk = A.call('getblock', bh, 0)
t0 = time.time(); r = B.call('submitblock', hexblk); t1 = time.time()
print('submitblock on B (never saw the txs):', r, f'wall {1000*(t1-t0):.0f} ms')
log = open(DB+'/regtest/debug.log').read().splitlines()
for line in log[-12:]:
    if re.search(r'Verify \d+ txins|Connect block:|Connect total|- Load block from disk|ConnectBlock|Connect transactions', line):
        print('B log:', line.split(' ', 1)[1])
for r in (A, B): r.call('stop')
