SPB Git

Repository Public

fetch_transactions.py 5.8 KB 148 lines python

1#!/usr/bin/env python32# =============================================================================3#                  SP BOUCHER | SOFTWARE & RESEARCH4#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5# =============================================================================6#7# Project          : QYVORA8# File             : security/vectors/utxo-mainnet/fetch_transactions.py9# Module           : Security10# Repository       : https://git.spboucher.ai/qyvora11# Project Website  : Not specified12# Created          : 2026-12-0513# Last Modified    : 2026-12-0514#15# Author           : Simon-Pierre Boucher16# Position         : Professor of Finance17# Institution      : Université du Québec en Outaouais (UQO)18# Organization     : SP Boucher19# Website          : https://spboucher.ai20# Git              : https://git.spboucher.ai21#22# Preferred Contact: contact@spboucher.ai23# Development      : dev@spboucher.ai24# Support          : support@spboucher.ai25# Security/Admin   : admin@spboucher.ai26#27# Copyright (c) 202628# Simon-Pierre Boucher29# All rights reserved where applicable. This file is governed by the30# applicable project license, copyright notices and relevant law.31# Existing third-party rights and notices remain unaffected.32#33# License          : None specified (no license file in this repository)34#35# Do not embed credentials, private keys, access tokens,36# certificates or confidential personal information.37#38# =============================================================================39# END OF SP BOUCHER SOURCE HEADER40# =============================================================================4142"""Fetches public main-network transactions of Litecoin, Dogecoin and Bitcoin Cash, each with the transactions its43inputs spend, from keyless public Blockbook indexers (read-only requests; nothing is uploaded).4445Usage: python3 -I fetch_transactions.py [coin ...] > transactions.json   (coins: litecoin dogecoin bitcoinCash)4647Only transactions whose inputs all spend P2PKH outputs (and P2WPKH on Litecoin) are kept: the input types the wallet48signs. The audit does not trust the indexer: the conformance test recomputes every identifier from the bytes, so a49source that altered a transaction would make the test fail, not pass.50"""51import json52import sys53import time54import urllib.request555657def get(url):58    last = None59    for attempt in range(5):60        try:61            time.sleep(0.6)  # public instances answer HTTP 429 to bursts62            req = urllib.request.Request(url, headers={"User-Agent": "vector-fetch/1.0"})63            with urllib.request.urlopen(req, timeout=30) as r:64                return r.read()65        except Exception as e:  # noqa: BLE001 - retried, then reported66            last = e67            time.sleep(4 * (attempt + 1))68    raise last697071def kind_of(script):72    if len(script) == 50 and script.startswith("76a914") and script.endswith("88ac"):73        return "p2pkh"74    if len(script) == 44 and script.startswith("0014"):75        return "p2wpkh"76    return "other"777879def blockbook(base, want, kinds, per_kind):80    status = json.loads(get(base + "/"))81    tip = status["blockbook"]["bestHeight"]82    out, counts, h = [], {k: 0 for k in kinds}, tip - 383    while len(out) < want and h > tip - 60:84        page = 185        while len(out) < want:86            blk = json.loads(get(f"{base}/block/{h}?page={page}"))87            for t in blk.get("txs", []):88                vin = t.get("vin", [])89                # the block listing omits the outpoints: a coinbase input is the one without address90                if not vin or len(vin) > 3 or any(not i.get("isAddress") for i in vin):91                    continue92                full = json.loads(get(f"{base}/tx/{t['txid']}"))93                raw = full.get("hex")94                if not raw or len(raw) > 4000 or any("txid" not in i for i in full.get("vin", [])):95                    continue96                prevs, found, ok = {}, set(), True97                for i in full["vin"]:98                    p = json.loads(get(f"{base}/tx/{i['txid']}"))99                    ph = p.get("hex")100                    if not ph or len(ph) > 40000:101                        ok = False102                        break103                    k = kind_of(p["vout"][i.get("vout", 0)]["hex"])104                    if k not in kinds:105                        ok = False106                        break107                    found.add(k)108                    prevs[i["txid"]] = ph109                if not ok or len(found) != 1:110                    continue111                k = next(iter(found))112                if counts[k] >= per_kind:113                    continue114                counts[k] += 1115                out.append({"txid": t["txid"], "height": h, "inputKind": k, "raw": raw, "previous": prevs})116                if len(out) >= want:117                    break118            if page >= blk.get("totalPages", 1):119                break120            page += 1121        h -= 1122    return out123124125SOURCES = {126    "litecoin": ("https://litecoin.atomicwallet.io/api/v2", 12, {"p2pkh", "p2wpkh"}, 6),127    "dogecoin": ("https://blockbook.doge.zelcore.io/api/v2", 8, {"p2pkh"}, 8),128    "bitcoinCash": ("https://blockbook.bch.zelcore.io/api/v2", 8, {"p2pkh"}, 8),129}130131132def main():133    doc = {"fetched": time.strftime("%Y-%m-%d", time.gmtime()), "coins": {}}134    for coin, (base, want, kinds, per_kind) in SOURCES.items():135        if len(sys.argv) > 1 and coin not in sys.argv[1:]:136            continue137        try:138            doc["coins"][coin] = {"source": base, "transactions": blockbook(base, want, kinds, per_kind)}139        except Exception as e:  # noqa: BLE001140            doc["coins"][coin] = {"source": base, "error": str(e), "transactions": []}141        print(coin, len(doc["coins"][coin]["transactions"]), doc["coins"][coin].get("error", ""), file=sys.stderr)142    json.dump(doc, sys.stdout, indent=1)143    sys.stdout.write("\n")144145146if __name__ == "__main__":147    main()148
Files main
Menu

Theme