"""Rebuild canonical coinbase keyring rows from pre-SegWit Bitcoin blocks.""" import argparse from concurrent.futures import ThreadPoolExecutor import csv from datetime import datetime, timedelta, timezone from hashlib import sha256 import json from pathlib import Path import struct from aws_data import cache_partitions, fetch, load_period NODE = "https://bitcoin-rpc.publicnode.com" CHECK = "https://blockstream.info/api" ZERO_HASH = "0" * 64 GENESIS_TX = "4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b" def rpc(method, parameters): calls = [ {"jsonrpc": "2.0", "id": index, "method": method, "params": args} for index, args in enumerate(parameters) ] replies = {row["id"]: row for row in json.loads(fetch(NODE, json.dumps(calls).encode()))} if len(replies) != len(calls): raise ValueError(f"{method} returned an incomplete batch") result = [] for index in range(len(calls)): reply = replies[index] if reply.get("error"): raise ValueError(f"{method}{parameters[index]}: {reply['error']}") result.append(reply["result"]) return result def read_batches(method, parameters): batches = [parameters[index:index + 32] for index in range(0, len(parameters), 32)] with ThreadPoolExecutor(max_workers=3) as pool: return [value for batch in pool.map(lambda args: rpc(method, args), batches) for value in batch] def hash256(value): return sha256(sha256(value).digest()).digest() def displayed_hash(value): return hash256(value)[::-1].hex() def merkle_root(txids): layer = [bytes.fromhex(txid)[::-1] for txid in txids] if not layer: raise ValueError("Block without a coinbase") while len(layer) > 1: if len(layer) % 2: layer.append(layer[-1]) layer = [hash256(layer[i] + layer[i + 1]) for i in range(0, len(layer), 2)] return layer[0][::-1].hex() def verify_header(height, block_id, block, parent): if block["height"] != height or block["hash"] != block_id: raise ValueError(f"Block identity mismatch at height {height}") if block.get("previousblockhash", ZERO_HASH) != parent: raise ValueError(f"Parent mismatch at height {height}") root = merkle_root(block["tx"]) if root != block["merkleroot"] or len(block["tx"]) != block["nTx"]: raise ValueError(f"Merkle tree or transaction count mismatch at height {height}") bits = int(block["bits"], 16) header = struct.pack( "> 24 mantissa = bits & 0x7FFFFF if not 3 <= exponent <= 32 or bits & 0x800000 or not mantissa: raise ValueError(f"Invalid proof-of-work target at height {height}") target = mantissa << (8 * (exponent - 3)) if displayed_hash(header) != block_id or int(block_id, 16) > target: raise ValueError(f"Invalid block hash or proof of work at height {height}") def compact_size(raw, offset): marker = raw[offset] if marker < 253: return marker, offset + 1 width = {253: 2, 254: 4, 255: 8}[marker] end = offset + 1 + width return int.from_bytes(raw[offset + 1:end], "little"), end def coinbase_outputs(tx_hex, txid): raw = bytes.fromhex(tx_hex) if displayed_hash(raw) != txid: raise ValueError(f"Coinbase transaction hash mismatch for {txid}") inputs, offset = compact_size(raw, 4) if inputs != 1 or raw[offset:offset + 36] != bytes(32) + bytes.fromhex("ffffffff"): raise ValueError(f"Unexpected coinbase input for {txid}") size, offset = compact_size(raw, offset + 36) count, offset = compact_size(raw, offset + size + 4) for index in range(count): sats, = struct.unpack_from(" 0], ) if start == 0: genesis_hex, = rpc("getblock", [[block_ids[0], 0]]) raw_transactions.insert(0, genesis_coinbase(bytes.fromhex(genesis_hex), block_ids[0])) if block_ids[0] != first_hash or block_ids[-1] != last_hash: raise ValueError("The independent explorer disagrees about a boundary block") anchor = parent print(f"Got {len(blocks)} public headers and transaction lists", flush=True) for height, block_id, block in zip(heights, block_ids, blocks, strict=True): verify_header(height, block_id, block, parent) parent = block_id verify_source(block_ids, blocks, raw_transactions) keyring, other, outpoints = [], [], [] for block, tx_hex in zip(blocks, raw_transactions, strict=True): txid = block["tx"][0] for index, sats, script in coinbase_outputs(tx_hex, txid): key = pubkey(script) if key is None: other.append((block["height"], txid, index, sats, script.hex())) else: keyring.append((block["height"], txid, index, key)) outpoints.append((txid, index, sats, script.hex())) print(f"Verified {len(raw_transactions)} coinbases and extracted {len(keyring)} public-key rows", flush=True) output.mkdir(parents=True, exist_ok=True) audit = { "firstHeight": start, "lastHeight": end, "blocksVerified": len(blocks), "parentHash": anchor, "firstHash": block_ids[0], "lastHash": block_ids[-1], "firstBlockUtc": datetime.fromtimestamp(blocks[0]["time"], timezone.utc).isoformat(), "lastBlockUtc": datetime.fromtimestamp(blocks[-1]["time"], timezone.utc).isoformat(), "merkleTransactions": sum(block["nTx"] for block in blocks), "p2pkOutputs": len(keyring), "p2pkBlocks": len({height for height, _, _, _ in keyring}), "distinctKeys": len({key for _, _, _, key in keyring}), "compressedKeys": len({key for _, _, _, key in keyring if len(key) == 66}), "otherOutputs": len(other), "keyringSha256": write_csv(output / "keyring.csv", ("height", "txid", "vout", "pubkey"), keyring), "otherSha256": write_csv(output / "other_coinbase_outputs.csv", ("height", "txid", "vout", "sats", "script"), other), "source": "AWS Public Blockchain Data" if objects else NODE, "parquetKeys": [key for _, _, key in objects], "utxoSnapshot": None, } manifest = output / "audit.json" manifest.write_text(json.dumps(audit, indent=2) + "\n", encoding="utf-8") print(json.dumps({key: value for key, value in audit.items() if key not in {"utxoSnapshot", "parquetKeys"}}), flush=True) if spends: audit["utxoSnapshot"] = count_utxos(outpoints) manifest.write_text(json.dumps(audit, indent=2) + "\n", encoding="utf-8") print(json.dumps({key: value for key, value in audit["utxoSnapshot"].items() if key != "unspentOutpoints"})) if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("start", type=int) parser.add_argument("end", type=int) parser.add_argument("output", type=Path) parser.add_argument("--utxo", action="store_true", help="verify confirmed spend counts against one live Bitcoin tip") parser.add_argument("--aws-cache", type=Path, help="rebuild from public AWS Parquet files cached here") args = parser.parse_args() if not 0 <= args.start <= args.end < 481824: parser.error("Select an inclusive range of heights before SegWit activation") rebuild(args.start, args.end, args.output, args.utxo, args.aws_cache)