#!/usr/bin/env python3 """Spend status for a keyring CSV via a public esplora API. Usage: spends.py KEYRING.csv [--api mempool|blockstream] [--out spends.csv] [--sleep 0.08] CSV: height,txid,vout,spent,spend_txid,spend_vin,spend_height,spend_time,value_sats """ from __future__ import annotations import argparse, csv, hashlib, json, sys, time, urllib.request, datetime APIS = { "mempool": "https://mempool.space/api", "blockstream": "https://blockstream.info/api", } 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 main(): ap = argparse.ArgumentParser() ap.add_argument("csv_path") ap.add_argument("--api", default="mempool", choices=APIS) ap.add_argument("--out", default="-") ap.add_argument("--sleep", type=float, default=0.08) args = ap.parse_args() base = APIS[args.api] tip = int(get(f"{base}/blocks/tip/height").decode().strip()) rows = [] with open(args.csv_path, newline="") as f: r = csv.DictReader(f) if r.fieldnames != ["height", "txid", "vout", "pubkey"]: raise SystemExit(f"unexpected header: {r.fieldnames}") for rec in r: rows.append((int(rec["height"]), rec["txid"], int(rec["vout"]))) out_rows = [] for i, (h, txid, vout) in enumerate(rows, 1): os_ = json.loads(get(f"{base}/tx/{txid}/outspend/{vout}")) spent = bool(os_.get("spent")) spend_txid = os_.get("txid") or "" spend_vin = os_.get("vin") if spent and os_.get("vin") is not None else "" st = os_.get("status") or {} spend_height = st.get("block_height") if spent else "" spend_time = st.get("block_time") if spent else "" # value: lazy, filled later in a second pass only if needed; record blank then fill from first uncached out_rows.append({ "height": h, "txid": txid, "vout": vout, "spent": "1" if spent else "0", "spend_txid": spend_txid, "spend_vin": spend_vin, "spend_height": spend_height if spend_height not in (None, "") else "", "spend_time": spend_time if spend_time not in (None, "") else "", }) if i % 50 == 0 or i == len(rows): print(f" outspend {i}/{len(rows)} spent={sum(1 for x in out_rows if x['spent']=='1')}", flush=True) time.sleep(args.sleep) # fill values from a sample of coinbase txs (all should be 50 BTC in this era); verify first, mid, last values = {} sample = [0, len(rows)//2, len(rows)-1] for idx in sample: h, txid, vout = rows[idx] tx = json.loads(get(f"{base}/tx/{txid}")) v = tx["vout"][vout]["value"] values[txid] = v value_set = set(values.values()) # if all samples equal, apply to all; else fetch all if len(value_set) == 1: default_val = next(iter(value_set)) for rec in out_rows: rec["value_sats"] = default_val print(f"value_sats uniform sample={default_val} at tip={tip}", flush=True) else: print(f"value_sats NOT uniform in sample {values}; fetching all", flush=True) for rec in out_rows: tx = json.loads(get(f"{base}/tx/{rec['txid']}")) rec["value_sats"] = tx["vout"][int(rec["vout"])]["value"] time.sleep(args.sleep) header = "height,txid,vout,spent,spend_txid,spend_vin,spend_height,spend_time,value_sats\n" lines = [header] for rec in out_rows: lines.append("{height},{txid},{vout},{spent},{spend_txid},{spend_vin},{spend_height},{spend_time},{value_sats}\n".format(**rec)) blob = "".join(lines).encode() digest = hashlib.sha256(blob).hexdigest() if args.out == "-": sys.stdout.buffer.write(blob) else: with open(args.out, "wb") as f: f.write(blob) spent_n = sum(1 for x in out_rows if x["spent"] == "1") unspent_n = len(out_rows) - spent_n unspent_sats = sum(int(x["value_sats"]) for x in out_rows if x["spent"] == "0") spent_times = [int(x["spend_time"]) for x in out_rows if x["spent"] == "1" and x["spend_time"] != ""] spent_heights = [int(x["spend_height"]) for x in out_rows if x["spent"] == "1" and x["spend_height"] != ""] years = {} for t in spent_times: y = datetime.datetime.utcfromtimestamp(t).year years[y] = years.get(y, 0) + 1 last_move = "" first_move = "" if spent_times: last = max(spent_times) first = min(spent_times) last_move = datetime.datetime.utcfromtimestamp(last).strftime("%Y-%m-%d") first_move = datetime.datetime.utcfromtimestamp(first).strftime("%Y-%m-%d") period_end = max(h for h,_,_ in rows) spent_inside = sum(1 for x in out_rows if x["spent"]=="1" and x["spend_height"]!="" and int(x["spend_height"]) <= period_end) summary = { "tip": tip, "rows": len(out_rows), "spent": spent_n, "unspent": unspent_n, "unspent_sats": unspent_sats, "unspent_btc": unspent_sats / 1e8, "first_move": first_move, "last_move": last_move, "first_spend_height": min(spent_heights) if spent_heights else None, "last_spend_height": max(spent_heights) if spent_heights else None, "spent_inside_period": spent_inside, "spends_by_year": {str(k): years[k] for k in sorted(years)}, "sha256": digest, "bytes": len(blob), "api": args.api, } print(json.dumps(summary, indent=2), file=sys.stderr) print(f"wrote {args.out} sha256={digest} bytes={len(blob)}", file=sys.stderr) return 0 if __name__ == "__main__": sys.exit(main())