SPB Git

Repository Public

utxo.py 17.3 KB 412 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project          : QYVORA7# File             : security/tests/oracles/mc/utxo.py8# Module           : Tests9# Repository       : https://git.spboucher.ai/qyvora10# Project Website  : Not specified11# Created          : 2026-12-0512# Last Modified    : 2026-12-0513#14# Author           : Simon-Pierre Boucher15# Position         : Professor of Finance16# Institution      : Université du Québec en Outaouais (UQO)17# Organization     : SP Boucher18# Website          : https://spboucher.ai19# Git              : https://git.spboucher.ai20#21# Preferred Contact: contact@spboucher.ai22# Development      : dev@spboucher.ai23# Support          : support@spboucher.ai24# Security/Admin   : admin@spboucher.ai25#26# Copyright (c) 202627# Simon-Pierre Boucher28# All rights reserved where applicable. This file is governed by the29# applicable project license, copyright notices and relevant law.30# Existing third-party rights and notices remain unaffected.31#32# License          : None specified (no license file in this repository)33#34# Do not embed credentials, private keys, access tokens,35# certificates or confidential personal information.36#37# =============================================================================38# END OF SP BOUCHER SOURCE HEADER39# =============================================================================4041"""Reference answers for the Litecoin, Dogecoin and Bitcoin Cash differential tests of the QYVORA audit.4243Protocol (see README.md): `python3 -I utxo.py <operation>` reads a JSON array of cases on standard input and writes a44JSON array of the same length; a case the reference rejects answers {"error": "..."}.4546References: bitcash (CashAddr polynomial and bit conversion, Bitcoin Cash P2PKH transactions), bip-utils (BIP-44 /47BIP-84 derivations, address encoders, coin parameters), embit (transaction parsing, original and BIP-143 signature48hashes), coincurve (libsecp256k1: RFC 6979 ECDSA), base58. Test environment only.49"""50import hashlib51import io52import json53import sys54from importlib import metadata5556import base5857import coincurve58from bip_utils import Bip44, Bip44Changes, Bip44Coins, Bip84, Bip84Coins, CoinsConf, WifEncoder59from bip_utils.bech32 import SegwitBech32Encoder60from bitcash import cashaddress61from bitcash.cashaddress import Address as BitcashAddress62from bitcash.transaction import create_p2pkh_transaction63from bitcash.network.meta import Unspent64from bitcash.types import CashTokens, PreparedOutput65from bitcash.wallet import PrivateKey as BitcashKey66from embit.script import Script67from embit.transaction import Transaction6869CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"70HASH_SIZES = [20, 24, 28, 32, 40, 48, 56, 64]717273def dsha(b):74    return hashlib.sha256(hashlib.sha256(b).digest()).digest()757677def op_versions(_):78    names = ["bitcash", "bip-utils", "embit", "coincurve", "base58", "ecdsa"]79    out = {}80    for n in names:81        try:82            out[n] = metadata.version(n)83        except metadata.PackageNotFoundError:84            pass85    return out868788# ---------------------------------------------------------------- CashAddr8990def cashaddr_encode(prefix, kind, payload):91    if len(payload) not in HASH_SIZES or not (0 <= kind <= 15):92        raise ValueError("size or type")93    version = (kind << 3) | HASH_SIZES.index(len(payload))94    words = cashaddress.convertbits([version] + list(payload), 8, 5)95    check = cashaddress.calculate_checksum(prefix, words)96    return prefix + ":" + cashaddress.b32encode(words + check)979899def op_cashaddr_encode(c):100    payload = bytes.fromhex(c["hash"])101    out = {"address": cashaddr_encode(c["prefix"], c["type"], payload)}102    # the named versions of bitcash's Address class, where one fits103    version = (c["type"] << 3) | HASH_SIZES.index(len(payload))104    suffix = BitcashAddress.VERSION_SUFFIXES.get(c["prefix"])105    name = BitcashAddress.ADDRESS_TYPES.get(version)106    if suffix is not None and name is not None:107        out["named"] = BitcashAddress(name + suffix, list(payload)).cash_address()108    return out109110111def op_cashaddr_raw(c):112    """A string with a valid checksum over arbitrary 5-bit words (non-zero padding, wrong lengths, reserved bit…)."""113    words = list(c["words"])114    return {"address": c["prefix"] + ":" + cashaddress.b32encode(words + cashaddress.calculate_checksum(c["prefix"], words))}115116117def cashaddr_strict_decode(text, default_prefix):118    """The decoding rules of the specification, with bitcash's polynomial and bit conversion."""119    if not text.isascii():120        raise ValueError("not ASCII")121    if text.upper() != text and text.lower() != text:122        raise ValueError("mixed case")123    text = text.lower()124    parts = text.split(":")125    if len(parts) == 2:126        prefix, body = parts127    elif len(parts) == 1 and default_prefix:128        prefix, body = default_prefix, parts[0]129    else:130        raise ValueError("prefix")131    if not prefix or not all("a" <= ch <= "z" for ch in prefix):132        raise ValueError("prefix characters")133    if any(ch not in CHARSET for ch in body) or len(body) < 8:134        raise ValueError("payload characters")135    words = [CHARSET.index(ch) for ch in body]136    if not cashaddress.verify_checksum(prefix, words):137        raise ValueError("checksum")138    data = cashaddress.convertbits(words[:-8], 5, 8, pad=False)139    if data is None or not data:140        raise ValueError("padding")141    version = data[0]142    if version & 0x80:143        raise ValueError("reserved bit")144    if len(data) - 1 != HASH_SIZES[version & 7]:145        raise ValueError("length")146    return prefix, version >> 3, bytes(data[1:])147148149def op_cashaddr_decode(c):150    out = {}151    try:152        prefix, kind, payload = cashaddr_strict_decode(c["text"], c.get("default_prefix"))153        out.update({"valid": True, "prefix": prefix, "type": kind, "hash": payload.hex()})154    except Exception as e:  # noqa: BLE001155        out.update({"valid": False, "reason": str(e)})156    # bitcash's own parser (three prefixes, six versions, lenient about padding): reported, compared where it applies157    text = c["text"]158    if ":" not in text and c.get("default_prefix"):159        text = (c["default_prefix"].upper() if text.isupper() else c["default_prefix"]) + ":" + text160    try:161        a = BitcashAddress.from_string(text)162        out["bitcash"] = {"version": a.version, "hash": bytes(a.payload).hex(), "prefix": a.prefix}163    except Exception as e:  # noqa: BLE001164        out["bitcash"] = None165        out["bitcash_reason"] = type(e).__name__166    return out167168169# ---------------------------------------------------------------- addresses and derivations170171NETWORKS = {172    "litecoin": (CoinsConf.LitecoinMainNet, "p2pkh_std_net_ver", "p2sh_std_net_ver", "p2sh_depr_net_ver"),173    "litecoinTestnet": (CoinsConf.LitecoinTestNet, "p2pkh_std_net_ver", "p2sh_std_net_ver", "p2sh_depr_net_ver"),174    "dogecoin": (CoinsConf.DogecoinMainNet, "p2pkh_net_ver", "p2sh_net_ver", None),175    "dogecoinTestnet": (CoinsConf.DogecoinTestNet, "p2pkh_net_ver", "p2sh_net_ver", None),176    "bitcoinCash": (CoinsConf.BitcoinCashMainNet, "p2pkh_legacy_net_ver", "p2sh_legacy_net_ver", None),177    "bitcoinCashTestnet": (CoinsConf.BitcoinCashTestNet, "p2pkh_legacy_net_ver", "p2sh_legacy_net_ver", None),178}179180181def op_parameters(c):182    conf, pkh, sh, depr = NETWORKS[c["network"]]183    out = {"p2pkh": conf.ParamByKey(pkh)[0], "p2sh": conf.ParamByKey(sh)[0], "wif": conf.ParamByKey("wif_net_ver")[0]}184    if depr:185        out["p2sh_deprecated"] = conf.ParamByKey(depr)[0]186    try:187        out["hrp"] = conf.ParamByKey("p2wpkh_hrp")188    except Exception:  # noqa: BLE001189        pass190    try:191        out["cashaddr_prefix"] = conf.ParamByKey("p2pkh_std_hrp")192    except Exception:  # noqa: BLE001193        pass194    return out195196197def op_address(c):198    """{network, kind: p2pkh | p2sh | p2sh_deprecated | witness, hash, version?} → {address} (Base58Check, Bech32/Bech32m199    or, on Bitcoin Cash with form 'cashaddr', CashAddr)."""200    conf, pkh, sh, depr = NETWORKS[c["network"]]201    payload = bytes.fromhex(c["hash"])202    kind = c["kind"]203    if kind == "witness":204        return {"address": SegwitBech32Encoder.Encode(conf.ParamByKey("p2wpkh_hrp"), c["version"], payload)}205    if c.get("form") == "cashaddr":206        return {"address": cashaddr_encode(conf.ParamByKey("p2pkh_std_hrp"), 0 if kind == "p2pkh" else 1, payload)}207    key = {"p2pkh": pkh, "p2sh": sh, "p2sh_deprecated": depr}[kind]208    return {"address": base58.b58encode_check(conf.ParamByKey(key) + payload).decode()}209210211def op_base58check_decode(c):212    raw = base58.b58decode_check(c["text"])213    return {"version": raw[0], "payload": raw[1:].hex()}214215216BIP44 = {217    "litecoin": Bip44Coins.LITECOIN, "litecoinTestnet": Bip44Coins.LITECOIN_TESTNET,218    "dogecoin": Bip44Coins.DOGECOIN, "dogecoinTestnet": Bip44Coins.DOGECOIN_TESTNET,219    "bitcoinCash": Bip44Coins.BITCOIN_CASH, "bitcoinCashTestnet": Bip44Coins.BITCOIN_CASH_TESTNET,220}221BIP84 = {"litecoin": Bip84Coins.LITECOIN, "litecoinTestnet": Bip84Coins.LITECOIN_TESTNET}222223224def op_derive(c):225    """{seed, network, purpose: 44 | 84, change: 0 | 1, index} → address, keys and the account path bip-utils used."""226    seed = bytes.fromhex(c["seed"])227    if c["purpose"] == 84:228        account = Bip84.FromSeed(seed, BIP84[c["network"]]).Purpose().Coin().Account(c.get("account", 0))229    else:230        account = Bip44.FromSeed(seed, BIP44[c["network"]]).Purpose().Coin().Account(c.get("account", 0))231    change = Bip44Changes.CHAIN_EXT if c["change"] == 0 else Bip44Changes.CHAIN_INT232    key = account.Change(change).AddressIndex(c["index"])233    conf = NETWORKS[c["network"]][0]234    private = key.PrivateKey().Raw().ToBytes()235    obj = account.Bip32Object()236    # the coin type is bip-utils' own (its coin configuration), not a value given by the test237    coin_index = account.CoinConf().CoinIndex()238    path = "m/%d'/%d'/%d'" % (c["purpose"], coin_index, c.get("account", 0))239    return {240        "address": key.PublicKey().ToAddress(),241        "public_key": key.PublicKey().RawCompressed().ToHex(),242        "private_key": private.hex(),243        "wif": WifEncoder.Encode(private, conf.ParamByKey("wif_net_ver")),244        "account_public_key": account.PublicKey().RawCompressed().ToHex(),245        "account_chain_code": obj.ChainCode().ToHex(),246        "account_path": path,247        "coin_type": coin_index,248    }249250251# ---------------------------------------------------------------- signature hashes252253def op_legacy_sighash(c):254    tx = Transaction.parse(bytes.fromhex(c["tx"]))255    return {"digest": tx.sighash_legacy(c["index"], Script(bytes.fromhex(c["script"])), c["type"]).hex()}256257258def legacy_digest(raw, index, script, hash_type):259    """The original signature hash written from Bitcoin Core's SignatureHash (script/interpreter.cpp, pre-SegWit260    serializer), with embit used only to parse the transaction. Blank outputs of SIGHASH_SINGLE are CTxOut() after261    SetNull: value -1 (eight ff bytes) and an empty script. No OP_CODESEPARATOR handling (the tests use none)."""262    tx = Transaction.parse(raw)263    base, anyone = hash_type & 0x1f, bool(hash_type & 0x80)264    if base == 3 and index >= len(tx.vout):265        return (1).to_bytes(32, "little")266    out = tx.version.to_bytes(4, "little")267    inputs = [index] if anyone else range(len(tx.vin))268    out += varint(len(inputs))269    for n in inputs:270        i = tx.vin[n]271        code = script if n == index else b""272        sequence = i.sequence if (n == index or base not in (2, 3)) else 0273        out += bytes(reversed(i.txid)) + i.vout.to_bytes(4, "little") + varint(len(code)) + code + sequence.to_bytes(4, "little")274    if base == 2:275        out += varint(0)276    elif base == 3:277        out += varint(index + 1)278        out += (b"\xff" * 8 + b"\x00") * index279        out += tx.vout[index].serialize()280    else:281        out += varint(len(tx.vout)) + b"".join(o.serialize() for o in tx.vout)282    out += tx.locktime.to_bytes(4, "little") + hash_type.to_bytes(4, "little")283    return dsha(out)284285286def op_legacy_sighash_both(c):287    """embit's digest and the one written above from Bitcoin Core: they differ for SIGHASH_SINGLE on an input other288    than the first (embit 0.8.0 serializes the blank outputs with value 0xffffffff instead of -1)."""289    raw, script = bytes.fromhex(c["tx"]), bytes.fromhex(c["script"])290    out = {"core": legacy_digest(raw, c["index"], script, c["type"]).hex()}291    try:292        out["embit"] = Transaction.parse(raw).sighash_legacy(c["index"], Script(script), c["type"]).hex()293    except Exception as e:  # noqa: BLE001294        out["embit_error"] = str(e)295    return out296297298def op_segwit_sighash(c):299    tx = Transaction.parse(bytes.fromhex(c["tx"]))300    return {"digest": tx.sighash_segwit(c["index"], Script(bytes.fromhex(c["script"])), c["value"], c["type"]).hex()}301302303def varint(n):304    if n < 0xfd:305        return bytes([n])306    if n <= 0xffff:307        return b"\xfd" + n.to_bytes(2, "little")308    if n <= 0xffffffff:309        return b"\xfe" + n.to_bytes(4, "little")310    return b"\xff" + n.to_bytes(8, "little")311312313def forkid_digest(raw, index, script, value, hash_type):314    """Bitcoin Cash "replay protected sighash" (UAHF specification, 2017), written here from the specification text315    with embit's parser: BIP-143 preimage, hash type with SIGHASH_FORKID, fork id 0."""316    tx = Transaction.parse(raw)317    base, anyone = hash_type & 0x1f, bool(hash_type & 0x80)318    zero = bytes(32)319    prevouts = zero if anyone else dsha(b"".join(bytes(reversed(i.txid)) + i.vout.to_bytes(4, "little") for i in tx.vin))320    sequences = zero if (anyone or base in (2, 3)) else dsha(b"".join(i.sequence.to_bytes(4, "little") for i in tx.vin))321    if base not in (2, 3):322        outputs = dsha(b"".join(o.serialize() for o in tx.vout))323    elif base == 3 and index < len(tx.vout):324        outputs = dsha(tx.vout[index].serialize())325    else:326        outputs = zero327    i = tx.vin[index]328    preimage = (tx.version.to_bytes(4, "little") + prevouts + sequences + bytes(reversed(i.txid)) + i.vout.to_bytes(4, "little")329                + varint(len(script)) + script + value.to_bytes(8, "little") + i.sequence.to_bytes(4, "little") + outputs330                + tx.locktime.to_bytes(4, "little") + hash_type.to_bytes(4, "little"))331    return dsha(preimage)332333334def op_forkid_sighash(c):335    return {"digest": forkid_digest(bytes.fromhex(c["tx"]), c["index"], bytes.fromhex(c["script"]), c["value"], c["type"]).hex()}336337338# ---------------------------------------------------------------- signatures and signed transactions339340def sign_der(key, digest):341    return coincurve.PrivateKey(key).sign(digest, hasher=None)342343344def op_sign(c):345    key = bytes.fromhex(c["key"])346    sig = sign_der(key, bytes.fromhex(c["digest"]))347    return {"der": sig.hex(), "public_key": coincurve.PrivateKey(key).public_key.format(compressed=True).hex()}348349350def op_verify(c):351    pub = coincurve.PublicKey(bytes.fromhex(c["public_key"]))352    return {"valid": bool(pub.verify(bytes.fromhex(c["der"]), bytes.fromhex(c["digest"]), hasher=None))}353354355def push(data):356    assert len(data) < 0x4c357    return bytes([len(data)]) + data358359360def op_legacy_signed_tx(c):361    """Signs every input of an unsigned transaction as P2PKH with one key: embit's original digest (or the fork-id362    digest above when "forkid" is set), libsecp256k1's RFC 6979 signature. {tx, key, scripts: [hex], values?: [int],363    forkid?: bool, compressed?: bool} → {raw}."""364    raw = bytes.fromhex(c["tx"])365    key = bytes.fromhex(c["key"])366    public = coincurve.PrivateKey(key).public_key.format(compressed=c.get("compressed", True))367    tx = Transaction.parse(raw)368    signed = Transaction.parse(raw)369    for n, script_hex in enumerate(c["scripts"]):370        script = bytes.fromhex(script_hex)371        if c.get("forkid"):372            digest, byte = forkid_digest(raw, n, script, c["values"][n], 0x41), b"\x41"373        else:374            digest, byte = tx.sighash_legacy(n, Script(script), 1), b"\x01"375        signed.vin[n].script_sig = Script(push(sign_der(key, digest) + byte) + push(public))376    return {"raw": signed.serialize().hex(), "txid": signed.txid().hex()}377378379def op_bitcash_tx(c):380    """bitcash builds and signs a P2PKH transaction (version 1, sequence 0xffffffff, lock time 0, SIGHASH_ALL|FORKID).381    {key, inputs: [{txid, vout, amount, script}], outputs: [{script, amount}]} → {raw}."""382    key = BitcashKey.from_hex(c["key"])383    unspents = [Unspent(i["amount"], 6, i["script"], i["txid"], i["vout"]) for i in c["inputs"]]384    outputs = [PreparedOutput(bytes.fromhex(o["script"]), o["amount"], CashTokens(None, None, None, None)) for o in c["outputs"]]385    return {"raw": create_p2pkh_transaction(key, unspents, outputs), "public_key": key.public_key.hex()}386387388def op_parse_tx(c):389    raw = bytes.fromhex(c["tx"])390    tx = Transaction.parse(raw)391    return {"txid": tx.txid().hex(), "inputs": len(tx.vin), "outputs": len(tx.vout), "reserialized": tx.serialize().hex(),392            "segwit": tx.is_segwit}393394395OPS = {name[3:]: fn for name, fn in list(globals().items()) if name.startswith("op_")}396397398def main():399    op = sys.argv[1]400    cases = json.load(sys.stdin)401    out = []402    for c in cases:403        try:404            out.append(OPS[op](c))405        except Exception as e:  # noqa: BLE001 - a case the reference rejects406            out.append({"error": "%s: %s" % (type(e).__name__, e)})407    json.dump(out, sys.stdout)408409410if __name__ == "__main__":411    main()412
Files main
Menu

Theme