=== fetch.py === #!/usr/bin/env python3 """Cached, rate-limit-aware fetcher for period-67 (blocks 133056..135071) Esplora data. Stages: blocks -> /blocks/ for start heights stepping -10 (10 summaries per call) txids -> /block//txids only for blocks with tx_count > 1 tx -> /tx/ for every block outspends -> /tx//outspends for every block All responses are cached verbatim under cache// so reruns are free. """ import json, os, sys, time, random, threading import urllib.request, urllib.error from concurrent.futures import ThreadPoolExecutor ROOT = os.path.dirname(os.path.abspath(__file__)) CACHE = os.path.join(ROOT, "cache") BASE = "https://blockstream.info/api" ALT = "https://mempool.space/api" FIRST, LAST = 133056, 135071 _print_lock = threading.RLock() def log(msg): with _print_lock: print(f"[{time.strftime('%H:%M:%S')}] {msg}", flush=True) # Global pace limiter: Esplora tolerates short bursts then drops/hangs the IP. RATE_LOCK = threading.Lock() MIN_INTERVAL = float(os.environ.get("MIN_INTERVAL", "0.12")) # seconds between request starts _last_start = [0.0] def _pace(): with RATE_LOCK: now = time.time() wait = _last_start[0] + MIN_INTERVAL - now if wait > 0: time.sleep(wait) now = time.time() _last_start[0] = now def http_get(path, tries=7): """GET path from primary base, falling back to ALT, with backoff. Returns bytes.""" last_err = None for attempt in range(tries): bases = [BASE, ALT] if attempt % 2 == 0 else [ALT, BASE] for base in bases: try: _pace() req = urllib.request.Request(base + path, headers={ "User-Agent": "genesis-keyring-ledger/1.0 (research)", "Accept": "application/json", }) with urllib.request.urlopen(req, timeout=15) as r: return r.read() except urllib.error.HTTPError as e: last_err = f"{base}{path} -> HTTP {e.code}" if e.code in (429, 500, 502, 503, 504) or e.code >= 500: continue raise except Exception as e: # network errors, timeouts last_err = f"{base}{path} -> {type(e).__name__}: {e}" continue sleep = min(10.0, 1.0 * (2 ** attempt)) + random.uniform(0, 1.0) log(f"BACKOFF {sleep:.1f}s after {last_err}") time.sleep(sleep) raise RuntimeError(f"giving up on {path}: {last_err}") def cache_path(stage, name): d = os.path.join(CACHE, stage) os.makedirs(d, exist_ok=True) return os.path.join(d, name + ".json") def get_cached(stage, name, path): fp = cache_path(stage, name) if os.path.exists(fp): with open(fp, "rb") as f: return json.loads(f.read()) data = http_get(path) with open(fp, "wb") as f: f.write(data) return json.loads(data) CONC = int(os.environ.get('CONC', '5')) def fetch_many(items, fn, concurrency, label): """items: list of tuples passed to fn. Cached calls don't consume concurrency slots fast.""" n = len(items) done = [0] t0 = time.time() fails = [] def wrapped(it): try: fn(it) except Exception as e: fails.append((it, repr(e))) finally: with _print_lock: done[0] += 1 if done[0] % 50 == 0 or done[0] == n: el = time.time() - t0 rate = done[0] / el if el else 0 eta = (n - done[0]) / rate if rate else 0 log(f"{label}: {done[0]}/{n} {rate:.2f}/s eta {eta/60:.1f} min") with ThreadPoolExecutor(max_workers=concurrency) as ex: list(ex.map(wrapped, items)) if fails: log(f"{label}: {len(fails)} FAILURES, first: {fails[0]}") return False return True # ---------- manifest from cache ---------- def load_blocks(): blocks = {} for start in range(LAST, FIRST - 1, -10): fp = cache_path("blocks", str(start)) if not os.path.exists(fp): raise SystemExit(f"missing block summary cache for start {start}") with open(fp) as f: arr = json.load(f) for b in arr: if FIRST <= b["height"] <= LAST: blocks[b["height"]] = b if len(blocks) != LAST - FIRST + 1: raise SystemExit(f"block count {len(blocks)} != {LAST-FIRST+1}") return [blocks[h] for h in range(FIRST, LAST + 1)] def stage_blocks(): starts = list(range(LAST, FIRST - 1, -10)) def fn(start): get_cached("blocks", str(start), f"/blocks/{start}") ok = fetch_many(starts, fn, CONC, "blocks") if not ok: return # previous-block hash of FIRST, for the chain link check (plain text, not JSON) fp = os.path.join(CACHE, "extra", f"block-height-{FIRST-1}.txt") if not os.path.exists(fp): os.makedirs(os.path.dirname(fp), exist_ok=True) with open(fp, "wb") as f: f.write(http_get(f"/block-height/{FIRST-1}")) log("extra: previous block hash for 28224 cached") log(f"blocks: {len(load_blocks())} summaries cached") def stage_txids(): blocks = load_blocks() multi = [b for b in blocks if b["tx_count"] > 1] log(f"txids: {len(multi)} blocks with tx_count>1 out of {len(blocks)}") def fn(b): get_cached("txids", b["id"], f"/block/{b['id']}/txids") ok = fetch_many(multi, fn, CONC, "txids") if ok: log("txids: done") def coinbase_txids(): """Return list of (height, coinbase_txid, block). Single-tx: txid == merkle_root.""" blocks = load_blocks() out = [] for b in blocks: if b["tx_count"] == 1: cb = b["merkle_root"] else: with open(cache_path("txids", b["id"])) as f: txids = json.load(f) cb = txids[0] out.append((b["height"], cb, b)) return out def stage_tx(): items = coinbase_txids() def fn(it): h, cb, b = it get_cached("tx", cb, f"/tx/{cb}") ok = fetch_many(items, fn, CONC, "tx") if ok: log("tx: done") def stage_outspends(): items = coinbase_txids() def fn(it): h, cb, b = it get_cached("outspends", cb, f"/tx/{cb}/outspends") ok = fetch_many(items, fn, CONC, "outspends") if ok: log("outspends: done") STAGES = {"blocks": stage_blocks, "txids": stage_txids, "tx": stage_tx, "outspends": stage_outspends} if __name__ == "__main__": stage = sys.argv[1] if stage == "all": for s in ["blocks", "txids", "tx", "outspends"]: STAGES[s]() else: STAGES[stage]() === build_verify.py === #!/usr/bin/env python3 """Build and fully verify the Genesis Keyring ledger for Bitcoin difficulty period 67 (blocks 133,056 .. 135,071). Reads cached Esplora responses from ./cache (see fetch.py), writes period67.csv, spends.csv, summary.json and lead.md. Verification performed: A. Every block header is rebuilt from its fields, double-SHA-256'd -> must equal block id, must satisfy the PoW target encoded in bits. B. Every block's previousblockhash must equal the previous block's id (chain link); block 133056's link is checked against block 133055 fetched from Esplora. C. Every coinbase transaction is rebuilt in original serialization from its fields and double-SHA-256'd -> byte-reversed must equal its txid (and the txid tied to the block). D. Merkle root recomputed from the block's txid list (coinbase first) -> must equal the header's merkle_root (single-tx blocks: coinbase txid == merkle root). E. P2PK output extraction: script == 0x41 || 65-byte uncompressed pubkey || 0xac, key starts 04. F. Spend status from /tx//outspends. G. Optional cross-check of 50 random blocks against mempool.space (separate API instance). """ import json, os, sys, hashlib, random, time sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from fetch import http_get, cache_path, load_blocks, coinbase_txids, FIRST, LAST, CACHE, log ROOT = os.path.dirname(os.path.abspath(__file__)) def sha256d(b): return hashlib.sha256(hashlib.sha256(b).digest()).digest() def varint(n): if n < 0xfd: return bytes([n]) if n <= 0xffff: return b"\xfd" + n.to_bytes(2, "little") if n <= 0xffffffff: return b"\xfe" + n.to_bytes(4, "little") return b"\xff" + n.to_bytes(8, "little") def ser_tx(tx): out = bytearray() out += int(tx["version"]).to_bytes(4, "little") out += varint(len(tx["vin"])) for i in tx["vin"]: out += bytes.fromhex(i["txid"])[::-1] out += int(i["vout"]).to_bytes(4, "little") ss = bytes.fromhex(i["scriptsig"]) out += varint(len(ss)) + ss out += int(i["sequence"]).to_bytes(4, "little") out += varint(len(tx["vout"])) for o in tx["vout"]: out += int(o["value"]).to_bytes(8, "little") sp = bytes.fromhex(o["scriptpubkey"]) out += varint(len(sp)) + sp out += int(tx["locktime"]).to_bytes(4, "little") return bytes(out) def ser_header(b): return (int(b["version"]).to_bytes(4, "little") + bytes.fromhex(b["previousblockhash"])[::-1] + bytes.fromhex(b["merkle_root"])[::-1] + int(b["timestamp"]).to_bytes(4, "little") + int(b["bits"]).to_bytes(4, "little") + int(b["nonce"]).to_bytes(4, "little")) def target_from_bits(bits): exp = bits >> 24 mant = bits & 0x007fffff if exp <= 3: return mant >> (8 * (3 - exp)) return mant << (8 * (exp - 3)) def merkle_root(txids): """txids in display hex order; returns display hex merkle root.""" layer = [bytes.fromhex(t)[::-1] for t in txids] while len(layer) > 1: if len(layer) % 2: layer.append(layer[-1]) layer = [sha256d(layer[i] + layer[i + 1]) for i in range(0, len(layer), 2)] return layer[0][::-1].hex() def main(): t0 = time.time() blocks = load_blocks() assert len(blocks) == LAST - FIRST + 1 == 2016 cb_list = coinbase_txids() assert len(cb_list) == 2016 prev22 = open(os.path.join(CACHE, "extra", f"block-height-{FIRST-1}.txt")).read().strip() res = { "period": 67, "first_height": FIRST, "last_height": LAST, "blocks_expected": 2016, "blocks_processed": 0, "rows": 0, "distinct_pubkeys": 0, "multi_output_coinbases": [], "blocks_no_p2pk": [], "spent": 0, "unspent": 0, "spend_records": 0, "verification": { "headers_checked": 0, "header_hash_matches": 0, "pow_met": 0, "prev_links_ok": 0, "txid_rebuild_checked": 0, "txid_rebuild_matches": 0, "merkle_checked": 0, "merkle_matches": 0, "tx_block_binding_ok": 0, "failures": [], }, "crosscheck": {}, } rows, spend_rows = [], [] prev_id = prev22 V = res["verification"] for idx, (h, cb, b) in enumerate(cb_list): res["blocks_processed"] += 1 if b["height"] != h: V["failures"].append(f"height mismatch block {b['height']} vs {h}") if b["previousblockhash"] != prev_id: V["failures"].append(f"prev-link mismatch at {h}") else: V["prev_links_ok"] += 1 prev_id = b["id"] # ---- A. header rebuild + hash + PoW hdr = ser_header(b) digest = sha256d(hdr) V["headers_checked"] += 1 if digest[::-1].hex() == b["id"]: V["header_hash_matches"] += 1 else: V["failures"].append(f"header hash mismatch at {h}") tgt = target_from_bits(int(b["bits"])) if int.from_bytes(digest, "little") <= tgt and tgt > 0: V["pow_met"] += 1 else: V["failures"].append(f"PoW fail at {h}") # ---- C. coinbase tx rebuild tx = json.load(open(cache_path("tx", cb))) raw = ser_tx(tx) built = sha256d(raw)[::-1].hex() V["txid_rebuild_checked"] += 1 if built == cb and tx.get("txid") == cb: V["txid_rebuild_matches"] += 1 else: V["failures"].append(f"txid rebuild mismatch at {h}: {built} vs {cb}") if tx["status"].get("block_height") == h and tx["status"].get("block_hash") == b["id"]: V["tx_block_binding_ok"] += 1 else: V["failures"].append(f"tx not bound to its block at {h}") if not (len(tx["vin"]) == 1 and tx["vin"][0].get("is_coinbase")): V["failures"].append(f"tx at {h} is not a coinbase") # ---- D. merkle root if b["tx_count"] == 1: txids = [cb] else: txids = json.load(open(cache_path("txids", b["id"]))) if len(txids) != b["tx_count"]: V["failures"].append(f"tx_count mismatch at {h}") if txids[0] != cb: V["failures"].append(f"first txid not coinbase at {h}") mr = merkle_root(txids) V["merkle_checked"] += 1 if mr == b["merkle_root"]: V["merkle_matches"] += 1 else: V["failures"].append(f"merkle mismatch at {h}: {mr} vs {b['merkle_root']}") # ---- E. P2PK outputs p2pk = [] if len(tx["vout"]) > 1: res["multi_output_coinbases"].append(h) for vi, o in enumerate(tx["vout"]): spk = o["scriptpubkey"] if o.get("scriptpubkey_type") == "p2pk" and spk.startswith("41") and spk.endswith("ac") and len(spk) == 134: pk = spk[2:132] if len(pk) == 130 and pk.startswith("04"): p2pk.append((vi, pk)) rows.append({"height": h, "txid": cb, "vout": vi, "pubkey": pk}) if not p2pk: res["blocks_no_p2pk"].append(h) # ---- F. spends osp = json.load(open(cache_path("outspends", cb))) if len(osp) != len(tx["vout"]): V["failures"].append(f"outspends length mismatch at {h}") for vi, pk in p2pk: o = osp[vi] if vi < len(osp) else {} if o.get("spent"): res["spent"] += 1 st = o.get("status") or {} spend_rows.append({"height": h, "txid": cb, "vout": vi, "spent_txid": o.get("txid", ""), "spent_height": st.get("block_height", ""), "spent_block_hash": st.get("block_hash", "")}) else: res["unspent"] += 1 rows.sort(key=lambda r: (r["height"], r["vout"])) res["rows"] = len(rows) res["distinct_pubkeys"] = len({r["pubkey"] for r in rows}) res["spend_records"] = len(spend_rows) # ---- CSV csv_path = os.path.join(ROOT, "period67.csv") with open(csv_path, "w") as f: f.write("height,txid,vout,pubkey\n") for r in rows: f.write(f"{r['height']},{r['txid']},{r['vout']},{r['pubkey']}\n") csv_sha = hashlib.sha256(open(csv_path, "rb").read()).hexdigest() with open(csv_path + ".sha256", "w") as f: f.write(f"{csv_sha} period67.csv\n") res["csv_sha256"] = csv_sha sp_path = os.path.join(ROOT, "spends.csv") with open(sp_path, "w") as f: f.write("height,txid,vout,spent_txid,spent_height,spent_block_hash\n") for r in spend_rows: f.write(f"{r['height']},{r['txid']},{r['vout']},{r['spent_txid']},{r['spent_height']},{r['spent_block_hash']}\n") res["spends_csv_sha256"] = hashlib.sha256(open(sp_path, "rb").read()).hexdigest() # ---- G. cross-check 50 random blocks against mempool.space rng = random.Random(14) sample = sorted(rng.sample(range(FIRST, LAST + 1), 50)) by_h = {r["height"]: r for r in rows} cc = {"blocks": len(sample), "height_hash_ok": 0, "first_txid_ok": 0, "blocks_ok": 0, "problems": []} for h in sample: try: mh = http_get(f"/block-height/{h}").decode().strip() except Exception as e: cc["problems"].append(f"{h}: block-height fetch {e!r}"); continue mine = {b["height"]: b for b in blocks}[h] if mh == mine["id"]: cc["height_hash_ok"] += 1 else: cc["problems"].append(f"{h}: hash {mh} != {mine['id']}") try: mtx = json.loads(http_get(f"/block/{mh}/txids")) except Exception as e: cc["problems"].append(f"{h}: txids fetch {e!r}"); continue r = by_h.get(h) if r and mtx and mtx[0] == r["txid"]: cc["first_txid_ok"] += 1 else: cc["problems"].append(f"{h}: first txid differs") if len(mtx) == mine["tx_count"]: cc["blocks_ok"] += 1 else: cc["problems"].append(f"{h}: tx_count {len(mtx)} vs {mine['tx_count']}") time.sleep(0.05) res["crosscheck"] = cc with open(os.path.join(ROOT, "summary.json"), "w") as f: json.dump(res, f, indent=2) log(f"rows={res['rows']} distinct={res['distinct_pubkeys']} spent={res['spent']} unspent={res['unspent']}") log(f"failures={len(V['failures'])}") log(f"csv sha256={csv_sha}") log(f"crosscheck={ {k: v for k, v in cc.items() if k != 'problems'} } problems={len(cc['problems'])}") log(f"elapsed {time.time()-t0:.1f}s") if __name__ == "__main__": main()