SPB Git

Repository Public

Targets+UTXOCoins.swift 63.9 KB 848 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : security/tests/Sources/FuzzTargets/Targets+UTXOCoins.swift8// Module           : Tests9// Repository       : https://git.spboucher.ai/qyvora10// Project Website  : Not specified11// Created          : 2026-12-0412// 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// =============================================================================4041import AuditSupport42import Foundation43import QyvoraMath44import QyvoraSecp256k145import QyvoraStorage46import QyvoraSymmetric47import QyvoraVault48@testable import QyvoraBitcoin49@testable import QyvoraCore50@testable import QyvoraNetworking51@testable import QyvoraWallet5253// Litecoin, Dogecoin and Bitcoin Cash: every parser of untrusted input added with these coins.54//   cashaddr                  CashAddr text: decode, canonical re-encoding, checksum, the address layer above it55//   utxo-coin-address         address text per network (letter selector): address ⇄ script, no cross-coin acceptance56//   utxo-legacy-transaction   transactions without witness (Dogecoin, Bitcoin Cash): decode, re-encode, digests57//   psbt-prevtx               PSBTs carrying previous transactions: the fee reported is authenticated, or absent58//   json-blockbook            every answer the Blockbook client reads (letter selector)59//   json-bitcore              every answer the Bitcore client reads (letter selector)60//   utxo-indexer-normalise    the wallet service synchronising a coin against hostile indexer answers, then paying61//   utxo-coin-sign            build + sign on the six networks from fuzzed coins, amounts and rates6263/// QY_UTXO_TRACE=1 with `qyfuzz repro` prints the path an input takes through the service harness (seed quality check).64private let traceEnabled = ProcessInfo.processInfo.environment["QY_UTXO_TRACE"] != nil65private func note(_ label: String) {66    FuzzOutcome.note(label)67    if traceEnabled { print("trace: " + label) }68}6970private let coinNetworks: [BitcoinNetwork] = [.litecoin, .litecoinTestnet, .dogecoin, .dogecoinTestnet, .bitcoinCash, .bitcoinCashTestnet]7172/// Public main-network transactions (security/vectors/utxo-mainnet): one of Dogecoin, one of Bitcoin Cash.73private let dogecoinTransactionHex = "010000000153fa6a0db7feefdd00d6c098b63ec84f4af3af5a1aea171a8858abb0c27c42e7000000006a47304402202f9d15ec6ac1c724ac46fcb968118cf007443c0a972f46e82e78dd56cc143529022063228fbae381fc582873fedec3d7eaa5a29b8b0eb22a865e6efb66eb00f2250c012103192d80c8ba63d24a1c1d99742afe5c954a8dcf96e0356627626d76273e83f635feffffff024033225b000000001976a914b1dd193bf5040d7184423c3e683bf228a127333488ac80841e00000000001976a914830a7420e63d76244ff7cbd1c248e94c1446325988ac4dd76200"7475private func mainnetVectorTransactions() -> [Bytes] {76    var out = [Bytes]()77    let url = AuditPaths.vectors.appendingPathComponent("utxo-mainnet/transactions.json")78    if let root = (try? AuditVectors.json(url)) as? [String: Any], let coins = root["coins"] as? [String: Any] {79        for name in ["dogecoin", "bitcoinCash"] {80            let list = (coins[name] as? [String: Any])?["transactions"] as? [[String: Any]] ?? []81            for t in list.prefix(3) { if let raw = Hex.decode(t["raw"] as? String ?? "") { out.append(raw) } }82        }83    }84    if let fallback = Hex.decode(dogecoinTransactionHex) { out.append(fallback) }85    return out86}8788// MARK: - Accounts and coins of the harnesses8990private enum CoinFixtures {91    static let master: ExtendedKey? = try? ExtendedKey.master(seed: fixtureBytes("utxo-coin-master", 32))92    /// One account per (network, purpose), derived once per process.93    static let accounts: [String: UTXOAccount] = {94        var out = [String: UTXOAccount]()95        guard let master else { return out }96        for n in coinNetworks {97            for p in UTXOAccountPurpose.allCases where n.supports(p) { out["\(n.rawValue)|\(p.rawValue)"] = try? UTXOAccount(master: master, network: n, purpose: p) }98        }99        return out100    }()101102    static func account(_ network: BitcoinNetwork, _ purpose: UTXOAccountPurpose? = nil) -> UTXOAccount? { accounts["\(network.rawValue)|\((purpose ?? network.defaultPurpose).rawValue)"] }103104    /// A coin of `account` and the transaction that creates it.105    static func coin(_ account: UTXOAccount, chain: UInt8, index: UInt8, value: UInt64, salt: Bytes, filler: Int) -> (utxo: BitcoinUTXO, previous: BitcoinTransaction)? {106        guard let c = UTXOAccount.Chain(rawValue: UInt32(chain & 1)), let script = try? account.scriptPubKey(chain: c, index: UInt32(index & 7)),107              let source = BitcoinOutPoint(hash: SHA256.hash(salt), index: 0) else { return nil }108        let fill = (0..<(filler % 3)).map { BitcoinTransaction.Output(value: UInt64($0), scriptPubKey: [0x6a, 0x01, UInt8($0)]) }109        let previous = BitcoinTransaction(version: 1, inputs: [.init(previousOutput: source, scriptSig: [0x51])], outputs: fill + [.init(value: value, scriptPubKey: script)])110        guard let outPoint = BitcoinOutPoint(hash: previous.txidBytes, index: UInt32(fill.count)) else { return nil }111        return (BitcoinUTXO(outPoint: outPoint, value: value, scriptPubKey: script, confirmations: 3, derivation: .init(chain: c.rawValue, index: UInt32(index & 7))), previous)112    }113}114115// MARK: - Seeds116117private func cashAddrSeeds() -> [Bytes] {118    var texts = [119        "bitcoincash:qpm2qsznhks23z7629mms6s4cwef74vcwvy22gdx6a", "bitcoincash:ppm2qsznhks23z7629mms6s4cwef74vcwvn0h829pq",120        "BITCOINCASH:QR95SY3J9XWD2AP32XKYKTTR4CVCU7AS4Y0QVERFUY", "qqq3728yw0y47sqn6l2na30mcw6zm78dzqre909m2r",121        "bchtest:pr6m7j9njldwwzlg9v7v53unlr4jkmx6eyvwc0uz5t", "prefix:0r6m7j9njldwwzlg9v7v53unlr4jkmx6ey3qnjwsrf",122        "bitcoincash:qvch8mmxy0rtfrlarg7ucrxxfzds5pamg73h7370aa87d80gyhqxq5nlegake", "prefix:x64nx6hz", "bchreg:555555555555555555555555555555555555555555555udxmlmrz",123        "1BpEi6DfDAUFd7GtittLSdBeYJvcoaVggu", "bitcoincash:", ":", "bitcoincash:qpm2qsznhks23z7629mms6s4cwef74vcwvy22gdx6b",124    ]125    for size in [20, 24, 28, 32, 40, 48, 56, 64] {126        if let t = CashAddr.encode(prefix: "bitcoincash", type: UInt8(size % 4), hash: fixtureBytes("cashaddr-\(size)", size)) { texts.append(t) }127    }128    return texts.map { Bytes($0.utf8) }129}130131private func coinAddressSeeds() -> [Bytes] {132    var out = [Bytes]()133    let networks = BitcoinNetwork.allCases134    for (k, n) in networks.enumerated() {135        let hash = fixtureBytes("coin-address-\(n.rawValue)", 32)136        var scripts = [try? BitcoinScript.p2pkh(publicKeyHash: Bytes(hash.prefix(20))), try? BitcoinScript.p2sh(scriptHash: Bytes(hash.prefix(20)))]137        if n.supportsSegWit { scripts += [try? BitcoinScript.p2wpkh(publicKeyHash: Bytes(hash.prefix(20))), try? BitcoinScript.p2wsh(scriptHash: hash), try? BitcoinScript.p2tr(outputKey: hash)] }138        for s in scripts.compactMap({ $0 }) {139            guard let a = try? BitcoinAddress(scriptPubKey: s, network: n) else { continue }140            let selector = [UInt8(0x61 + k)]141            out.append(selector + Bytes(a.string.utf8))142            if let legacy = a.base58String, legacy != a.string { out.append(selector + Bytes(legacy.utf8)) }143            if n.cashAddrPrefix != nil { out.append(selector + Bytes(a.stringWithoutPrefix.utf8)) }144            // the same text under the next network145            out.append([UInt8(0x61 + (k + 1) % networks.count)] + Bytes(a.string.utf8))146        }147    }148    out.append(Bytes("b3CWFddi6m4ndiGyKqzYvsFYagqDLPVMTzC".utf8))149    return out150}151152private func legacyTransactionSeeds() -> [Bytes] {153    var out = mainnetVectorTransactions()154    // no input, one output: also readable as a SegWit marker and flag (found by the first run of this target)155    if let ambiguous = Hex.decode("fe00016d000153f7800db7fe02dd00d6c098b6") { out.append(ambiguous) }156    if let account = CoinFixtures.account(.dogecoin), let c = CoinFixtures.coin(account, chain: 0, index: 1, value: 500_000_000, salt: [1], filler: 1) {157        out.append(c.previous.serialized())158    }159    return out160}161162private func psbtPreviousTransactionSeeds() -> [Bytes] {163    var out = [Bytes]()164    for (n, purpose) in [(BitcoinNetwork.dogecoin, UTXOAccountPurpose.bip44), (.bitcoinCash, .bip44), (.litecoin, .bip44), (.litecoin, .bip84), (.dogecoinTestnet, .bip44)] {165        guard let account = CoinFixtures.account(n, purpose) else { continue }166        var utxos = [BitcoinUTXO](), previous = [String: BitcoinTransaction]()167        for k in 0..<2 {168            guard let c = CoinFixtures.coin(account, chain: UInt8(k), index: UInt8(k + 1), value: 900_000_000 + UInt64(k), salt: [UInt8(k), 7], filler: k) else { continue }169            utxos.append(c.utxo)170            previous[c.utxo.outPoint.txid] = c.previous171        }172        guard let change = try? account.scriptPubKey(chain: .change, index: 5), let to = try? BitcoinScript.p2pkh(publicKeyHash: fixtureBytes("psbt-prevtx-to", 20)) else { continue }173        var request = BitcoinSpendRequest(network: n, recipients: [.init(value: 1_200_000_000, scriptPubKey: to)], utxos: utxos, feeRate: .minimum(for: n), changeScript: change)174        request.seed = 3175        guard let plan = try? BitcoinTransactionBuilder.build(request), var psbt = try? account.psbt(for: plan, previousTransactions: previous) else { continue }176        out.append(psbt.serialized())177        // one input without its previous transaction, one with a witness-UTXO record instead178        var stripped = psbt179        stripped.inputs[0].nonWitnessUTXO = nil180        out.append(stripped.serialized())181        stripped.inputs[0].witnessUTXO = plan.inputs[0].output182        out.append(stripped.serialized())183        if (try? account.sign(psbt: &psbt)) != nil { out.append(psbt.serialized()) }184    }185    return out186}187188private let blockbookSeedTexts: [String] = {189    let txid = sampleTxid190    let tx = #"{"txid":"\#(txid)","version":1,"vin":[{"txid":"\#(String(repeating: "cd", count: 32))","vout":1,"sequence":4294967294,"n":0,"addresses":["D7JeqAsJ9Vie3VnpticCJ2N9s2RJQQjgiG"],"isAddress":true,"value":"1531194000"}],"vout":[{"value":"1528968000","n":0,"hex":"76a914b1dd193bf5040d7184423c3e683bf228a127333488ac","addresses":["DMMZ1Qm3sU6LM2GZCH5UzojRZA8SFjPDBH"],"isAddress":true}],"blockHeight":6477647,"confirmations":7816,"blockTime":1795951329,"size":225,"fees":"226000","hex":"\#(dogecoinTransactionHex)"}"#191    return [192        #"0{"blockbook":{"coin":"Dogecoin","bestHeight":6485462,"lastBlockTime":"2026-12-05T05:11:35.43573209Z"},"backend":{"blocks":6485462}}"#,193        #"1{"blockHash":"1a91e3dace36e2be3bf030a65679fe821aa1d6ef92e7c9902eb318182c355691"}"#,194        #"2{"address":"DH5yaieqoZN36fDVciNyRueRGvGLR3mr7L","balance":"6223538467666","totalReceived":"5581286333513200844","totalSent":"5581280109974733178","unconfirmedBalance":"-12","unconfirmedTxs":1,"txs":1488}"#,195        #"3[{"txid":"\#(txid)","vout":1,"value":"2000000","height":6477647,"confirmations":7816},{"txid":"\#(txid)","value":"95347802","height":6423225,"confirmations":62238,"coinbase":true},{"txid":"\#(txid)","vout":2,"value":"1230000000","confirmations":0}]"#,196        #"4{"page":1,"totalPages":3,"itemsOnPage":25,"address":"DH5yaieqoZN36fDVciNyRueRGvGLR3mr7L","balance":"1","txs":3,"transactions":[\#(tx)]}"#,197        "5" + tx, #"6{"result":"0.01002"}"#, #"7{"result":"\#(txid)"}"#, #"7{"error":"-26: txn-mempool-conflict"}"#, #"7{"error":"-27: transaction already in block chain"}"#,198        #"8{"blockHash":"0000000000000000029e471c41818d24b8b74c911071c4ef0b4a0509f9b5a8ce"}"#,199        #"4{"page":1,"totalPages":1,"transactions":[{"txid":"\#(txid)","vin":[{"n":0,"isAddress":false,"value":"0"}],"vout":[{"value":"312579328","n":0,"addresses":["bitcoincash:qqjyycerhgygpzwxmnfe83nchng8v66qas5yt745rm"],"isAddress":true},{"value":"0","n":1,"addresses":["OP_RETURN aa21a9ed"],"isAddress":false}],"blockHeight":980350,"confirmations":10,"blockTime":1796439551,"fees":"0"}]}"#,200    ]201}()202203private let bitcoreSeedTexts: [String] = {204    let txid = sampleTxid205    func coin(_ index: Int, mintHeight: Int, spentHeight: Int, spent: String = "") -> String {206        #"{"chain":"DOGE","network":"mainnet","coinbase":false,"mintIndex":\#(index),"spentTxid":"\#(spent)","mintTxid":"\#(txid)","mintHeight":\#(mintHeight),"spentHeight":\#(spentHeight),"address":"DH5yaieqoZN36fDVciNyRueRGvGLR3mr7L","script":"76a914830a7420e63d76244ff7cbd1c248e94c1446325988ac","value":2000000,"confirmations":-1,"sequenceNumber":4294967294}"#207    }208    let block = #"{"chain":"DOGE","network":"mainnet","hash":"1a91e3dace36e2be3bf030a65679fe821aa1d6ef92e7c9902eb318182c355691","height":0,"time":"2013-12-06T10:25:40.000Z"}"#209    return [210        #"0{"chain":"DOGE","hash":"7947887e10b1279fb0174d2d3a8719e4c4224aef6f4748df2cfa0a6b0e1153c5","height":6485457,"time":"2026-12-05T05:08:10.000Z"}"#,211        "1" + block,212        "2[" + coin(1, mintHeight: 6_477_647, spentHeight: -2) + "," + coin(0, mintHeight: 6_477_600, spentHeight: 6_477_681, spent: String(repeating: "ef", count: 32)) + "," + coin(2, mintHeight: -1, spentHeight: -1, spent: String(repeating: "12", count: 32)) + "]",213        "3[" + coin(1, mintHeight: 6_477_647, spentHeight: -2) + "," + coin(4, mintHeight: -1, spentHeight: -2) + "]",214        "4[" + coin(1, mintHeight: 6_477_647, spentHeight: -2) + "]",215        // one body that is both a transaction and its coins (the stub answers both requests with it)216        #"5{"txid":"\#(txid)","blockHeight":6477647,"blockTime":"2026-11-29T11:22:09.000Z","coinbase":false,"size":225,"fee":226000,"inputs":["# + coin(0, mintHeight: 6_477_620, spentHeight: 6_477_647, spent: txid) + #"],"outputs":["# + coin(1, mintHeight: 6_477_647, spentHeight: -2) + "," + coin(0, mintHeight: 6_477_647, spentHeight: -2) + "]}",217        #"6{"feerate":0.01002,"blocks":2}"#, #"7{"txid":"\#(txid)"}"#, "7txn-mempool-conflict", "7transaction already in block chain", "8" + block,218    ]219}()220221// MARK: - The wallet service against hostile coin indexers222223/// Answers the three indexer protocols for one wallet: the identity block is always the right one (an endpoint that224/// passed the chain check and then lies is the case under test); the first receive address gets the fuzzed sections.225final class CoinRouter: HTTPTransport, @unchecked Sendable {226    private let lock = NSLock()227    private var sections = [String]()228    private var sent = [String]()229    var firstAddresses = [String: String]()   // network raw value → first receive address as the indexer is asked for it230231    func install(_ s: [String]) { lock.withLock { sections = s; sent = [] } }232    var broadcasts: [String] { lock.withLock { sent } }233    private func section(_ index: Int, _ fallback: String) -> String { lock.withLock { index < sections.count && !sections[index].isEmpty ? sections[index] : fallback } }234235    static let unusedBlockbook = #"{"balance":"0","totalReceived":"0","totalSent":"0","unconfirmedBalance":"0","unconfirmedTxs":0,"txs":0}"#236    static let unusedEsplora = #"{"address":"x","chain_stats":{"funded_txo_count":0,"funded_txo_sum":0,"spent_txo_count":0,"spent_txo_sum":0,"tx_count":0},"mempool_stats":{"funded_txo_count":0,"funded_txo_sum":0,"spent_txo_count":0,"spent_txo_sum":0,"tx_count":0}}"#237238    func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) {239        guard let url = request.url, let host = url.host, let response = HTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: nil) else { throw NetworkError.invalidURL }240        let path = url.path, query = url.query ?? ""241        func isFirst(_ network: BitcoinNetwork) -> Bool { firstAddresses[network.rawValue].map { !$0.isEmpty && path.contains($0) } ?? false }242        var body = ""243        switch host {244        case "bb.test":   // Blockbook, Dogecoin Testnet245            let n = BitcoinNetwork.dogecoinTestnet246            if request.httpMethod == "POST" {247                lock.withLock { sent.append(String(decoding: request.httpBody ?? Data(), as: UTF8.self)) }248                body = section(8, #"{"error":"refused"}"#)249            } else if path.contains("/block-index/") {250                body = #"{"blockHash":"\#(n.identityBlock.hash)"}"#251            } else if path.contains("/utxo/") {252                body = isFirst(n) ? section(3, "[]") : "[]"253            } else if path.contains("/address/") {254                if query.contains("details=txs") { body = isFirst(n) ? section(4, #"{"page":1,"totalPages":1,"transactions":[]}"#) : #"{"page":1,"totalPages":1,"transactions":[]}"# } else {255                    body = isFirst(n) ? section(2, Self.unusedBlockbook) : Self.unusedBlockbook256                }257            } else if path.contains("/estimatefee/") {258                body = section(5, #"{"result":"0.01"}"#)259            } else if path.contains("/tx/") {260                body = section(6, "{}")261            } else {262                body = section(1, #"{"blockbook":{"bestHeight":500}}"#)263            }264        case "bc.test":   // Bitcore, Bitcoin Cash Testnet265            let n = BitcoinNetwork.bitcoinCashTestnet266            if request.httpMethod == "POST" {267                lock.withLock { sent.append(String(decoding: request.httpBody ?? Data(), as: UTF8.self)) }268                body = section(8, "refused")269            } else if path.hasSuffix("/block/tip") {270                body = section(1, #"{"hash":"\#(String(repeating: "aa", count: 32))","height":250000}"#)271            } else if path.contains("/block/") {272                body = #"{"hash":"\#(n.identityBlock.hash)","height":\#(n.identityBlock.height)}"#273            } else if path.contains("/address/") {274                body = isFirst(n) ? (query.contains("unspent=true") ? section(3, "[]") : section(2, "[]")) : "[]"275            } else if path.contains("/fee/") {276                body = section(5, #"{"feerate":0.00001}"#)277            } else if path.hasSuffix("/coins") {278                body = section(6, #"{"inputs":[],"outputs":[]}"#)279            } else {280                body = section(4, "{}")281            }282        case "es.test", "bb2.test":   // Esplora and a second Blockbook, Litecoin Testnet (two clients: the survey of tips)283            let n = BitcoinNetwork.litecoinTestnet284            if host == "bb2.test" {285                if path.contains("/block-index/") { body = #"{"blockHash":"\#(n.identityBlock.hash)"}"# } else if path.contains("/utxo/") { body = "[]" } else if path.contains("/address/") {286                    body = query.contains("details=txs") ? #"{"page":1,"totalPages":1,"transactions":[]}"# : Self.unusedBlockbook287                } else if path.contains("/estimatefee/") { body = #"{"result":"0.0001"}"# } else { body = section(7, #"{"blockbook":{"bestHeight":100}}"#) }288            } else if request.httpMethod == "POST" {289                lock.withLock { sent.append(String(decoding: request.httpBody ?? Data(), as: UTF8.self)) }290                body = section(8, "refused")291            } else if path.contains("/block-height/") {292                body = n.identityBlock.hash293            } else if path.hasSuffix("/blocks/tip/height") {294                body = section(1, "200")295            } else if path.hasSuffix("/fee-estimates") {296                body = section(5, #"{"1":25.3,"6":10.1,"144":1.0}"#)297            } else if path.contains("/address/") {298                if path.hasSuffix("/utxo") { body = isFirst(n) ? section(3, "[]") : "[]" } else if path.contains("/txs") {299                    body = isFirst(n) && !path.contains("/txs/chain/") ? section(4, "[]") : "[]"300                } else { body = isFirst(n) ? section(2, Self.unusedEsplora) : Self.unusedEsplora }301            } else {302                body = section(6, "")303            }304        default:305            throw NetworkError.invalidURL306        }307        return (Data(body.utf8), response)308    }309}310311struct CoinWalletFixture: Sendable {312    let service: WalletService313    let router: CoinRouter314    static let password = "correct horse battery staple 42"315    static let networks: [BitcoinNetwork] = [.dogecoinTestnet, .bitcoinCashTestnet, .litecoinTestnet]316317    static let endpoints = EndpointConfiguration(318        esplora: ["signet": ["https://unused.test/api"], "litecoinTestnet": ["https://es.test/api"]],319        blockbook: ["dogecoinTestnet": ["https://bb.test/api/v2"], "litecoinTestnet": ["https://bb2.test/api/v2"]],320        bitcore: ["bitcoinCashTestnet": ["https://bc.test/api/BCH/testnet"]],321        ethereumRPC: [:], ethereumIndexer: [:], priceAPI: "https://prices.test/api/v3")322323    static let shared: CoinWalletFixture? = {324        let dir = FileManager.default.temporaryDirectory.appendingPathComponent("qyfuzz-coins-\(getpid())")325        try? FileManager.default.removeItem(at: dir)326        guard let store = try? FileStore(root: dir) else { return nil }327        let vault = Vault(fileStore: store, keychain: InMemoryKeychainStore(), configuration: .init(kdf: .insecureForTesting))328        let router = CoinRouter()329        guard let service = try? WalletService(vault: vault, fileStore: store, transport: router, sleep: { _ in }, transactionSeed: 7, backupKDF: .insecureForTesting, historyPagesPerAddress: 2)330        else { return nil }331        nonisolated(unsafe) var ok = false332        fuzzAwait {333            do {334                try await service.setEndpoints(endpoints)335                try await service.importWallet(words: BIP39.words(from: abandon), password: password)336                try await service.setEnabledChains([.bitcoin, .litecoin, .dogecoin, .bitcoinCash])337                ok = true338            } catch {}339        }340        guard ok, let master = try? ExtendedKey.master(seed: try BIP39.seed(mnemonic: BIP39.words(from: abandon))) else { return nil }341        for n in networks {342            if let a = try? UTXOAccount(master: master, network: n).address(chain: .receive, index: 0) { router.firstAddresses[n.rawValue] = a.stringWithoutPrefix }343        }344        return CoinWalletFixture(service: service, router: router)345    }()346347    /// The funding transaction of the seeds: pays the first receive address of `network`.348    static func funding(_ network: BitcoinNetwork, value: UInt64) -> (tx: BitcoinTransaction, script: Bytes, address: String)? {349        guard let master = try? ExtendedKey.master(seed: try BIP39.seed(mnemonic: BIP39.words(from: abandon))), let account = try? UTXOAccount(master: master, network: network),350              let address = try? account.address(chain: .receive, index: 0), let source = BitcoinOutPoint(hash: Bytes(repeating: 0x21, count: 32), index: 0) else { return nil }351        let other = (try? BitcoinScript.p2pkh(publicKeyHash: Bytes(repeating: 0x33, count: 20))) ?? []352        return (BitcoinTransaction(version: 1, inputs: [.init(previousOutput: source, scriptSig: [0x51])], outputs: [.init(value: 777, scriptPubKey: other), .init(value: value, scriptPubKey: address.scriptPubKey)]),353                address.scriptPubKey, address.string)354    }355}356357private func coinSyncSeeds() -> [Bytes] {358    func lines(_ mode: String, _ sections: [Int: String]) -> Bytes {359        let last = sections.keys.max() ?? 0360        return Bytes(([mode] + (1...max(1, last)).map { sections[$0] ?? "" }).joined(separator: "\n").utf8)361    }362    var out = [Bytes]()363    let source = String(repeating: "21", count: 32)364    // a: Dogecoin Testnet through Blockbook365    if let f = CoinWalletFixture.funding(.dogecoinTestnet, value: 50_000_000_000) {366        let txid = f.tx.txid, hex = f.tx.hex, script = Hex.encode(f.script)367        let tx = #"{"txid":"\#(txid)","vin":[{"txid":"\#(source)","sequence":4294967295,"n":0,"addresses":["nd1LEFTcEkzkkRAyBTHKEmpMfTxWxkQZas"],"isAddress":true,"value":"50000001000"}],"vout":[{"value":"777","n":0,"hex":"76a914\#(String(repeating: "33", count: 20))88ac","isAddress":false},{"value":"50000000000","n":1,"hex":"\#(script)","addresses":["\#(f.address)"],"isAddress":true}],"blockHeight":400,"confirmations":101,"blockTime":1795951329,"size":225,"fees":"223","hex":"\#(hex)"}"#368        let stats = #"{"address":"\#(f.address)","balance":"50000000000","totalReceived":"50000000000","totalSent":"0","unconfirmedBalance":"0","unconfirmedTxs":0,"txs":1}"#369        let utxo = #"[{"txid":"\#(txid)","vout":1,"value":"50000000000","height":400,"confirmations":101}]"#370        let history = #"{"page":1,"totalPages":1,"itemsOnPage":25,"transactions":[\#(tx)]}"#371        let status = #"{"blockbook":{"bestHeight":500,"lastBlockTime":"2026-12-05T05:11:35Z"}}"#372        out.append(lines("a", [1: status, 2: stats, 3: utxo, 4: history, 5: #"{"result":"0.01"}"#, 6: tx, 8: #"{"result":"\#(String(repeating: "00", count: 32))"}"#]))373        out.append(lines("a", [1: status, 2: stats, 3: utxo, 4: history]))374        // the indexer understates the coin375        out.append(lines("a", [1: status, 2: stats, 3: #"[{"txid":"\#(txid)","vout":1,"value":"5000000000","height":400,"confirmations":101}]"#, 4: history.replacingOccurrences(of: "\"50000000000\"", with: "\"5000000000\""), 6: tx]))376    }377    // b: Bitcoin Cash Testnet through Bitcore378    if let f = CoinWalletFixture.funding(.bitcoinCashTestnet, value: 50_000_000) {379        let txid = f.tx.txid, script = Hex.encode(f.script), bare = String(f.address.split(separator: ":").last ?? "")380        func coin(_ index: Int, _ value: UInt64, _ s: String, mint: String, spent: String = "", spentHeight: Int = -2, mintHeight: Int = 240_000) -> String {381            #"{"chain":"BCH","network":"testnet","coinbase":false,"mintIndex":\#(index),"spentTxid":"\#(spent)","mintTxid":"\#(mint)","mintHeight":\#(mintHeight),"spentHeight":\#(spentHeight),"address":"\#(bare)","script":"\#(s)","value":\#(value),"sequenceNumber":4294967295}"#382        }383        let mine = coin(1, 50_000_000, script, mint: txid)384        let tip = #"{"hash":"\#(String(repeating: "aa", count: 32))","height":250000,"time":"2026-12-05T05:08:10.000Z"}"#385        let tx = #"{"txid":"\#(txid)","blockHeight":240000,"blockTime":"2026-11-29T11:22:09.000Z","coinbase":false,"size":225,"fee":223}"#386        let coins = #"{"inputs":[\#(coin(0, 50_001_000, "76a914" + String(repeating: "44", count: 20) + "88ac", mint: source, spent: txid, spentHeight: 240_000, mintHeight: 239_000))],"outputs":[\#(coin(0, 777, "76a914" + String(repeating: "33", count: 20) + "88ac", mint: txid)),\#(mine)]}"#387        out.append(lines("b", [1: tip, 2: "[" + mine + "]", 3: "[" + mine + "]", 4: tx, 5: #"{"feerate":0.00001}"#, 6: coins, 8: #"{"txid":"\#(String(repeating: "00", count: 32))"}"#]))388        out.append(lines("b", [1: tip, 2: "[" + mine + "]", 3: "[" + mine + "]", 4: tx, 6: coins]))389    }390    // c: Litecoin Testnet through Esplora, a second indexer (Blockbook) answering its own tip391    if let f = CoinWalletFixture.funding(.litecoinTestnet, value: 40_000_000) {392        let txid = f.tx.txid, script = Hex.encode(f.script)393        let tx = #"[{"txid":"\#(txid)","version":1,"locktime":0,"vin":[{"txid":"\#(source)","vout":0,"prevout":{"scriptpubkey":"0014\#(String(repeating: "ee", count: 20))","value":40001000},"sequence":4294967295}],"vout":[{"scriptpubkey":"76a914\#(String(repeating: "33", count: 20))88ac","value":777},{"scriptpubkey":"\#(script)","scriptpubkey_address":"\#(f.address)","value":40000000}],"fee":223,"weight":900,"status":{"confirmed":true,"block_height":150,"block_time":1700000000}}]"#394        let utxo = #"[{"txid":"\#(txid)","vout":1,"value":40000000,"status":{"confirmed":true,"block_height":150,"block_time":1700000000}}]"#395        let stats = #"{"address":"\#(f.address)","chain_stats":{"funded_txo_count":1,"funded_txo_sum":40000000,"spent_txo_count":0,"spent_txo_sum":0,"tx_count":1},"mempool_stats":{"funded_txo_count":0,"funded_txo_sum":0,"spent_txo_count":0,"spent_txo_sum":0,"tx_count":0}}"#396        out.append(lines("c", [1: "200", 2: stats, 3: utxo, 4: tx, 5: #"{"1":25.3,"6":10.1,"144":1.0}"#, 7: #"{"blockbook":{"bestHeight":199}}"#, 8: txid]))397        out.append(lines("c", [1: "-9223372036854775808", 2: stats, 3: utxo, 4: tx, 7: #"{"blockbook":{"bestHeight":100}}"#]))398        out.append(lines("c", [1: "200", 2: stats, 3: utxo, 4: tx, 7: #"{"blockbook":{"bestHeight":999999999}}"#]))399    }400    return out401}402403// MARK: - Targets404405let utxoCoinTargets: [FuzzTarget] = [406    FuzzTarget(407        "cashaddr", "CashAddr: decode with and without prefix, canonical re-encoding, checksum, and the Bitcoin Cash address parser above it",408        maxLength: 200, text: true,409        dictionary: ["bitcoincash:", "bchtest:", "bchreg:", "simpleledger:", "ecash:", ":", "q", "p", "z", "r", "Q", "P", "qqqqqqqq", "1", "b", "i", "o"],410        seeds: cashAddrSeeds411    ) { input in412        let text = fuzzString(input)413        let lower = text.lowercased()414        for prefix in [nil, "bitcoincash", "bchtest"] as [String?] {415            guard let d = CashAddr.decode(text, defaultPrefix: prefix) else { continue }416            FuzzOutcome.note("decoded\(d.hash.count)")417            fuzzCheck([20, 24, 28, 32, 40, 48, 56, 64].contains(d.hash.count) && d.type <= 15 && !d.prefix.isEmpty, "decoded fields out of range")418            guard let again = CashAddr.encode(prefix: d.prefix, type: d.type, hash: d.hash) else { fuzzFail("decoded CashAddr does not encode") }419            // canonical: the lower-case text itself, or the default prefix followed by it420            fuzzCheck(again == lower || again == d.prefix + ":" + lower, "CashAddr re-encoding differs from the text")421            fuzzCheck(CashAddr.decode(again) == d && CashAddr.hasValidChecksum(again), "canonical CashAddr does not decode to the same value")422            fuzzCheck(text == lower || text == text.uppercased(), "mixed-case CashAddr accepted")423        }424        if lower.contains(":"), CashAddr.decode(text) != nil { fuzzCheck(CashAddr.hasValidChecksum(text), "decoded without a valid checksum") }425        // the address layer: only 20-byte P2PKH / P2SH of the network's own prefix426        for network in [BitcoinNetwork.bitcoinCash, .bitcoinCashTestnet] {427            guard let a = attempt(network.rawValue, { try BitcoinAddress(text, network: network) }) else { continue }428            fuzzCheck(a.type == .p2pkh || a.type == .p2sh, "Bitcoin Cash address of another type")429            guard let d = CashAddr.decode(a.string), d.prefix == network.cashAddrPrefix, d.hash.count == 20, d.type <= 1 else { fuzzFail("Bitcoin Cash address is not a 20-byte CashAddr of the network") }430            guard let back = try? BitcoinAddress(scriptPubKey: a.scriptPubKey, network: network) else { fuzzFail("script of a parsed address has no address") }431            fuzzCheck(back.string == a.string && (try? BitcoinAddress(a.string, network: network))?.scriptPubKey == a.scriptPubKey, "address / script round trip")432            let other: BitcoinNetwork = network == .bitcoinCash ? .bitcoinCashTestnet : .bitcoinCash433            if !a.isLegacyFormat { fuzzCheck((try? BitcoinAddress(text, network: other)) == nil, "CashAddr accepted on both Bitcoin Cash networks") }434        }435        // the encoder on the raw bytes436        var f = FuzzInput(input)437        let type = f.byte() & 0x1f, size = [20, 24, 28, 32, 40, 48, 56, 64, 19, 0][Int(f.byte()) % 10]438        if let e = CashAddr.encode(prefix: "bchtest", type: type, hash: f.take(size)) {439            fuzzCheck(type <= 15 && size >= 20, "invalid CashAddr encoded")440            fuzzCheck(CashAddr.decode(e)?.type == type, "encoded CashAddr does not decode")441        }442    },443444    FuzzTarget(445        "utxo-coin-address", "Address text on each UTXO network (letter selector): parse, address ⇄ script round trip, no acceptance by another coin",446        maxLength: 140, text: true,447        dictionary: ["ltc1q", "tltc1q", "ltc1p", "bc1q", "tb1q", "bitcoincash:q", "bchtest:p", "D", "L", "M", "3", "1", "n", "2", "Q", "9", "A", ":", "simpleledger:", "ecash:"],448        seeds: coinAddressSeeds449    ) { input in450        guard let selector = input.first else { return }451        let networks = BitcoinNetwork.allCases452        let network = networks[fuzzSelector(selector, networks.count)]453        let text = fuzzString(Bytes(input.dropFirst()))454        var acceptors = [BitcoinNetwork]()455        for n in networks where (try? BitcoinAddress(text, network: n)) != nil { acceptors.append(n) }456        // which networks may share an encoding: one coin's own networks; Bitcoin and Bitcoin Cash for the Base58 form;457        // the test networks among themselves (bytes 0x6f and 0xc4 are common to them)458        let coins = Set(acceptors.map(\.coin))459        if coins.count > 1 {460            let base58 = !text.contains(":") && !["bc1", "tb1", "ltc1", "tltc1", "bcrt1", "rltc1"].contains { text.lowercased().hasPrefix($0) }461            let legacyPair = coins == [.bitcoin, .bitcoinCash] && acceptors.allSatisfy { !$0.isTest }462            fuzzCheck(base58 && (legacyPair || acceptors.allSatisfy(\.isTest)), "address accepted by several coins: \(acceptors.map(\.rawValue))")463        }464        fuzzCheck(!(acceptors.contains { $0.isTest } && acceptors.contains { !$0.isTest }), "address accepted on a main and on a test network")465        guard let a = attempt({ try BitcoinAddress(text, network: network) }) else { return }466        FuzzOutcome.note(a.type.rawValue)467        fuzzCheck(a.network == network && a.type != .unknown, "parsed address fields")468        fuzzCheck(network.supportsSegWit || BitcoinScript.witnessProgram(of: a.scriptPubKey) == nil, "SegWit address accepted on a network without SegWit")469        guard let back = try? BitcoinAddress(scriptPubKey: a.scriptPubKey, network: network) else { fuzzFail("script of a parsed address has no address") }470        fuzzCheck(back.string == a.string && back.type == a.type, "address(script(address)) differs")471        guard let again = try? BitcoinAddress(a.string, network: network) else { fuzzFail("canonical address does not parse") }472        fuzzCheck(again.scriptPubKey == a.scriptPubKey && again.string == a.string && !again.isLegacyFormat, "canonical address round trip")473        if let legacy = a.base58String {474            guard let l = try? BitcoinAddress(legacy, network: network) else { fuzzFail("Base58 form does not parse") }475            fuzzCheck(l.scriptPubKey == a.scriptPubKey && l.isLegacyFormat == (network.cashAddrPrefix != nil), "Base58 form round trip")476        }477        fuzzCheck(a.isLegacyFormat == false || network.cashAddrPrefix != nil, "legacy flag outside Bitcoin Cash")478        fuzzUse(a.stringWithoutPrefix.utf8.count)479    },480481    FuzzTarget(482        "utxo-legacy-transaction", "Transactions without witness (Dogecoin, Bitcoin Cash): strict decode, byte-identical re-encode, identifier, digests of both algorithms",483        maxLength: 4096, tokens: [[0x00, 0x01], [0xfd, 0xfd, 0x00], [0xff, 0xff, 0xff, 0xff], [0x41], [0x76, 0xa9, 0x14], [0x88, 0xac]], seeds: legacyTransactionSeeds484    ) { input in485        guard let tx = attempt({ try BitcoinTransaction(parsing: input, allowWitness: false) }) else {486            // what the witness-aware parser accepts and this one refuses must carry the marker487            if let w = try? BitcoinTransaction(parsing: input, allowWitness: true) { fuzzCheck(input.count > 5 && input[4] == 0 && w.serialized() == input, "refused without being a witness serialization") }488            return489        }490        fuzzCheck(tx.serialized() == input && tx.serialized(includeWitness: false) == input, "re-encoding differs from the input")491        fuzzCheck(!tx.hasWitness && tx.vsize == input.count && tx.weight == 4 * input.count, "size of a transaction without witness")492        fuzzCheck(tx.txidBytes == SHA256.double(input) && tx.wtxid == tx.txid, "identifier")493        if tx.inputs.isEmpty {494            // "no input, then a count of 1" is also the SegWit marker and flag: the two parsers legitimately differ on a495            // transaction without inputs, which no network accepts and the sanity check refuses496            fuzzCheck((try? tx.checkSanity(maximumMoney: BitcoinNetwork.dogecoin.maximumMoney)) == nil, "a transaction without input passes the sanity check")497        } else {498            fuzzCheck((try? BitcoinTransaction(parsing: input, allowWitness: true)) == tx, "the witness-aware parser reads another transaction")499        }500        fuzzCheck((try? BitcoinTransaction(hex: tx.hex, allowWitness: false)) == tx, "hexadecimal round trip")501        for money in [BitcoinNetwork.dogecoin.maximumMoney, BitcoinNetwork.bitcoinCash.maximumMoney] {502            attempt("sanity:") { try tx.checkSanity(maximumMoney: money) }503            if let total = tx.outputValue(maximumMoney: money) { fuzzCheck(total <= money, "output total above the monetary range") }504        }505        let script = tx.outputs.first?.scriptPubKey ?? [0x51]506        for i in tx.inputs.indices.prefix(3) {507            for type: UInt32 in [0x01, 0x03, 0x82] {508                let original = attempt("l:") { try BitcoinSighash.legacy(transaction: tx, inputIndex: i, scriptCode: script, type: BitcoinSighashType(rawValue: type)) }509                let fork = attempt("f:") { try BitcoinSighash.forkID(transaction: tx, inputIndex: i, scriptCode: script, value: 1, type: BitcoinSighashType(rawValue: type | 0x40)) }510                fuzzCheck(original?.count == 32 && fork?.count == 32 && original != fork, "digests")511                fuzzCheck((try? BitcoinSighash.forkID(transaction: tx, inputIndex: i, scriptCode: script, value: 2, type: BitcoinSighashType(rawValue: type | 0x40))) != fork, "fork-id digest ignores the amount")512            }513            // a transaction read from the wire never verifies against an arbitrary output, under any scheme514            let spent = BitcoinTransaction.Output(value: 1, scriptPubKey: (try? BitcoinScript.p2pkh(publicKeyHash: Bytes(repeating: 7, count: 20))) ?? [])515            for scheme in UTXOSighashScheme.allCases { fuzzCheck((try? BitcoinVerifier.verifyInput(transaction: tx, inputIndex: i, spentOutput: spent, scheme: scheme)) == nil, "verified against an unrelated output") }516        }517        // as a previous transaction: it authenticates only its own outputs518        for (n, o) in tx.outputs.enumerated().prefix(3) {519            guard let outPoint = BitcoinOutPoint(hash: tx.txidBytes, index: UInt32(n)) else { continue }520            fuzzCheck(BitcoinUTXO(outPoint: outPoint, value: o.value, scriptPubKey: o.scriptPubKey, confirmations: 1).isAuthenticated(by: tx), "own output not authenticated")521            fuzzCheck(!BitcoinUTXO(outPoint: outPoint, value: o.value &+ 1, scriptPubKey: o.scriptPubKey, confirmations: 1).isAuthenticated(by: tx), "another amount authenticated")522        }523        if let beyond = BitcoinOutPoint(hash: tx.txidBytes, index: UInt32(truncatingIfNeeded: tx.outputs.count)) {524            fuzzCheck(!BitcoinUTXO(outPoint: beyond, value: 0, scriptPubKey: [], confirmations: 1).isAuthenticated(by: tx), "output index beyond the transaction authenticated")525        }526    },527528    FuzzTarget(529        "psbt-prevtx", "PSBT with previous transactions (PSBT_IN_NON_WITNESS_UTXO): the fee reported is inputs from authenticated previous outputs minus outputs, on every scheme",530        maxLength: 8192, tokens: [[0x70, 0x73, 0x62, 0x74, 0xff], [0x01, 0x00], [0x01, 0x01], [0x01, 0x03], [0x00], [0x41, 0x00, 0x00, 0x00], [0x01, 0x00, 0x00, 0x00]],531        seeds: psbtPreviousTransactionSeeds532    ) { input in533        guard let parsed = attempt({ try PSBT(parsing: input) }) else { return }534        fuzzCheck((try? PSBT(parsing: parsed.serialized())) == parsed, "PSBT round trip")535        for network in [BitcoinNetwork.dogecoin, .bitcoinCash, .litecoin] {536            var psbt = parsed537            psbt.prepare(for: network)538            let tx = psbt.unsignedTransaction539            // every previous transaction that was parsed is the one its outpoint names540            for i in psbt.inputs.indices {541                if let p = psbt.inputs[i].nonWitnessUTXO {542                    fuzzCheck(p.txidBytes == tx.inputs[i].previousOutput.hash && Int(tx.inputs[i].previousOutput.index) < p.outputs.count, "previous transaction not authenticated at parse")543                    fuzzCheck(psbt.spentOutput(inputIndex: i) == p.outputs[Int(tx.inputs[i].previousOutput.index)], "spent output is not the one of the previous transaction")544                }545            }546            if let fee = psbt.fee {547                FuzzOutcome.note("fee")548                var total: UInt64 = 0549                for i in psbt.inputs.indices {550                    guard let spent = psbt.spentOutput(inputIndex: i) else { fuzzFail("fee reported with an input of unknown amount") }551                    if network.sighashScheme != .bip143 { fuzzCheck(psbt.inputs[i].nonWitnessUTXO != nil, "fee reported from a witness-UTXO record on \(network.rawValue)") }552                    total += spent.value553                }554                let outputs = tx.outputs.reduce(UInt64(0)) { $0 + $1.value }555                fuzzCheck(total >= outputs && fee == total - outputs && total <= network.maximumMoney, "fee is not inputs minus outputs")556            }557            // the account signs only when the whole fee is authenticated (BIP-44 account: the digest commits to no amount)558            if let account = CoinFixtures.account(network, .bip44) {559                var copy = psbt560                if let added = attempt("s:", { try account.sign(psbt: &copy) }) {561                    fuzzCheck(copy.fee != nil && copy.inputs.allSatisfy { $0.nonWitnessUTXO != nil }, "signed a PSBT whose fee is not authenticated")562                    if added > 0 { FuzzOutcome.note("signed") }563                    fuzzCheck(copy.unsignedTransaction == tx, "signing changed the transaction")564                } else {565                    fuzzCheck(copy == psbt, "a refused PSBT was modified")566                }567            }568            attempt("x:") { try psbt.extractTransaction(verify: true) }569        }570    },571572    FuzzTarget(573        "json-blockbook", "Blockbook responses: status, block index, address, unspent outputs, history, transaction, fee estimate, broadcast, chain check",574        maxLength: 4096, text: true,575        dictionary: ["\"txid\":", "\"vout\":", "\"value\":\"", "\"bestHeight\":", "\"confirmations\":", "\"blockHeight\":", "\"hex\":\"", "\"vin\":[", "\"addresses\":[", "\"isAddress\":true", "\"totalPages\":", "\"page\":", "\"result\":\"",576                     "\"error\":\"", "18446744073709551615", "18446744073709551616", "-9223372036854775808", "9223372036854775807", "-1", "1e999", "null", "\"transactions\":[", "\"unconfirmedBalance\":\"-", "[", "]", "{", "}"],577        seeds: { blockbookSeedTexts.map { Bytes(letterSelector($0).utf8) } }578    ) { input in579        guard let selector = input.first else { return }580        let body = Data(input.dropFirst())581        let network: BitcoinNetwork = body.count % 2 == 0 ? .dogecoin : .bitcoinCash582        let configuration = EndpointConfiguration(esplora: [:], blockbook: [network.rawValue: ["https://bb.test/api/v2"]], ethereumRPC: [:], ethereumIndexer: [:], priceAPI: "")583        let which = fuzzSelector(selector, 9)584        let client = BlockbookClient(network: network, configuration: configuration, transport: StubTransport(body: body, status: which == 7 && body.count % 3 == 0 ? 400 : 200))585        let address = network == .dogecoin ? "DH5yaieqoZN36fDVciNyRueRGvGLR3mr7L" : "qqjyycerhgygpzwxmnfe83nchng8v66qas5yt745rm"586        fuzzAwait {587            do {588                switch which {589                case 0:590                    let tip = try await client.tip()591                    fuzzCheck(tip.height >= 0 && tip.height < 1_000_000_000, "tip out of range")592                case 1: fuzzCheck(UTXOWire.isTxid(try await client.blockHash(height: 7)), "block hash is not 64 hexadecimal characters")593                case 2:594                    let s = try await client.stats(address: address)595                    fuzzCheck((s.transactionCount ?? 0) >= 0 && (s.isUsed || s.transactionCount == 0 || s.transactionCount == nil), "address statistics")596                case 3:597                    let coins = try await client.coins(address: address)598                    fuzzCheck(coins.count <= UTXOWire.maximumCoins && coins.allSatisfy { UTXOWire.isTxid($0.txid) && ($0.height ?? 1) > 0 }, "coin list")599                    for c in coins.prefix(4) { fuzzUse(c.confirmations(tipHeight: Int(c.vout))) }600                case 4:601                    let page = try await client.history(address: address, cursor: body.count % 5 == 0 ? UTXOHistoryCursor(token: "2") : nil)602                    fuzzCheck(page.transactions.count <= UTXOWire.maximumTransactionsPerPage, "history page too long")603                    for t in page.transactions {604                        fuzzCheck(UTXOWire.isTxid(t.txid) && t.inputs.count <= UTXOWire.maximumEntriesPerTransaction && t.outputs.count <= UTXOWire.maximumEntriesPerTransaction, "history transaction")605                        fuzzCheck((t.height ?? 1) > 0 && (t.virtualSize ?? 1) > 0 && t.outputs.allSatisfy { ($0.scriptPubKey?.utf8.count ?? 0) <= UTXOWire.maximumScriptHex }, "history transaction fields")606                    }607                    if let next = page.next { fuzzCheck(Int(next.token) != nil, "cursor") }608                case 5:609                    let hex = try await client.rawTransaction(txid: sampleTxid)610                    fuzzCheck(!hex.isEmpty && hex == hex.lowercased() && Hex.decode(hex) != nil, "raw transaction is not lower-case hexadecimal")611                    // what the wallet does with it: parse, and trust it only for the identifier it hashes to612                    if let tx = try? BitcoinTransaction(hex: hex, allowWitness: false) { fuzzCheck(tx.txid != sampleTxid || tx.hex == hex, "raw transaction identity") }613                case 6:614                    let estimates = try await client.feeEstimates()615                    fuzzCheck(estimates.values.allSatisfy { $0.isFinite && $0 > 0 && $0 <= 100_000_000 }, "fee estimate out of range")616                    for v in estimates.values { if let r = FeeRate.fromEstimate(satPerVByte: v) { fuzzCheck(r.clamped(to: network) <= .maximum(for: network), "clamped rate above the ceiling") } }617                case 7:618                    let id = try await client.broadcast(rawHex: "00")619                    fuzzCheck(id.isEmpty || UTXOWire.isTxid(id), "broadcast answer")620                default: try await client.verifyChain()621                }622                FuzzOutcome.note("ok\(which)")623            } catch {624                FuzzOutcome.note("error\(which)")625            }626        }627    },628629    FuzzTarget(630        "json-bitcore", "Bitcore responses: block, tip, coins of an address, statistics, history, transaction with its coins, fee, broadcast, chain check",631        maxLength: 4096, text: true,632        dictionary: ["\"mintTxid\":\"", "\"mintIndex\":", "\"mintHeight\":", "\"spentTxid\":\"", "\"spentHeight\":", "\"value\":", "\"script\":\"", "\"address\":\"", "\"coinbase\":true", "\"height\":", "\"hash\":\"", "\"feerate\":",633                     "\"inputs\":[", "\"outputs\":[", "\"txid\":\"", "\"blockHeight\":", "\"fee\":", "-2", "-1", "-3", "18446744073709551615", "-9223372036854775808", "9223372036854775807", "1e999", "null", "\"false\"", "[", "]", "{", "}"],634        seeds: { bitcoreSeedTexts.map { Bytes(letterSelector($0).utf8) } }635    ) { input in636        guard let selector = input.first else { return }637        let body = Data(input.dropFirst())638        let network: BitcoinNetwork = body.count % 2 == 0 ? .dogecoin : .bitcoinCash639        let configuration = EndpointConfiguration(esplora: [:], bitcore: [network.rawValue: ["https://bc.test/api/X/mainnet"]], ethereumRPC: [:], ethereumIndexer: [:], priceAPI: "")640        let which = fuzzSelector(selector, 9)641        let client = BitcoreClient(network: network, configuration: configuration, transport: StubTransport(body: body, status: which == 7 && body.count % 3 == 0 ? 500 : 200))642        let address = network == .dogecoin ? "DH5yaieqoZN36fDVciNyRueRGvGLR3mr7L" : "bitcoincash:qqjyycerhgygpzwxmnfe83nchng8v66qas5yt745rm"643        fuzzAwait {644            do {645                switch which {646                case 0:647                    let tip = try await client.tip()648                    fuzzCheck(tip.height >= 0 && tip.height < 1_000_000_000, "tip out of range")649                case 1: fuzzCheck(UTXOWire.isTxid(try await client.blockHash(height: 0)), "block hash is not 64 hexadecimal characters")650                case 2:651                    let s = try await client.stats(address: address)652                    fuzzCheck((s.transactionCount ?? 0) >= 0 && (s.isComplete || (s.hasSpent && s.isUsed && s.confirmedBalance == nil)), "address statistics")653                case 3:654                    let coins = try await client.coins(address: address)655                    fuzzCheck(coins.count < BitcoreClient.coinLimit && coins.allSatisfy { UTXOWire.isTxid($0.txid) && ($0.height ?? 1) > 0 }, "coin list")656                case 4:657                    let page = try await client.history(address: address, cursor: body.count % 5 == 0 ? UTXOHistoryCursor(token: "1") : nil)658                    fuzzCheck(page.transactions.count <= BitcoreClient.pageSize, "history page too long")659                case 5:660                    let t = try await client.transaction(sampleTxid)661                    fuzzCheck(t.txid == sampleTxid && t.inputs.count <= UTXOWire.maximumEntriesPerTransaction && t.outputs.count <= UTXOWire.maximumEntriesPerTransaction, "transaction")662                    fuzzCheck((t.height ?? 1) > 0 && (t.virtualSize ?? 1) > 0 && t.inputs.allSatisfy { $0.txid == nil || UTXOWire.isTxid($0.txid ?? "") }, "transaction fields")663                case 6:664                    let estimates = try await client.feeEstimates()665                    fuzzCheck(estimates.values.allSatisfy { $0.isFinite && $0 > 0 && $0 <= 100_000_000 }, "fee estimate out of range")666                case 7:667                    let id = try await client.broadcast(rawHex: "00")668                    fuzzCheck(id.isEmpty || UTXOWire.isTxid(id), "broadcast answer")669                default: try await client.verifyChain()670                }671                // Bitcore never serves raw transactions672                do { _ = try await client.rawTransaction(txid: sampleTxid); fuzzFail("Bitcore served a raw transaction") } catch {}673                FuzzOutcome.note("ok\(which)")674            } catch {675                FuzzOutcome.note("error\(which)")676            }677        }678    },679680    FuzzTarget(681        "utxo-indexer-normalise", "Wallet service synchronising Dogecoin, Bitcoin Cash and Litecoin test networks against hostile Blockbook, Bitcore and Esplora answers, then fee options, a payment and its signature",682        maxLength: 6000, text: true,683        dictionary: ["\n", "\"value\":", "\"value\":\"", "\"vout\":", "\"txid\":\"", "\"hex\":\"", "\"confirmations\":", "\"height\":", "\"blockHeight\":", "\"bestHeight\":", "\"mintHeight\":", "\"spentHeight\":", "\"txs\":",684                     "\"totalPages\":", "\"transactions\":[", "\"coinbase\":true", "18446744073709551615", "1000000000000000000", "1000000000000000001", "2100000000000000", "-9223372036854775808", "9223372036854775807",685                     "999999999", "1000000000", "-1", "-2", "null", "[]", "{}", "1e999"],686        seeds: coinSyncSeeds687    ) { input in688        guard let fixture = CoinWalletFixture.shared else { return }689        let sections = fuzzString(input).split(separator: "\n", omittingEmptySubsequences: false).map(String.init)690        fixture.router.install(sections)691        let network = CoinWalletFixture.networks[fuzzSelector(sections.first?.utf8.first ?? 0x61, 3)]692        let service = fixture.service693        fuzzAwait {694            let snapshot: BitcoinSnapshot695            do { snapshot = try await service.syncUTXOCoin(network) } catch {696                note("sync:" + String(describing: error))697                return698            }699            note("synced\(min(snapshot.utxos.count, 3))")700            // bounds on what is kept701            let maximum = network.maximumMoney702            var total: UInt64 = 0703            for u in snapshot.utxos {704                fuzzCheck(u.utxo.value > 0 && u.utxo.value <= maximum, "coin outside the monetary range kept")705                total += u.utxo.value706                fuzzCheck(total <= maximum, "coins above the monetary range kept")707                // every coin is on a script the wallet derived itself708                fuzzCheck(u.utxo.derivation != nil && snapshot.addresses.contains { $0.address == u.utxo.address } || u.utxo.address == snapshot.receiveAddress.address, "coin on a script that is not the wallet's")709            }710            fuzzCheck(snapshot.balance.confirmed + snapshot.balance.pending == total && snapshot.network == network && snapshot.tipHeight < 100_000_000, "balance is not the sum of the coins kept")711            fuzzCheck(Set(snapshot.utxos.map(\.utxo.outPoint)).count == snapshot.utxos.count, "duplicate coin kept")712            fuzzCheck(snapshot.transactions.count <= 2 * 100 * 80 && snapshot.transactions.allSatisfy { $0.txid.utf8.count == 64 }, "history size")713            if let fees = try? await service.coinFeeOptions(network) {714                let floor = FeeRate.minimum(for: network), cap = FeeRate.maximum(for: network)715                fuzzCheck(fees.slow.rate <= fees.normal.rate && fees.normal.rate <= fees.fast.rate && fees.slow.rate >= floor && fees.fast.rate <= cap, "fee options outside the network's bounds")716            }717            // a payment from what was kept718            let external = (try? BitcoinAddress(scriptPubKey: BitcoinScript.p2pkh(publicKeyHash: Bytes(repeating: 0x55, count: 20)), network: network).string) ?? ""719            guard let plan = try? await service.prepareCoinSend(network: network, to: external, amount: 10_000_000, feeRate: .minimum(for: network), sendMax: sections.count % 5 == 0,720                                                              coinControl: BitcoinCoinControl(includeUnconfirmed: true)) else {721                note("no-plan")722                return723            }724            note("plan")725            let inputs = plan.plan.inputs.reduce(UInt64(0)) { $0 + $1.value }, outputs = plan.plan.transaction.outputs.reduce(UInt64(0)) { $0 + $1.value }726            fuzzCheck(inputs == outputs + plan.fee && inputs <= total, "plan does not conserve value")727            var result = try? await service.signAndBroadcast(service.review(for: plan))728            if result == nil, (try? await service.unlock(password: CoinWalletFixture.password)) != nil { result = try? await service.signAndBroadcast(service.review(for: plan)) }729            let sent = fixture.router.broadcasts730            guard let raw = sent.first else {731                fuzzCheck(result == nil, "a result without a broadcast")732                note("not-sent")733                return734            }735            note("sent")736            // what left the wallet: exactly the plan, every signature valid, and on Dogecoin every coin authenticated by737            // the raw transaction the indexer served (section 6)738            let hex = raw.hasPrefix("{") ? ((try? JSONDecoder().decode([String: String].self, from: Data(raw.utf8)))?["rawTx"] ?? "") : raw739            guard let tx = try? BitcoinTransaction(hex: hex, allowWitness: network.supportsSegWit) else { fuzzFail("the wallet broadcast something that is not a transaction") }740            fuzzCheck(tx.outputs == plan.plan.transaction.outputs && tx.inputs.map(\.previousOutput) == plan.plan.inputs.map(\.outPoint), "the transaction broadcast is not the plan")741            fuzzCheck(BitcoinVerifier.isValid(transaction: tx, spentOutputs: plan.plan.inputs.map(\.output), scheme: network.sighashScheme), "a signature of the broadcast transaction is invalid")742            fuzzCheck(network.supportsSegWit || !tx.hasWitness, "witness data on a network without SegWit")743            if network == .dogecoinTestnet {744                struct Served: Decodable { let hex: String? }745                let served = (try? JSONDecoder().decode(Served.self, from: Data((sections.count > 6 ? sections[6] : "").utf8)))?.hex ?? ""746                guard let previous = try? BitcoinTransaction(hex: served, allowWitness: false) else { fuzzFail("Dogecoin payment signed without a parsable previous transaction") }747                fuzzCheck(plan.plan.inputs.allSatisfy { $0.isAuthenticated(by: previous) }, "Dogecoin payment signed over a coin its previous transaction does not show")748            }749        }750    },751752    FuzzTarget(753        "utxo-coin-sign", "Build and sign on the six networks from fuzzed coins, amounts and rates: value conservation, coin rules, signatures under the right digest only",754        maxLength: 256, seeds: {755            // network, purpose/flags, coin count, per coin (chain, index, 8-byte value, filler), amount, rate, destination kind756            func seed(_ network: UInt8, _ flags: UInt8, _ coins: [(UInt8, UInt8, UInt64, UInt8)], amount: UInt64, rate: UInt32, kind: UInt8) -> Bytes {757                var out: Bytes = [network, flags, UInt8(coins.count)]758                for c in coins { out += [c.0, c.1] + (0..<8).map { UInt8(truncatingIfNeeded: c.2 >> (8 * UInt64($0))) } + [c.3] }759                out += (0..<8).map { UInt8(truncatingIfNeeded: amount >> (8 * UInt64($0))) }760                out += (0..<4).map { UInt8(truncatingIfNeeded: rate >> (8 * UInt32($0))) } + [kind]761                return out762            }763            var out = [Bytes]()764            for n in UInt8(0)..<6 {765                out.append(seed(n, 0, [(0, 1, 5_000_000_000, 0), (1, 2, 700_000_000, 1)], amount: 1_200_000_000, rate: 0, kind: 0))766                out.append(seed(n, 1, [(0, 3, 90_000_000_000, 2)], amount: 0, rate: 3, kind: 1))767                // send-max with a coin that costs more to spend than it holds: it is left out768                out.append(seed(n, 1, [(0, 3, 90_000_000_000, 2), (1, 2, 1, 0)], amount: 0, rate: 5, kind: 0))769                out.append(seed(n, 2, [(0, 0, 2_000_000, 0), (0, 0, 3_000_000, 1), (1, 7, 4_000_000, 2)], amount: 8_000_000, rate: 1, kind: 2))770                out.append(seed(n, 4, [(1, 5, UInt64.max, 0), (0, 5, 1 << 62, 0)], amount: 1 << 61, rate: 0xffff_ffff, kind: 3))771            }772            return out773        }774    ) { input in775        var f = FuzzInput(input)776        let network = coinNetworks[Int(f.byte()) % coinNetworks.count]777        let flags = f.byte()778        let purpose: UTXOAccountPurpose = network.supportsSegWit && flags & 4 == 0 ? .bip84 : .bip44779        guard let account = CoinFixtures.account(network, purpose) else { return }780        var utxos = [BitcoinUTXO](), previous = [String: BitcoinTransaction]()781        let count = Int(f.byte()) % 5 + 1782        for k in 0..<count {783            let chain = f.byte(), index = f.byte()784            let value = f.take(8).enumerated().reduce(UInt64(0)) { $0 | UInt64($1.element) << (8 * UInt64($1.offset)) }785            guard let c = CoinFixtures.coin(account, chain: chain, index: index, value: value, salt: [UInt8(k), chain, index], filler: Int(f.byte())) else { continue }786            if previous[c.utxo.outPoint.txid] != nil { continue }787            utxos.append(c.utxo)788            previous[c.utxo.outPoint.txid] = c.previous789        }790        let amount = f.take(8).enumerated().reduce(UInt64(0)) { $0 | UInt64($1.element) << (8 * UInt64($1.offset)) }791        let rateBytes = f.take(4).enumerated().reduce(UInt64(0)) { $0 | UInt64($1.element) << (8 * UInt64($1.offset)) }792        let floor = FeeRate.minimum(for: network).milliSatPerVByte793        let rate = FeeRate(milliSatPerVByte: flags & 8 != 0 ? rateBytes : floor + rateBytes % (FeeRate.maximum(for: network).milliSatPerVByte - floor + 1))794        let hash = fixtureBytes("utxo-coin-sign-destination", 32)795        let destination: Bytes796        switch f.byte() % 6 {797        case 0: destination = (try? BitcoinScript.p2pkh(publicKeyHash: Bytes(hash.prefix(20)))) ?? []798        case 1: destination = (try? BitcoinScript.p2sh(scriptHash: Bytes(hash.prefix(20)))) ?? []799        case 2: destination = (try? BitcoinScript.p2wpkh(publicKeyHash: Bytes(hash.prefix(20)))) ?? []800        case 3: destination = (try? BitcoinScript.p2tr(outputKey: hash)) ?? []801        case 4: destination = [0x6a, 0x02, 0x01, 0x02]802        default: destination = (try? account.scriptPubKey(chain: .receive, index: 9)) ?? []803        }804        let sendMax = flags & 1 != 0805        guard let change = try? account.scriptPubKey(chain: .change, index: 6) else { return }806        var request = BitcoinSpendRequest(network: network, recipients: sendMax ? [] : [.init(value: amount, scriptPubKey: destination)], utxos: utxos, feeRate: rate,807                                          changeScript: flags & 2 != 0 ? nil : change, sendMaxScript: sendMax ? destination : nil)808        request.seed = UInt64(flags)809        request.currentHeight = flags & 16 != 0 ? nil : 1_234_567810        guard let plan = attempt({ try BitcoinTransactionBuilder.build(request) }) else { return }811        let tx = plan.transaction812        // sums cannot overflow: the builder bounded the candidates by the monetary range813        let inputs = plan.inputs.reduce(UInt64(0)) { $0 + $1.value }, outputs = tx.outputs.reduce(UInt64(0)) { $0 + $1.value }814        fuzzCheck(inputs == outputs + plan.fee && inputs <= network.maximumMoney, "value is not conserved")815        fuzzCheck(plan.fee >= rate.fee(weight: plan.estimatedWeight) && plan.fee <= request.maximumFee, "fee outside [target, cap]")816        fuzzCheck(rate >= .minimum(for: network) && rate <= .maximum(for: network), "built at a rate outside the network's bounds")817        fuzzCheck(tx.outputs.allSatisfy { BitcoinScript.isUnspendable($0.scriptPubKey) || (!BitcoinSizeEstimator.isDust($0, network: network) && $0.value > 0) }, "dust output")818        fuzzCheck(network.supportsSegWit || tx.outputs.allSatisfy { BitcoinScript.witnessProgram(of: $0.scriptPubKey) == nil }, "witness program paid without SegWit")819        fuzzCheck(tx.inputs.allSatisfy { $0.sequence == (network.supportsRBF ? 0xffff_fffd : 0xffff_fffe) } && tx.lockTime <= 1_234_567, "sequence or lock time")820        if sendMax {821            // every coin worth its own input is spent; a coin left out holds less than its input costs at this rate822            let left = utxos.filter { u in !plan.inputs.contains(u) }823            fuzzCheck(plan.sendMaxIndex != nil && tx.outputs.count == 1 && left.allSatisfy { u in u.inputWeight.map { u.value <= rate.fee(weight: $0) } ?? true }, "send-max shape")824        }825        guard let signed = attempt("sign:", { try account.sign(plan: plan, previousTransactions: previous) }) else { fuzzFail("a plan of the builder could not be signed") }826        let spent = plan.inputs.map(\.output)827        let scheme = network.sighashScheme828        fuzzCheck(BitcoinVerifier.isValid(transaction: signed, spentOutputs: spent, scheme: scheme), "signature invalid under the network's scheme")829        fuzzCheck(signed.outputs == tx.outputs && signed.lockTime == tx.lockTime && signed.vsize <= plan.estimatedVSize, "signed transaction differs from the plan or exceeds its size")830        if purpose == .bip44 {831            let byte: UInt8 = scheme == .bip143ForkID ? 0x41 : 0x01832            fuzzCheck(!signed.hasWitness && signed.inputs.allSatisfy { $0.scriptSig.count > 1 && $0.scriptSig[Int($0.scriptSig[0])] == byte }, "P2PKH signature form")833            fuzzCheck(!BitcoinVerifier.isValid(transaction: signed, spentOutputs: spent, scheme: scheme == .bip143ForkID ? .legacy : .bip143ForkID), "valid on the other side of the fork")834        } else {835            fuzzCheck(signed.hasWitness && signed.txid == tx.txid, "P2WPKH signature form")836        }837        if account.requiresPreviousTransactions {838            fuzzCheck((try? account.sign(plan: plan)) == nil, "signed without previous transactions")839            var lying = previous840            if var p = lying[plan.inputs[0].outPoint.txid] {841                p.lockTime ^= 1842                lying[plan.inputs[0].outPoint.txid] = p843                fuzzCheck((try? account.sign(plan: plan, previousTransactions: lying)) == nil, "signed over a previous transaction that is not the one spent")844            }845        }846    },847]848
Files main
Menu

Theme