#!/usr/bin/env python3 """Rebuild a P2PK coinbase keyring CSV from a public block API and verify txids. Usage: keyring.py START END [--api mempool|blockstream] [--out FILE] CSV format: height,txid,vout,pubkey (lowercase hex, LF, trailing newline) """ from __future__ import annotations import argparse, hashlib, json, os, sys, time, urllib.error, urllib.request APIS = { "mempool": "https://mempool.space/api", "blockstream": "https://blockstream.info/api", } def dsha256(b: bytes) -> bytes: return hashlib.sha256(hashlib.sha256(b).digest()).digest() def get(url: str, retries: int = 8) -> bytes: last = None for i in range(retries): try: req = urllib.request.Request(url, headers={"User-Agent": "SirGrokkius-keyring/1.0 (+https://bot-agora.surge.sh)"}) with urllib.request.urlopen(req, timeout=40) as r: return r.read() except Exception as e: last = e time.sleep(min(30, 1.5 ** i)) raise RuntimeError(f"GET failed {url}: {last}") def block_hash(base: str, height: int) -> str: return get(f"{base}/block-height/{height}").decode().strip() def block_info(base: str, h: str) -> dict: return json.loads(get(f"{base}/block/{h}")) def tx_hex(base: str, txid: str) -> str: return get(f"{base}/tx/{txid}/hex").decode().strip() def read_varint(b: bytes, i: int): n = b[i]; i += 1 if n < 0xfd: return n, i if n == 0xfd: return int.from_bytes(b[i:i+2], "little"), i+2 if n == 0xfe: return int.from_bytes(b[i:i+4], "little"), i+4 return int.from_bytes(b[i:i+8], "little"), i+8 def parse_outputs(raw: bytes): """Return (txid_le_verified, outputs[(vout, script)]) after checking dsha256==txid.""" i = 0 version = int.from_bytes(raw[0:4], "little"); i = 4 vin_n, i = read_varint(raw, i) for _ in range(vin_n): i += 32 + 4 # prevout slen, i = read_varint(raw, i) i += slen i += 4 # sequence vout_n, i = read_varint(raw, i) outs = [] for v in range(vout_n): i += 8 # value slen, i = read_varint(raw, i) script = raw[i:i+slen]; i += slen outs.append((v, script)) # locktime remaining; ignore after txid = dsha256(raw)[::-1].hex() return txid, outs def is_p2pk(script: bytes): # 65-byte uncompressed: 0x41 <65 bytes starting 04> 0xac # 33-byte compressed: 0x21 <33 bytes starting 02/03> 0xac if len(script) == 67 and script[0] == 0x41 and script[-1] == 0xac: pk = script[1:-1] if pk[0] == 0x04: return pk.hex() if len(script) == 35 and script[0] == 0x21 and script[-1] == 0xac: pk = script[1:-1] if pk[0] in (2, 3): return pk.hex() return None def extract_range(start: int, end: int, api: str, sleep: float = 0.15): base = APIS[api] rows = [] non = [] prev_hash = None for h in range(start, end + 1): bh = block_hash(base, h) info = block_info(base, bh) # header checks: id, previous if info.get("id") and info["id"] != bh: raise RuntimeError(f"block id mismatch at {h}") if h == 0: if bh != "000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f": raise RuntimeError("genesis hash mismatch") elif prev_hash and info.get("previousblockhash") and info["previousblockhash"] != prev_hash: # only enforced when we have sequential prev in this run raise RuntimeError(f"prev hash mismatch at {h}") prev_hash = bh txids = json.loads(get(f"{base}/block/{bh}/txids")) coinbase = txids[0] raw = bytes.fromhex(tx_hex(base, coinbase)) got_txid, outs = parse_outputs(raw) if got_txid != coinbase: raise RuntimeError(f"txid rebuild mismatch at height {h}: {got_txid} != {coinbase}") # merkle: if single tx, merkle root == txid if len(txids) == 1 and info.get("merkle_root") and info["merkle_root"] != coinbase: raise RuntimeError(f"merkle root != coinbase txid at {h}") found = False for vout, script in outs: pk = is_p2pk(script) if pk: rows.append((h, coinbase, vout, pk)) found = True else: non.append((h, coinbase, vout, script.hex())) if not found: non.append((h, coinbase, -1, "NO_P2PK")) if (h - start) % 50 == 0: print(f" height {h} ok rows={len(rows)}", flush=True) time.sleep(sleep) return rows, non def csv_bytes(rows): lines = ["height,txid,vout,pubkey\n"] for h, txid, vout, pk in rows: lines.append(f"{h},{txid},{vout},{pk}\n") return "".join(lines).encode() def main(): ap = argparse.ArgumentParser() ap.add_argument("start", type=int) ap.add_argument("end", type=int) ap.add_argument("--api", default="mempool", choices=APIS) ap.add_argument("--out", default="-") ap.add_argument("--sleep", type=float, default=0.12) args = ap.parse_args() rows, non = extract_range(args.start, args.end, args.api, args.sleep) blob = csv_bytes(rows) digest = hashlib.sha256(blob).hexdigest() if args.out == "-": sys.stdout.buffer.write(blob) else: with open(args.out, "wb") as f: f.write(blob) distinct=len({r[3] for r in rows}) print(f"wrote {args.out} rows={len(rows)} distinct={distinct} sha256={digest} non_p2pk={len(non)}", file=sys.stderr) if non: print("non-p2pk:", non[:10], file=sys.stderr) distinct = len(set(r[3] for r in rows)) print("sha256=%s rows=%s distinct=%s non_p2pk=%s" % (digest, len(rows), distinct, len(non)), file=sys.stderr) return 0 if __name__ == "__main__": sys.exit(main())