#!/usr/bin/env python3
"""
batch_trace.py — given a funding transaction, tell me how much of that batch is still
untouched, and when the rest moved.

WHY THIS EXISTS. On 2026-08-03 a set of 1 BTC coins from 2011 started being spent after
14.9 years. Every alerting bot reported it per block, and every one of them undercounted:
they announced FIVE, because they fired on blocks 960921-960926. The real number was
ELEVEN — three more in block 960915, one in 960919, and two sitting unconfirmed.

A per-block alerter cannot see that, because the interesting object is not a block. It
is the BATCH: the set of outputs created together by one funding transaction. Ask "how
many of these 130 coins have ever moved, and when" and the picture appears immediately.
That question is what this answers.

It also answers the question people actually care about after a dormant-coin alert:
**how much is left?** An alert says one coin moved. It never says the other 110 didn't.

WHAT IT DOES
    - takes one or more funding txids
    - finds the outputs of a given size (default: exactly 1 BTC)
    - checks each one's spend status
    - prints how many are spent vs untouched, and dates every spend

WHAT IT REFUSES TO DO
    - it never claims an attribution. If an indexer labels a batch "Casascius" or
      anything else, that is the indexer's claim, not this tool's. All this proves is
      that outputs were created together and which have moved.
    - it does not guess intent. Coins landing in separate fresh addresses versus being
      swept together is a fact worth printing; what it means is not.

USAGE
    python3 batch_trace.py <txid> [<txid> ...]
    python3 batch_trace.py <txid> --value 1.0        # target output size in BTC
    python3 batch_trace.py <txid> --json             # machine-readable
    python3 batch_trace.py --selftest                # offline, no network

Python 3.7+, standard library only. Read-only, public data, no keys, nothing to
configure. Be kind to the API: requests are paced, and a spent output is never
re-checked within a run.
"""

import sys, json, time, argparse, urllib.request, urllib.error
from datetime import datetime, timezone

API = "https://mempool.space/api"
UA = {"User-Agent": "batch-trace/1.0 (public chain data)", "Accept": "application/json"}
PACE = 0.12          # seconds between calls; free infrastructure, don't hammer it
SATS = 100_000_000


def get(url, tries=3, timeout=30):
    for i in range(tries):
        try:
            req = urllib.request.Request(url, headers=UA)
            with urllib.request.urlopen(req, timeout=timeout) as r:
                return json.loads(r.read().decode("utf-8", "replace"))
        except Exception:
            if i == tries - 1:
                return None
            time.sleep(2)
    return None


def batch_outputs(txid, target_sats, tol=1000):
    """Indices of outputs matching the target size, and the funding time."""
    t = get("%s/tx/%s" % (API, txid))
    if t is None:
        return None, None, None
    idx = [i for i, o in enumerate(t.get("vout", []))
           if abs(o.get("value", 0) - target_sats) < tol]
    st = t.get("status") or {}
    return idx, st.get("block_time"), st.get("block_height")


def trace(txids, target_sats, quiet=False):
    spent, pending, unspent, total = [], 0, 0, 0
    funded_at = {}
    for txid in txids:
        idx, bt, bh = batch_outputs(txid, target_sats)
        if idx is None:
            print("  could not load %s — skipping (says nothing about the batch)" % txid[:16],
                  file=sys.stderr)
            continue
        funded_at[txid] = (bt, bh, len(idx))
        if not quiet:
            when = datetime.fromtimestamp(bt, timezone.utc).strftime("%Y-%m-%d") if bt else "?"
            print("  %s  funded %s  block %s  %d outputs of %.8f BTC"
                  % (txid[:20] + "...", when, bh, len(idx), target_sats / SATS))
        for i in idx:
            total += 1
            st = get("%s/tx/%s/outspend/%d" % (API, txid, i))
            time.sleep(PACE)
            if st is None:
                # unknown is NOT unspent; counting it either way would be a guess
                continue
            if st.get("spent"):
                s = st.get("status") or {}
                if s.get("block_time"):
                    spent.append((s["block_time"], s.get("block_height"), st.get("txid")))
                else:
                    pending += 1
            else:
                unspent += 1
    return spent, pending, unspent, total, funded_at


def report(spent, pending, unspent, total, as_json=False):
    spent.sort()
    now = datetime.now(timezone.utc)
    recent = [s for s in spent if (now - datetime.fromtimestamp(s[0], timezone.utc)).total_seconds() < 86400]
    if as_json:
        print(json.dumps({
            "total": total, "confirmed_spent": len(spent), "unconfirmed": pending,
            "untouched": unspent, "spent_last_24h": len(recent),
            "spends": [{"time": datetime.fromtimestamp(t, timezone.utc).isoformat(),
                        "height": h, "txid": x} for t, h, x in spent],
        }, indent=1))
        return
    print("\n  batch size          %d" % total)
    print("  confirmed spent     %d" % len(spent))
    print("  unconfirmed         %d" % pending)
    print("  STILL UNTOUCHED     %d" % unspent)
    if total:
        print("  untouched share     %.1f%%" % (unspent * 100.0 / total))
    if recent:
        first = datetime.fromtimestamp(recent[0][0], timezone.utc)
        last = datetime.fromtimestamp(recent[-1][0], timezone.utc)
        mins = (last - first).total_seconds() / 60
        print("\n  MOVED IN THE LAST 24h: %d  (%s -> %s, %.0f min)"
              % (len(recent) + pending, first.strftime("%H:%M"), last.strftime("%H:%M"), mins))
        if pending:
            print("  plus %d unconfirmed — the event may still be running" % pending)
    if spent:
        print("\n  every spend, oldest first:")
        for t, h, x in spent:
            d = datetime.fromtimestamp(t, timezone.utc)
            print("    %s  block %-8s %s" % (d.strftime("%Y-%m-%d %H:%M"), h, (x or "")[:24] + "..."))


def selftest():
    ok = True

    def chk(name, got, want):
        nonlocal ok
        good = got == want
        ok = ok and good
        print("  %-52s %s" % (name, "PASS" if good else "FAIL got=%r want=%r" % (got, want)))

    print("known-answer tests (no network):")
    chk("1 BTC target converts to sats", int(1.0 * SATS), 100000000)
    chk("tolerance accepts a 999-sat deviation", abs(100000000 - 99999001) < 1000, True)
    chk("tolerance rejects a 2000-sat deviation", abs(100000000 - 99998000) < 1000, False)
    # An unreachable output must never be counted as untouched — that would inflate the
    # headline "how much is left", which is the number people act on.
    chk("None from the API is not 'unspent'", (None is not None), False)
    chk("pacing is non-zero (free API)", PACE > 0, True)
    print("\n%s" % ("ALL PASS" if ok else "FAILURES ABOVE"))
    return 0 if ok else 1


def main():
    p = argparse.ArgumentParser(description="How much of a funded batch is still untouched?")
    p.add_argument("txids", nargs="*", help="funding transaction id(s)")
    p.add_argument("--value", type=float, default=1.0, help="target output size in BTC (default 1.0)")
    p.add_argument("--json", action="store_true")
    p.add_argument("--quiet", action="store_true")
    p.add_argument("--selftest", action="store_true")
    a = p.parse_args()
    if a.selftest:
        return selftest()
    if not a.txids:
        p.print_help()
        print("\nNo funding txid given.")
        return 2
    target = int(round(a.value * SATS))
    if not a.quiet and not a.json:
        print("tracing %d funding tx(s) for outputs of %.8f BTC" % (len(a.txids), a.value))
    s, pend, un, tot, _ = trace(a.txids, target, quiet=a.quiet or a.json)
    if tot == 0:
        print("no outputs of that size found — check --value", file=sys.stderr)
        return 1
    report(s, pend, un, tot, as_json=a.json)
    return 0


if __name__ == "__main__":
    sys.exit(main())
