Audit Your Bitcoin UTXOs for Post-Quantum Exposure (100% Offline, Zero-Dependency Python Script)

Following the Dec 3, 2026 Bitcoin Core contributor joint statement on PQ signatures, here is how to classify your own UTXOs completely offline (P2TR/P2PK/reused vs fresh P2WPKH/P2WSH) without leaking your xpub.

Following today’s joint statement from Bitcoin Core contributors (Antoine Poinsot, Cory Fields, Greg Sanders, Jonas Nick, Matt Corallo, Michael Ford, Murch, Pieter Wuille, and Tim Ruffing) prioritizing post-quantum signature proposals (targeting draft BIPs by end of January 2027), the most practical question for self-custody holders right now is:

Which of my UTXOs already have an elliptic-curve public key exposed on-chain at rest, and which ones should I NOT touch yet?

Do not paste your xpub, zpub, or address list into random web checkers — that permanently leaks your wallet cluster and balance history. You can audit your own UTXO set completely offline in 10 seconds.


1. What is actually exposed at rest today?

Script Type Address Prefix Pubkey Exposed at Rest? Action Today
P2PK (legacy raw key) YES — raw pubkey in scriptPubKey Migrate to fresh P2WPKH or P2WSH
P2TR (Taproot) bc1p... YES — 32-byte tweaked x-only pubkey sits directly in scriptPubKey even if never spent Consider migrating cold storage to fresh P2WPKH / P2WSH
Reused P2PKH / P2WPKH / P2SH / P2WSH 1..., 3..., bc1q... YES — any prior spend from that address already revealed the pubkey / script in scriptSig or witness Sweep all remaining UTXOs to a fresh address
Fresh P2WPKH bc1q... (42 chars) NO — only HASH160(pubkey) on-chain until spend Leave alone (moving it exposes pubkey in mempool)
Fresh P2WSH bc1q... (62 chars) NO — only SHA256(witnessScript) on-chain until spend Leave alone (strongest hash-at-rest today)

Two operational traps to avoid:

  1. Do NOT panic-consolidate fresh P2WPKH UTXOs into new P2WPKH outputs. Broadcasting a spend exposes your public key while sitting in the mempool — you gain nothing unless migrating out of P2TR, P2PK, or reused addresses.
  2. Multi-UTXO single-address discipline: If one fresh bc1q... address holds 2+ UTXOs, spending one reveals the pubkey for the remaining UTXOs at that address. Either leave all untouched or sweep all together in one tx.

For context, sampling mainnet blocks 978667–978669 today shows ~9.5% of newly created outputs (~5.9% of BTC value) are still landing in v1_p2tr Taproot outputs with exposed pubkeys at rest, while ~69.7% of outputs use v0_p2wpkh.


2. Usage (100% offline or with your own local node)

Save btc_pq_audit.py below (zero third-party dependencies — Python 3.8+ standard library only, safe on an airgapped machine).

Bitcoin Core (listunspent):

bitcoin-cli listunspent > utxos.json
python3 btc_pq_audit.py utxos.json --fee-rate 3

Sparrow Wallet (UTXOs -> Export CSV):

python3 btc_pq_audit.py sparrow_utxos.csv --fee-rate 3

Check prior address reuse against your own local Esplora / mempool node:

python3 btc_pq_audit.py addresses.txt --esplora http://127.0.0.1:3006/api

3. Complete auditable source (btc_pq_audit.py)

#!/usr/bin/env python3
"""
btc_pq_audit.py — Zero-dependency, airgap-friendly Bitcoin Post-Quantum UTXO Exposure Auditor.

Classifies Bitcoin UTXOs / addresses by whether their elliptic-curve public key is
already exposed on-chain at rest (P2PK, P2TR Taproot, or reused hash-based addresses)
versus hash-protected at rest (fresh P2WPKH / P2WSH / P2PKH / P2SH).

Supports:
  1) `bitcoin-cli listunspent` JSON (100% offline)
  2) Sparrow Wallet UTXOs CSV export (100% offline)
  3) Plain-text address list (offline script classification, or optional --esplora reuse check)

No third-party packages required. Python 3.8+ standard library only.
License: MIT
"""
import argparse
import csv
import json
import sys
import urllib.request
from collections import defaultdict
from pathlib import Path

# Approximate input vbytes per script type when migrating to a fresh P2WPKH/P2WSH output
INPUT_VBYTES = {
    "P2TR": 57.5,
    "P2WPKH": 68.0,
    "P2PKH": 148.0,
    "P2SH": 91.0,      # typical P2SH-P2WPKH
    "P2WSH": 105.0,    # typical 2-of-3 multisig estimate
    "P2PK": 114.0,
    "UNKNOWN": 100.0,
}
OUTPUT_VBYTES_P2WPKH = 31.0
OUTPUT_VBYTES_P2WSH = 43.0
TX_OVERHEAD_VBYTES = 10.5


def classify_address(addr: str) -> str:
    a = addr.strip()
    al = a.lower()
    if al.startswith(("bc1p", "tb1p", "bcrt1p")) and len(a) >= 62:
        return "P2TR"
    if al.startswith(("bc1q", "tb1q", "bcrt1q")):
        # Witness v0: 20-byte program -> 42 chars (mainnet); 32-byte program -> 62 chars (mainnet)
        if len(a) <= 46:
            return "P2WPKH"
        return "P2WSH"
    if a.startswith(("1", "m", "n")):
        return "P2PKH"
    if a.startswith(("3", "2")):
        return "P2SH"
    return "UNKNOWN"


def classify_scriptpubkey_hex(spk: str) -> str:
    s = spk.strip().lower()
    if s.startswith("5120") and len(s) == 68:
        return "P2TR"
    if s.startswith("0014") and len(s) == 44:
        return "P2WPKH"
    if s.startswith("0020") and len(s) == 68:
        return "P2WSH"
    if s.startswith("76a914") and s.endswith("88ac") and len(s) == 50:
        return "P2PKH"
    if s.startswith("a914") and s.endswith("87") and len(s) == 46:
        return "P2SH"
    if s.endswith("ac") and len(s) in (70, 134):
        return "P2PK"
    return "UNKNOWN"


def check_esplora_reuse(addr: str, base_url: str) -> dict:
    """Query an Esplora-compatible API (local node preferred!) for spent tx count & balance."""
    url = f"{base_url.rstrip('/')}/address/{addr}"
    req = urllib.request.Request(url, headers={"User-Agent": "btc-pq-audit/1.0"})
    with urllib.request.urlopen(req, timeout=15) as r:
        data = json.loads(r.read().decode("utf-8"))
    cs = data.get("chain_stats", {})
    ms = data.get("mempool_stats", {})
    spent_count = cs.get("spent_txo_count", 0) + ms.get("spent_txo_count", 0)
    funded_sum = cs.get("funded_txo_sum", 0) + ms.get("funded_txo_sum", 0)
    spent_sum = cs.get("spent_txo_sum", 0) + ms.get("spent_txo_sum", 0)
    return {
        "spent_txo_count": spent_count,
        "balance_sats": funded_sum - spent_sum,
    }


def load_utxos(path: Path, fmt: str) -> list:
    raw = path.read_text(encoding="utf-8").strip()
    if fmt == "auto":
        if raw.startswith("[") or raw.startswith("{"):
            fmt = "core"
        elif "," in raw.splitlines()[0] and "address" in raw.splitlines()[0].lower():
            fmt = "sparrow"
        else:
            fmt = "addresses"

    utxos = []
    if fmt == "core":
        data = json.loads(raw)
        if isinstance(data, dict):
            data = data.get("unspent", data.get("utxos", []))
        for row in data:
            addr = row.get("address", "")
            spk = row.get("scriptPubKey", "")
            stype = classify_scriptpubkey_hex(spk) if spk else classify_address(addr)
            amt_btc = float(row.get("amount", 0.0))
            sats = int(round(amt_btc * 1e8)) if "amount" in row else int(row.get("value", 0))
            utxos.append({
                "txid": row.get("txid", ""),
                "vout": row.get("vout", 0),
                "address": addr,
                "script_type": stype,
                "sats": sats,
                "reused": bool(row.get("reused", False)),
            })
    elif fmt == "sparrow":
        reader = csv.DictReader(raw.splitlines())
        for row in reader:
            norm = {k.strip().lower(): (v or "").strip() for k, v in row.items() if k}
            addr = norm.get("address", "")
            val_str = norm.get("value", norm.get("amount", "0")).replace(",", "")
            sats = int(float(val_str) * 1e8) if "." in val_str else int(val_str or 0)
            utxos.append({
                "txid": norm.get("output", "").split(":")[0],
                "vout": norm.get("output", ":0").split(":")[-1],
                "address": addr,
                "script_type": classify_address(addr),
                "sats": sats,
                "reused": False,
            })
    elif fmt == "addresses":
        for line in raw.splitlines():
            addr = line.strip().split()[0] if line.strip() else ""
            if not addr or addr.startswith("#"):
                continue
            utxos.append({
                "txid": "",
                "vout": 0,
                "address": addr,
                "script_type": classify_address(addr),
                "sats": 0,
                "reused": False,
            })
    else:
        raise ValueError(f"Unsupported format: {fmt}")
    return utxos


def audit(utxos: list, esplora_url: str = None, fee_rate: float = 5.0) -> dict:
    # Detect duplicate addresses inside the active UTXO set (multi-UTXO reuse warning)
    addr_counts = defaultdict(int)
    for u in utxos:
        if u["address"]:
            addr_counts[u["address"]] += 1

    esplora_cache = {}
    if esplora_url:
        for addr in sorted(addr_counts.keys()):
            try:
                esplora_cache[addr] = check_esplora_reuse(addr, esplora_url)
            except Exception as e:
                esplora_cache[addr] = {"error": str(e), "spent_txo_count": 0, "balance_sats": 0}

    exposed = []
    protected = []
    warnings = []

    for u in utxos:
        addr = u["address"]
        stype = u["script_type"]
        sats = u["sats"]
        spent_prior = False

        if addr in esplora_cache and "error" not in esplora_cache[addr]:
            info = esplora_cache[addr]
            if info["spent_txo_count"] > 0:
                spent_prior = True
            if sats == 0 and info["balance_sats"] > 0:
                sats = info["balance_sats"]

        reused_onchain = u["reused"] or spent_prior
        multi_utxo_same_addr = addr_counts[addr] > 1

        reason = None
        if stype == "P2PK":
            reason = "P2PK raw public key embedded directly in scriptPubKey"
        elif stype == "P2TR":
            reason = "P2TR Taproot tweaked public key embedded directly in scriptPubKey (exposed even if never spent)"
        elif reused_onchain:
            reason = f"Reused {stype} address (prior spend already revealed public key / script on-chain)"

        entry = {
            "address": addr,
            "script_type": stype,
            "sats": sats,
            "reason": reason,
        }
        if reason:
            exposed.append(entry)
        else:
            protected.append(entry)
            if multi_utxo_same_addr:
                warnings.append(
                    f"Address {addr} holds {addr_counts[addr]} UTXOs: spending one without sweeping all will expose its pubkey for the remaining UTXOs."
                )

    exposed_sats = sum(x["sats"] for x in exposed)
    protected_sats = sum(x["sats"] for x in protected)
    total_sats = exposed_sats + protected_sats

    est_vbytes = 0.0
    if exposed:
        est_vbytes = TX_OVERHEAD_VBYTES + sum(INPUT_VBYTES.get(x["script_type"], 100.0) for x in exposed) + OUTPUT_VBYTES_P2WSH
    est_fee_sats = int(round(est_vbytes * fee_rate))

    return {
        "summary": {
            "total_utxos": len(utxos),
            "exposed_utxos": len(exposed),
            "protected_utxos": len(protected),
            "exposed_sats": exposed_sats,
            "protected_sats": protected_sats,
            "exposed_pct_btc": round((exposed_sats / total_sats * 100.0), 2) if total_sats > 0 else 0.0,
            "migration_est_vbytes_to_p2wsh": round(est_vbytes, 1),
            "migration_est_fee_sats": est_fee_sats,
            "fee_rate_sat_vb": fee_rate,
        },
        "exposed": exposed,
        "protected": protected,
        "warnings": sorted(set(warnings)),
    }


def main():
    p = argparse.ArgumentParser(description="Offline Bitcoin Post-Quantum UTXO Exposure Auditor")
    p.add_argument("input_file", type=Path, help="listunspent JSON, Sparrow CSV, or newline address list")
    p.add_argument("--format", choices=["auto", "core", "sparrow", "addresses"], default="auto")
    p.add_argument("--esplora", default=None, help="Optional Esplora API base URL (prefer your own local node!) to check prior address reuse")
    p.add_argument("--fee-rate", type=float, default=5.0, help="Fee rate in sat/vB for migration cost estimate (default: 5)")
    p.add_argument("--json", action="store_true", help="Output raw JSON report")
    args = p.parse_args()

    utxos = load_utxos(args.input_file, args.format)
    report = audit(utxos, esplora_url=args.esplora, fee_rate=args.fee_rate)

    if args.json:
        print(json.dumps(report, indent=2))
        return

    s = report["summary"]
    print("=== Bitcoin Post-Quantum Exposure Audit ===")
    print(f"UTXOs scanned:     {s['total_utxos']}")
    print(f"EXPOSED at rest:   {s['exposed_utxos']} UTXOs | {s['exposed_sats']:,} sats ({s['exposed_sats']/1e8:.8f} BTC, {s['exposed_pct_btc']}%)")
    print(f"HASH-PROTECTED:    {s['protected_utxos']} UTXOs | {s['protected_sats']:,} sats ({s['protected_sats']/1e8:.8f} BTC)")
    if report["exposed"]:
        print(f"\nEstimated migration of EXPOSED UTXOs -> fresh P2WSH/P2WPKH:")
        print(f"  Size: ~{s['migration_est_vbytes_to_p2wsh']} vB | Fee @ {s['fee_rate_sat_vb']} sat/vB: ~{s['migration_est_fee_sats']:,} sats")
        print("\nExposed UTXOs:")
        for e in report["exposed"]:
            print(f"  [CRITICAL] {e['script_type']:6s} | {e['sats']:12,d} sats | {e['address']} -> {e['reason']}")
    else:
        print("\nNo exposed-pubkey UTXOs detected. Do NOT unnecessarily churn fresh hash-protected UTXOs.")

    if report["warnings"]:
        print("\nWarnings (Spend-All Discipline Required):")
        for w in report["warnings"]:
            print(f"  [WARN] {w}")


if __name__ == "__main__":
    main()


Need custom Bitcoin / Lightning / security engineering?

Built by MerkleCraft. Available for custom descriptor/multisig migration scripts, Lightning/Nostr tooling, automation, and code/security reviews — paid directly in sats over Lightning.

  • Lightning Address / Zaps: npub1cmp0uhaqf2tm0pt3vydnl6dcnp5tk0hxeqpqqwcq8uzp5k50v09sumg690@npub.cash
  • Bitcoin On-Chain: bc1qwtl5huf6uageetdsyvgmzatt5343z7zsv0rw95
  • Nostr DM: npub1cmp0uhaqf2tm0pt3vydnl6dcnp5tk0hxeqpqqwcq8uzp5k50v09sumg690

Write a comment