SPB Git

Repository Public

UTXOCoinTests.swift 65.9 KB 961 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Tests/QyvoraBitcoinTests/UTXOCoinTests.swift8// 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// =============================================================================4041import Foundation42import Testing43import QyvoraMath44import QyvoraSymmetric45import QyvoraSecp256k146import QyvoraCore47@testable import QyvoraBitcoin4849// Litecoin, Dogecoin and Bitcoin Cash: addresses, derivations, signatures, sizes, fee and dust rules.50// Reference data: UTXOReferenceVectors.swift (bip_utils, bitcoinjs-lib, bitcash, public mainnet transactions),51// BCHNSighashVectors.swift (Bitcoin Cash Node), CashAddr specification examples.5253private func network(_ name: String) throws -> BitcoinNetwork { try #require(BitcoinNetwork(rawValue: name)) }5455/// A made-up transaction paying `value` to `script` (one arbitrary input): what a coin of the tests comes from.56private func funding(script: Bytes, value: UInt64, salt: UInt8, extraOutputs: Int = 0) -> BitcoinTransaction {57    let input = BitcoinTransaction.Input(previousOutput: BitcoinOutPoint(hash: Bytes(repeating: salt, count: 32), index: UInt32(salt))!, scriptSig: [0x00])58    let filler = (0..<extraOutputs).map { BitcoinTransaction.Output(value: 1_000_000 + UInt64($0), scriptPubKey: [0x6a, 0x01, UInt8($0)]) }59    return BitcoinTransaction(version: 1, inputs: [input], outputs: filler + [BitcoinTransaction.Output(value: value, scriptPubKey: script)])60}6162/// A coin of `account` at chain/index together with the transaction that created it.63private func coin(_ account: UTXOAccount, chain: UTXOAccount.Chain = .receive, index: UInt32, value: UInt64, salt: UInt8,64                  confirmations: UInt32 = 6) throws -> (utxo: BitcoinUTXO, previous: BitcoinTransaction) {65    let script = try account.scriptPubKey(chain: chain, index: index)66    let previous = funding(script: script, value: value, salt: salt, extraOutputs: Int(salt % 3))67    let outPoint = try #require(BitcoinOutPoint(hash: previous.txidBytes, index: UInt32(previous.outputs.count - 1)))68    let utxo = BitcoinUTXO(outPoint: outPoint, value: value, scriptPubKey: script, confirmations: confirmations,69                           derivation: .init(chain: chain.rawValue, index: index))70    return (utxo, previous)71}7273private struct LCG {74    var state: UInt6475    mutating func next() -> UInt64 {76        state = state &* 6_364_136_223_846_793_005 &+ 1_442_695_040_888_963_40777        return state >> 1178    }79    mutating func below(_ n: UInt64) -> UInt64 { next() % n }80}8182// MARK: - Addresses8384@Suite struct UTXOAddressTests {85    /// Addresses seen on each chain (block explorers, 2026-12-05) or produced by the reference tools.86    static let valid: [(network: BitcoinNetwork, text: String, type: BitcoinScriptType)] = [87        // Litecoin: "L" P2PKH, "M" P2SH, ltc1q P2WPKH88        (.litecoin, "LfdYLbP9F9CpmCX6atZnHZb8KkS8T6x4DK", .p2pkh),89        (.litecoin, "LP3VMt5aE2bYChcoTUYFujoxEHmZ4ZZXrQ", .p2pkh),90        (.litecoin, "LUWPbpM43E2p7ZSh8cyTBEkvpHmr3cB8Ez", .p2pkh),91        (.litecoin, "MDPewAKwj83V9FBUEK2YJUZE9X16NyfK5M", .p2sh),92        (.litecoin, "ltc1ql0p7lpatwkjm6q9x0pq4l3uc4d5rpt0xlxl0q5", .p2wpkh),93        (.litecoin, "ltc1qjmxnz78nmc8nq77wuxh25n2es7rzm5c2rkk4wh", .p2wpkh),94        (.litecoinTestnet, "tltc1q7aeurq0z0fyq8656ym8xdtf3aq2r3t0whzajya", .p2wpkh),95        (.litecoinTestnet, "tltc1q6rz28mcfaxtmd6v789l9rrlrusdprr9pesrjxk", .p2wpkh),96        (.litecoinTestnet, "mkpZhYtJu2r87Js3pDiWJDmPte2NRZ8bJV", .p2pkh),97        // Dogecoin: "D" P2PKH, "9" / "A" P2SH; testnet "n" P2PKH98        (.dogecoin, "DH5yaieqoZN36fDVciNyRueRGvGLR3mr7L", .p2pkh),99        (.dogecoin, "D7JeqAsJ9Vie3VnpticCJ2N9s2RJQQjgiG", .p2pkh),100        (.dogecoin, "DBus3bamQjgJULBJtYXpEzDWQRwF5iwxgC", .p2pkh),101        (.dogecoin, "9zwwMKiNcybj2pk29YkoJdQVM76zVJu4E5", .p2sh),102        (.dogecoinTestnet, "nZVmfmUtKPmskB9Ds4P9GUJy9eYFqPKHqH", .p2pkh),103        // Bitcoin Cash: CashAddr "q" P2PKH, "p" P2SH104        (.bitcoinCash, "bitcoincash:qpzvmgyt554gfu04u7wxrhneyk88dzvknvl94aq775", .p2pkh),105        (.bitcoinCash, "bitcoincash:qqyx49mu0kkn9ftfj6hje6g2wfer34yfnq5tahq3q6", .p2pkh),106        (.bitcoinCash, "bitcoincash:ppm2qsznhks23z7629mms6s4cwef74vcwvn0h829pq", .p2sh),107        (.bitcoinCashTestnet, "bchtest:qqaz6s295ncfs53m86qj0uw6sl8u2kuw0ymst35fx4", .p2pkh),108        (.bitcoinCashTestnet, "bchtest:pr6m7j9njldwwzlg9v7v53unlr4jkmx6eyvwc0uz5t", .p2sh),109    ]110111    @Test func validAddressesParseAndRoundTrip() throws {112        for v in Self.valid {113            let a = try BitcoinAddress(v.text, network: v.network)114            #expect(a.type == v.type, "\(v.text)")115            #expect(a.string == v.text)116            #expect(!a.isLegacyFormat)117            #expect(a.network == v.network)118            // script → address gives the same text; the script is the standard template119            #expect(try BitcoinAddress(scriptPubKey: a.scriptPubKey, network: v.network) == a)120            #expect(BitcoinScript.classify(a.scriptPubKey).type == v.type)121        }122    }123124    /// An address of one coin is refused on every network of another coin — except where two chains really share an125    /// encoding, which is listed here.126    @Test func addressesAreBoundToTheirCoin() throws {127        var refused = 0128        for v in Self.valid {129            for other in BitcoinNetwork.allCases where other != v.network {130                let parsed = BitcoinAddress.parse(v.text, network: other)131                if v.network.cashAddrPrefix != nil || v.type == .p2wpkh {132                    // CashAddr and Bech32 carry their network: only the same prefix is accepted (Bitcoin's testnet and133                    // signet share "tb")134                    let samePrefix = v.type == .p2wpkh ? other.bech32HRP == v.network.bech32HRP : other.cashAddrPrefix == v.network.cashAddrPrefix135                    #expect((parsed != nil) == samePrefix, "\(v.text) on \(other)")136                } else if v.type == .p2pkh {137                    // Base58: accepted exactly where the version byte is the same (0x6f is common to several test networks)138                    #expect((parsed != nil) == (other.p2pkhVersion == v.network.p2pkhVersion), "\(v.text) on \(other)")139                } else {140                    #expect((parsed != nil) == (other.p2shVersion == v.network.p2shVersion), "\(v.text) on \(other)")141                }142                if parsed == nil { refused += 1 }143            }144        }145        #expect(refused > 100)146        // the precise reason147        #expect(throws: BitcoinAddress.Error.wrongNetwork) { try BitcoinAddress("DH5yaieqoZN36fDVciNyRueRGvGLR3mr7L", network: .mainnet) }148        #expect(throws: BitcoinAddress.Error.wrongNetwork) { try BitcoinAddress("DH5yaieqoZN36fDVciNyRueRGvGLR3mr7L", network: .litecoin) }149        #expect(throws: BitcoinAddress.Error.wrongNetwork) { try BitcoinAddress("LfdYLbP9F9CpmCX6atZnHZb8KkS8T6x4DK", network: .dogecoin) }150        #expect(throws: BitcoinAddress.Error.wrongNetwork) { try BitcoinAddress("LfdYLbP9F9CpmCX6atZnHZb8KkS8T6x4DK", network: .bitcoinCash) }151        #expect(throws: BitcoinAddress.Error.wrongNetwork) { try BitcoinAddress("ltc1ql0p7lpatwkjm6q9x0pq4l3uc4d5rpt0xlxl0q5", network: .mainnet) }152        #expect(throws: BitcoinAddress.Error.wrongNetwork) { try BitcoinAddress("bc1qcr8te4kr609gcawutmrza0j4xv80jy8z306fyu", network: .litecoin) }153        #expect(throws: BitcoinAddress.Error.wrongNetwork) { try BitcoinAddress("tltc1q7aeurq0z0fyq8656ym8xdtf3aq2r3t0whzajya", network: .litecoin) }154        // SegWit addresses on chains without SegWit155        #expect(throws: BitcoinAddress.Error.wrongNetwork) { try BitcoinAddress("bc1qcr8te4kr609gcawutmrza0j4xv80jy8z306fyu", network: .dogecoin) }156        #expect(throws: BitcoinAddress.Error.wrongNetwork) { try BitcoinAddress("ltc1ql0p7lpatwkjm6q9x0pq4l3uc4d5rpt0xlxl0q5", network: .bitcoinCash) }157        #expect(throws: BitcoinAddress.Error.invalidFormat) { try BitcoinAddress("bc1qcr8te4kr609gcawutmrza0j4xv80jy8z306fyv", network: .dogecoin) }158        // CashAddr on the other chains, and across the Bitcoin Cash networks159        let cash = "bitcoincash:qpzvmgyt554gfu04u7wxrhneyk88dzvknvl94aq775"160        for other in [BitcoinNetwork.mainnet, .litecoin, .dogecoin, .bitcoinCashTestnet] {161            #expect(throws: BitcoinAddress.Error.wrongNetwork) { try BitcoinAddress(cash, network: other) }162        }163        #expect(throws: BitcoinAddress.Error.wrongNetwork) { try BitcoinAddress("bchtest:qqaz6s295ncfs53m86qj0uw6sl8u2kuw0ymst35fx4", network: .bitcoinCash) }164        #expect(throws: BitcoinAddress.Error.wrongNetwork) { try BitcoinAddress("qqaz6s295ncfs53m86qj0uw6sl8u2kuw0ymst35fx4", network: .bitcoinCash) }165    }166167    @Test func litecoinFormats() throws {168        // the first letter of each kind169        let hash = Bytes(repeating: 0x3c, count: 20)170        #expect(try BitcoinAddress(scriptPubKey: BitcoinScript.p2pkh(publicKeyHash: hash), network: .litecoin).string.hasPrefix("L"))171        #expect(try BitcoinAddress(scriptPubKey: BitcoinScript.p2sh(scriptHash: hash), network: .litecoin).string.hasPrefix("M"))172        #expect(try BitcoinAddress(scriptPubKey: BitcoinScript.p2sh(scriptHash: hash), network: .litecoinTestnet).string.hasPrefix("Q"))173        #expect(try BitcoinAddress(scriptPubKey: BitcoinScript.p2wpkh(publicKeyHash: hash), network: .litecoin).string.hasPrefix("ltc1q"))174        #expect(try BitcoinAddress(scriptPubKey: BitcoinScript.p2wsh(scriptHash: Bytes(repeating: 1, count: 32)), network: .litecoinTestnet).string.hasPrefix("tltc1q"))175        // Taproot (MWEB upgrade): Bech32m176        let taproot = try BitcoinAddress(scriptPubKey: BitcoinScript.p2tr(outputKey: Bytes(repeating: 2, count: 32)), network: .litecoin)177        #expect(taproot.string.hasPrefix("ltc1p") && taproot.type == .p2tr)178        #expect(try BitcoinAddress(taproot.string, network: .litecoin) == taproot)179        // upper case Bech32 is accepted and shown in lower case; mixed case is not180        let lower = "ltc1ql0p7lpatwkjm6q9x0pq4l3uc4d5rpt0xlxl0q5"181        #expect(try BitcoinAddress(lower.uppercased(), network: .litecoin).string == lower)182        #expect(throws: BitcoinAddress.Error.mixedCase) { try BitcoinAddress("ltc1Ql0p7lpatwkjm6q9x0pq4l3uc4d5rpt0xlxl0q5", network: .litecoin) }183        #expect(throws: BitcoinAddress.Error.invalidChecksum) { try BitcoinAddress("ltc1ql0p7lpatwkjm6q9x0pq4l3uc4d5rpt0xlxl0q6", network: .litecoin) }184        // the former P2SH encoding, identical to Bitcoin's "3…" (and "2…" on testnet), is refused with its own reason185        let former = Base58Check.encode([0x05] + hash), formerTest = Base58Check.encode([0xc4] + hash)186        #expect(former.hasPrefix("3") && formerTest.hasPrefix("2"))187        #expect(throws: BitcoinAddress.Error.ambiguousLegacyFormat) { try BitcoinAddress(former, network: .litecoin) }188        #expect(throws: BitcoinAddress.Error.ambiguousLegacyFormat) { try BitcoinAddress(formerTest, network: .litecoinTestnet) }189        // the same text is an ordinary P2SH address on Bitcoin190        #expect(try BitcoinAddress(former, network: .mainnet).type == .p2sh)191        // a one-character error in Base58192        #expect(throws: BitcoinAddress.Error.invalidChecksum) { try BitcoinAddress("LfdYLbP9F9CpmCX6atZnHZb8KkS8T6x4DL", network: .litecoin) }193    }194195    @Test func dogecoinFormats() throws {196        #expect(try BitcoinAddress(scriptPubKey: BitcoinScript.p2pkh(publicKeyHash: Bytes(repeating: 0, count: 20)), network: .dogecoin).string.hasPrefix("D"))197        #expect(try BitcoinAddress(scriptPubKey: BitcoinScript.p2pkh(publicKeyHash: Bytes(repeating: 0xff, count: 20)), network: .dogecoin).string.hasPrefix("D"))198        // P2SH (version 0x16) starts with "9" or "A"199        let low = try BitcoinAddress(scriptPubKey: BitcoinScript.p2sh(scriptHash: Bytes(repeating: 0, count: 20)), network: .dogecoin)200        let high = try BitcoinAddress(scriptPubKey: BitcoinScript.p2sh(scriptHash: Bytes(repeating: 0xff, count: 20)), network: .dogecoin)201        #expect(low.string.hasPrefix("9") && high.string.hasPrefix("A"))202        #expect(try BitcoinAddress(high.string, network: .dogecoin) == high)203        // testnet: "n" P2PKH (0x71), "2" P2SH (0xc4)204        #expect(try BitcoinAddress(scriptPubKey: BitcoinScript.p2pkh(publicKeyHash: Bytes(repeating: 0x55, count: 20)), network: .dogecoinTestnet).string.hasPrefix("n"))205        #expect(try BitcoinAddress(scriptPubKey: BitcoinScript.p2sh(scriptHash: Bytes(repeating: 0x55, count: 20)), network: .dogecoinTestnet).string.hasPrefix("2"))206        // no SegWit: witness scripts have no address there207        for script in [try BitcoinScript.p2wpkh(publicKeyHash: Bytes(repeating: 1, count: 20)), try BitcoinScript.p2wsh(scriptHash: Bytes(repeating: 1, count: 32)),208                       try BitcoinScript.p2tr(outputKey: Bytes(repeating: 1, count: 32))] {209            for n in [BitcoinNetwork.dogecoin, .dogecoinTestnet, .bitcoinCash, .bitcoinCashTestnet] {210                #expect(throws: BitcoinAddress.Error.noAddressForScript) { try BitcoinAddress(scriptPubKey: script, network: n) }211            }212        }213        #expect(throws: BitcoinAddress.Error.invalidChecksum) { try BitcoinAddress("DH5yaieqoZN36fDVciNyRueRGvGLR3mr7M", network: .dogecoin) }214        #expect(throws: BitcoinAddress.Error.invalidFormat) { try BitcoinAddress("DH5yaieqoZN36fDVciNyRueRGvGLR3mr70", network: .dogecoin) }215        #expect(throws: BitcoinAddress.Error.invalidFormat) { try BitcoinAddress("", network: .dogecoin) }216        #expect(throws: BitcoinAddress.Error.invalidFormat) { try BitcoinAddress("DH5yaieqoZN36fDVciNyRueRGvGLR3mr7L ", network: .dogecoin) }217    }218219    @Test func bitcoinCashFormats() throws {220        // the translation examples of the CashAddr specification: legacy accepted, CashAddr displayed221        let pairs = [222            ("1BpEi6DfDAUFd7GtittLSdBeYJvcoaVggu", "bitcoincash:qpm2qsznhks23z7629mms6s4cwef74vcwvy22gdx6a", BitcoinScriptType.p2pkh),223            ("1KXrWXciRDZUpQwQmuM1DbwsKDLYAYsVLR", "bitcoincash:qr95sy3j9xwd2ap32xkykttr4cvcu7as4y0qverfuy", .p2pkh),224            ("16w1D5WRVKJuZUsSRzdLp9w3YGcgoxDXb", "bitcoincash:qqq3728yw0y47sqn6l2na30mcw6zm78dzqre909m2r", .p2pkh),225            ("3CWFddi6m4ndiGyKqzYvsFYagqDLPVMTzC", "bitcoincash:ppm2qsznhks23z7629mms6s4cwef74vcwvn0h829pq", .p2sh),226            ("3LDsS579y7sruadqu11beEJoTjdFiFCdX4", "bitcoincash:pr95sy3j9xwd2ap32xkykttr4cvcu7as4yc93ky28e", .p2sh),227            ("31nwvkZwyPdgzjBJZXfDmSWsC4ZLKpYyUw", "bitcoincash:pqq3728yw0y47sqn6l2na30mcw6zm78dzq5ucqzc37", .p2sh),228        ]229        for (legacy, cash, type) in pairs {230            let fromLegacy = try BitcoinAddress(legacy, network: .bitcoinCash)231            let fromCash = try BitcoinAddress(cash, network: .bitcoinCash)232            #expect(fromLegacy.isLegacyFormat && !fromCash.isLegacyFormat)233            #expect(fromLegacy.string == cash && fromCash.string == cash)234            #expect(fromLegacy.scriptPubKey == fromCash.scriptPubKey && fromCash.type == type)235            #expect(fromCash.base58String == legacy)236            // without the prefix (inferred), and in upper case (QR codes)237            let body = String(cash.dropFirst("bitcoincash:".count))238            #expect(fromCash.stringWithoutPrefix == body)239            #expect(try BitcoinAddress(body, network: .bitcoinCash) == fromCash)240            #expect(try BitcoinAddress(cash.uppercased(), network: .bitcoinCash) == fromCash)241            #expect(try BitcoinAddress(body.uppercased(), network: .bitcoinCash) == fromCash)242            // the same Base58 text is a Bitcoin address too: nothing in it says which chain was meant243            #expect(try BitcoinAddress(legacy, network: .mainnet).scriptPubKey == fromCash.scriptPubKey)244        }245        let good = "bitcoincash:qpm2qsznhks23z7629mms6s4cwef74vcwvy22gdx6a"246        #expect(throws: BitcoinAddress.Error.mixedCase) { try BitcoinAddress("bitcoincash:Qpm2qsznhks23z7629mms6s4cwef74vcwvy22gdx6a", network: .bitcoinCash) }247        #expect(throws: BitcoinAddress.Error.mixedCase) { try BitcoinAddress("BitcoinCash:qpm2qsznhks23z7629mms6s4cwef74vcwvy22gdx6a", network: .bitcoinCash) }248        #expect(throws: BitcoinAddress.Error.invalidChecksum) { try BitcoinAddress(String(good.dropLast()) + "q", network: .bitcoinCash) }249        #expect(throws: BitcoinAddress.Error.invalidChecksum) { try BitcoinAddress("qpm2qsznhks23z7629mms6s4cwef74vcwvy22gdx6q", network: .bitcoinCash) }250        #expect(throws: BitcoinAddress.Error.invalidFormat) { try BitcoinAddress("bitcoincash:", network: .bitcoinCash) }251        #expect(throws: BitcoinAddress.Error.invalidFormat) { try BitcoinAddress(good + ":x", network: .bitcoinCash) }252        #expect(throws: BitcoinAddress.Error.invalidFormat) { try BitcoinAddress("bitcoincash:" + String(repeating: "b", count: 42), network: .bitcoinCash) }253        // valid CashAddr strings this wallet does not pay to: token-aware types, hashes that are not 160 bits254        let h20 = Bytes(repeating: 9, count: 20)255        for type: UInt8 in [2, 3, 15] {256            let text = try #require(CashAddr.encode(prefix: "bitcoincash", type: type, hash: h20))257            #expect(throws: BitcoinAddress.Error.unsupportedAddressType) { try BitcoinAddress(text, network: .bitcoinCash) }258        }259        for v in CashAddrVectors where v.prefix == "bitcoincash" && v.size != 20 {260            #expect(throws: BitcoinAddress.Error.unsupportedAddressType) { try BitcoinAddress(v.address, network: .bitcoinCash) }261        }262        // testnet legacy forms263        let legacyTest = try BitcoinAddress(Base58Check.encode([0x6f] + h20), network: .bitcoinCashTestnet)264        #expect(legacyTest.isLegacyFormat && legacyTest.string.hasPrefix("bchtest:q"))265    }266267    @Test func wifVersionsPerNetwork() throws {268        let key = Bytes((1...32).map { UInt8($0) })269        var seen = [String: BitcoinNetwork]()270        for n in BitcoinNetwork.allCases {271            let wif = try BitcoinWIF.encode(privateKey: key, network: n)272            let decoded = try BitcoinWIF.decode(wif, network: n)273            #expect(decoded.privateKey == key && decoded.compressed)274            if let previous = seen[wif] { #expect(previous.wifVersion == n.wifVersion) }275            seen[wif] = n276            for other in BitcoinNetwork.allCases where other.wifVersion != n.wifVersion {277                #expect(throws: BitcoinWIF.Error.wrongNetwork) { try BitcoinWIF.decode(wif, network: other) }278            }279        }280        // first characters of compressed keys: Litecoin "T", Dogecoin "Q", Bitcoin and Bitcoin Cash "K" or "L", test networks "c"281        #expect(try BitcoinWIF.encode(privateKey: key, network: .litecoin).hasPrefix("T"))282        #expect(try BitcoinWIF.encode(privateKey: key, network: .dogecoin).hasPrefix("Q"))283        #expect(try BitcoinWIF.encode(privateKey: key, network: .bitcoinCashTestnet).hasPrefix("c"))284    }285}286287/// The CashAddr larger vectors, reshaped for the address tests of this module.288private let CashAddrVectors: [(prefix: String, size: Int, address: String)] = [289    ("bitcoincash", 24, "bitcoincash:q9adhakpwzztepkpwp5z0dq62m6u5v5xtyj7j3h2ws4mr9g0"),290    ("bitcoincash", 28, "bitcoincash:qgagf7w02x4wnz3mkwnchut2vxphjzccwxgjvvjmlsxqwkcw59jxxuz"),291    ("bitcoincash", 32, "bitcoincash:qvch8mmxy0rtfrlarg7ucrxxfzds5pamg73h7370aa87d80gyhqxq5nlegake"),292    ("bitcoincash", 40, "bitcoincash:qnq8zwpj8cq05n7pytfmskuk9r4gzzel8qtsvwz79zdskftrzxtar994cgutavfklv39gr3uvz"),293]294295// MARK: - Derivations296297@Suite struct UTXODerivationTests {298    /// BIP-44 and BIP-84 keys and addresses against bip_utils, for every network of the reference set.299    @Test func derivationsMatchBipUtils() throws {300        let master = try abandonMaster()301        var compared = 0302        var accounts = [String: UTXOAccount]()303        for d in UTXOReferenceVectors.derivations {304            let n = try network(d.network)305            let purpose = try #require(UTXOAccountPurpose(rawValue: d.purpose))306            let key = "\(d.network)/\(d.purpose)"307            if accounts[key] == nil { accounts[key] = try UTXOAccount(master: master, network: n, purpose: purpose) }308            let account = try #require(accounts[key])309            let chain = try #require(UTXOAccount.Chain(rawValue: d.chain))310            #expect(try account.publicKey(chain: chain, index: d.index).hex == d.publicKey, "\(key) \(d.chain)/\(d.index)")311            #expect(try account.address(chain: chain, index: d.index).string == d.address, "\(key) \(d.chain)/\(d.index)")312            #expect(account.path(chain: chain, index: d.index).description == "m/\(d.purpose)'/\(n.coinType)'/0'/\(d.chain)/\(d.index)")313            compared += 1314        }315        #expect(compared == 80)316        #expect(accounts.count == 10)317    }318319    @Test func defaultPurposeAndRefusals() throws {320        let master = try abandonMaster()321        #expect(try UTXOAccount(master: master, network: .litecoin).purpose == .bip84)322        #expect(try UTXOAccount(master: master, network: .dogecoin).purpose == .bip44)323        #expect(try UTXOAccount(master: master, network: .bitcoinCash).purpose == .bip44)324        #expect(try BIP84Account(master: master, network: .mainnet).purpose == .bip84)325        #expect(try UTXOAccount(master: master, network: .dogecoin).scriptType == .p2pkh)326        for n in [BitcoinNetwork.dogecoin, .dogecoinTestnet, .bitcoinCash, .bitcoinCashTestnet] {327            #expect(throws: BitcoinAccountError.purposeNotSupported) { try UTXOAccount(master: master, network: n, purpose: .bip84) }328        }329        // first addresses, as wallets of each coin show them330        #expect(try UTXOAccount(master: master, network: .dogecoin).address(chain: .receive, index: 0).string == "DBus3bamQjgJULBJtYXpEzDWQRwF5iwxgC")331        #expect(try UTXOAccount(master: master, network: .litecoin).address(chain: .receive, index: 0).string == "ltc1qjmxnz78nmc8nq77wuxh25n2es7rzm5c2rkk4wh")332        #expect(try UTXOAccount(master: master, network: .bitcoinCash).address(chain: .receive, index: 0).string == "bitcoincash:qqyx49mu0kkn9ftfj6hje6g2wfer34yfnq5tahq3q6")333    }334335    @Test func watchOnlyAccountsAndExtendedKeys() throws {336        let master = try abandonMaster()337        for n in [BitcoinNetwork.dogecoin, .dogecoinTestnet, .bitcoinCash, .bitcoinCashTestnet, .litecoin, .litecoinTestnet] {338            let full = try UTXOAccount(master: master, network: n)339            let plain = full.extendedPublicKey(slip132: false)340            #expect(plain.hasPrefix(n.isTest ? "tpub" : "xpub"))341            // a BIP-44 account has no SLIP-132 form342            let displayed = full.extendedPublicKey()343            #expect(displayed.hasPrefix(full.purpose == .bip84 ? (n.isTest ? "vpub" : "zpub") : (n.isTest ? "tpub" : "xpub")))344            let watch = try UTXOAccount(extendedKey: plain, network: n)345            #expect(watch.isWatchOnly && watch.purpose == full.purpose)346            #expect(try watch.address(chain: .receive, index: 7) == full.address(chain: .receive, index: 7))347            #expect(try watch.address(chain: .change, index: 2) == full.address(chain: .change, index: 2))348            #expect(throws: BitcoinAccountError.networkMismatch) { try UTXOAccount(extendedKey: plain, network: n.isTest ? n.mainCounterpart : n.testCounterpart) }349            var tx = BitcoinTransaction(inputs: [], outputs: [])350            #expect(throws: BitcoinAccountError.watchOnly) { try watch.sign(transaction: &tx, spending: []) }351        }352        // a zpub announces BIP-84: refused where the account is BIP-44353        let zpub = try BIP84Account(master: master, network: .mainnet).extendedPublicKey()354        #expect(throws: BitcoinAccountError.purposeNotSupported) { try UTXOAccount(extendedKey: zpub, network: .dogecoin) }355        #expect(throws: BitcoinAccountError.purposeNotSupported) { try UTXOAccount(extendedKey: zpub, network: .mainnet, purpose: .bip44) }356        #expect(try UTXOAccount(extendedKey: zpub, network: .litecoin).purpose == .bip84)357    }358359    @Test func gapLimitLocateAndDescriptors() throws {360        let account = try UTXOAccount(master: try abandonMaster(), network: .dogecoin)361        // discovery over P2PKH scripts362        let used: Set<Bytes> = [try account.scriptPubKey(chain: .receive, index: 0), try account.scriptPubKey(chain: .receive, index: 19),363                                try account.scriptPubKey(chain: .receive, index: 25)]364        let found = try account.discover(chain: .receive, usedScripts: used)365        #expect(found.used == [0, 19, 25] && found.nextUnused == 26)366        #expect(account.scanRange(used: found.used) == 0..<46)367        #expect(throws: BitcoinAccountError.gapLimitReached) { try account.nextUnusedAddress(chain: .receive, used: [], skipping: 20) }368        // lookup: only P2PKH scripts of the account369        let located = try #require(account.locate(scriptPubKey: try account.scriptPubKey(chain: .change, index: 3)))370        #expect(located.chain == .change && located.index == 3)371        let key = try account.publicKey(chain: .receive, index: 0)372        #expect(account.locate(scriptPubKey: try BitcoinScript.p2wpkh(publicKey: key)) == nil)373        #expect(try account.scriptIndex(receiveCount: 30, changeCount: 5).count == 35)374375        // descriptors: pkh() with the origin m/44'/3'/0', readable back376        let d = try account.descriptors()377        let fingerprint = try #require(account.masterFingerprint).hex378        #expect(d.receive.kind == .pkh)379        #expect(d.receive.body.hasPrefix("pkh([\(fingerprint)/44h/3h/0h]xpub") || d.receive.body.hasPrefix("pkh([\(fingerprint)/44'/3'/0']xpub"))380        #expect(try d.receive.address(index: 5, network: .dogecoin) == account.address(chain: .receive, index: 5))381        #expect(try d.change.address(index: 2, network: .dogecoin) == account.address(chain: .change, index: 2))382        #expect(try d.combined.singlePath(1).scriptPubKey(index: 2) == account.scriptPubKey(chain: .change, index: 2))383        let reparsed = try OutputDescriptor(parsing: d.receive.string)384        #expect(reparsed == d.receive)385        // Litecoin keeps wpkh()386        #expect(try UTXOAccount(master: try abandonMaster(), network: .litecoin).descriptors().receive.kind == .wpkh)387        // no P2WSH multisig wallet where SegWit does not exist388        let wsh = "wsh(sortedmulti(1,02cc6b0dc33aabcf3a23643e5e2919a80c50fb3dd2129ce409bbc5f0d4643d05e0,030fe9d8d0e15d432d1ae9b3c52f4cb6e37e3c7a41af0139783da09eab85a182dc))"389        #expect(throws: BitcoinAccountError.unsupportedDescriptor) { try MultisigAccount(descriptor: wsh, network: .dogecoin) }390        #expect(throws: BitcoinAccountError.unsupportedDescriptor) { try MultisigAccount(descriptor: wsh, network: .bitcoinCash) }391        #expect((try? MultisigAccount(descriptor: wsh, network: .litecoin)) != nil)392    }393}394395// MARK: - Signatures against reference implementations396397@Suite struct UTXOSignatureTests {398    struct Loaded {399        let network: BitcoinNetwork400        let account: UTXOAccount401        let reference: BitcoinTransaction402        let unsigned: BitcoinTransaction403        let utxos: [BitcoinUTXO]404        let previous: [String: BitcoinTransaction]405    }406407    func load(_ v: UTXOReferenceVectors.Signed) throws -> Loaded {408        let n = try network(v.network)409        let account = try UTXOAccount(master: try abandonMaster(), network: n)410        let reference = try BitcoinTransaction(hex: v.raw)411        #expect(reference.hex == v.raw)412        if !v.txid.isEmpty { #expect(reference.txid == v.txid) }413        #expect(reference.version == v.version && reference.lockTime == v.lockTime)414        #expect(reference.inputs.allSatisfy { $0.sequence == v.sequence })415        #expect(reference.outputs.count == v.outputs.count)416        for (o, expected) in zip(reference.outputs, v.outputs) {417            #expect(try BitcoinAddress(expected.address, network: n).scriptPubKey == o.scriptPubKey)418            #expect(o.value == expected.value)419        }420        var utxos = [BitcoinUTXO]()421        var previous = [String: BitcoinTransaction]()422        for (k, i) in v.inputs.enumerated() {423            let outPoint = try #require(BitcoinOutPoint(txid: i.txid, vout: i.vout))424            #expect(reference.inputs[k].previousOutput == outPoint)425            let chain = try #require(i.chain.flatMap { UTXOAccount.Chain(rawValue: $0) }), index = try #require(i.index)426            // the key of the reference tool is the key of our account at the same path427            #expect(try account.scriptPubKey(chain: chain, index: index) == unhex(i.script))428            utxos.append(BitcoinUTXO(outPoint: outPoint, value: i.value, scriptPubKey: unhex(i.script), confirmations: 6,429                                     derivation: .init(chain: chain.rawValue, index: index)))430            if let raw = i.previousTransaction {431                let t = try BitcoinTransaction(hex: raw)432                #expect(t.txid == i.txid)433                previous[i.txid] = t434            }435        }436        var unsigned = reference437        for k in unsigned.inputs.indices {438            unsigned.inputs[k].scriptSig = []439            unsigned.inputs[k].witness = []440        }441        return Loaded(network: n, account: account, reference: reference, unsigned: unsigned, utxos: utxos, previous: previous)442    }443444    /// Dogecoin P2PKH, original signature hash: the transaction signed by bitcoinjs-lib is reproduced byte for byte.445    @Test func dogecoinLegacySignatureMatchesBitcoinJS() throws {446        let v = UTXOReferenceVectors.dogecoinP2PKH447        let l = try load(v)448        let outputs = l.utxos.map(\.output)449        try BitcoinVerifier.verify(transaction: l.reference, spentOutputs: outputs, scheme: .legacy)450        var ours = l.unsigned451        try l.account.sign(transaction: &ours, spending: l.utxos, previousTransactions: l.previous)452        #expect(ours.hex == v.raw)453        #expect(ours.txid == v.txid)454        #expect(!ours.hasWitness && ours.vsize == ours.serialized().count)455456        // the digest does not commit to the amounts: without the previous transactions nothing is signed457        var refused = l.unsigned458        #expect(throws: BitcoinAccountError.unauthenticatedInput(index: 0)) { try l.account.sign(transaction: &refused, spending: l.utxos) }459        #expect(throws: BitcoinAccountError.unauthenticatedInput(index: 1)) {460            try l.account.sign(transaction: &refused, spending: l.utxos, previousTransactions: [v.inputs[0].txid: try #require(l.previous[v.inputs[0].txid])])461        }462        #expect(refused == l.unsigned)463        // an indexer understating a coin (the difference would become fee) is caught by the previous transaction464        var lying = l.utxos465        lying[1] = BitcoinUTXO(outPoint: lying[1].outPoint, value: lying[1].value - 1_000_000_000, scriptPubKey: lying[1].scriptPubKey, confirmations: 6,466                               derivation: lying[1].derivation)467        #expect(throws: BitcoinAccountError.unauthenticatedInput(index: 1)) {468            try l.account.sign(transaction: &refused, spending: lying, previousTransactions: l.previous)469        }470        // and indeed the signature itself would not have caught it471        #expect(BitcoinVerifier.isValid(transaction: l.reference, spentOutputs: lying.map(\.output), scheme: .legacy))472473        // under Bitcoin Cash's rules the same signatures are invalid (no fork id), and a changed output breaks them474        #expect(!BitcoinVerifier.isValid(transaction: l.reference, spentOutputs: outputs, scheme: .bip143ForkID))475        var tampered = l.reference476        tampered.outputs[0].value += 1477        #expect(!BitcoinVerifier.isValid(transaction: tampered, spentOutputs: outputs, scheme: .legacy))478        #expect(l.reference.inputs.allSatisfy { $0.scriptSig[Int($0.scriptSig[0])] == 0x01 })479    }480481    /// The BIP-174 route for Dogecoin: the PSBT created by bitcoinjs-lib (non_witness_utxo) signed by our account.482    @Test func dogecoinPSBTFromBitcoinJS() throws {483        let v = UTXOReferenceVectors.dogecoinP2PKH484        let l = try load(v)485        var psbt = try PSBT(base64: try #require(v.unsignedPSBT))486        #expect(psbt.inputs.allSatisfy { $0.nonWitnessUTXO != nil && $0.witnessUTXO == nil })487        #expect(try l.account.sign(psbt: &psbt) == 2)488        #expect(psbt.sighashScheme == .legacy)489        try psbt.finalize()490        #expect(try psbt.extractTransaction().hex == v.raw)491492        // without the previous transaction a P2PKH input cannot be signed493        var stripped = try PSBT(base64: try #require(v.unsignedPSBT))494        stripped.inputs[0].witnessUTXO = l.utxos[0].output495        stripped.inputs[0].nonWitnessUTXO = nil496        // (the account refuses before looking at any input: QYV-SVC-064; the per-input signer gives its own reason)497        #expect(throws: PSBTError.nonWitnessUTXORequired) { try l.account.sign(psbt: &stripped) }498        stripped.prepare(for: .dogecoin)499        #expect(throws: PSBTError.witnessUTXOForNonWitnessInput) { try stripped.sign(inputIndex: 0, privateKey: try l.account.privateKey(chain: .receive, index: 0)) }500        // a fork-id hash type has no meaning on Dogecoin501        var declared = try PSBT(base64: try #require(v.unsignedPSBT))502        try declared.setSighashType(.allForkID, inputIndex: 0)503        #expect(throws: PSBTError.sighashTypeNotAllowed) { try l.account.sign(psbt: &declared) }504        // the plan → PSBT route refuses to produce an unsignable PSBT505        let plan = try BitcoinTransactionBuilder.build(BitcoinSpendRequest(506            network: .dogecoin, recipients: [BitcoinTransaction.Output(value: 1_000_000_000, scriptPubKey: l.reference.outputs[0].scriptPubKey)],507            utxos: l.utxos, feeRate: .minimum(for: .dogecoin), changeScript: try l.account.scriptPubKey(chain: .change, index: 0)))508        #expect(throws: PSBTError.nonWitnessUTXORequired) { try l.account.psbt(for: plan) }509        var viaPSBT = try l.account.psbt(for: plan, previousTransactions: l.previous)510        #expect(viaPSBT.inputs.allSatisfy { $0.nonWitnessUTXO != nil })511        #expect(try l.account.sign(psbt: &viaPSBT) == plan.inputs.count)512        try viaPSBT.finalize()513        #expect(try viaPSBT.extractTransaction() == l.account.sign(plan: plan, previousTransactions: l.previous))514    }515516    /// Litecoin P2WPKH (BIP-143): byte for byte against bitcoinjs-lib, directly and through its PSBT.517    @Test func litecoinSegwitSignatureMatchesBitcoinJS() throws {518        let v = UTXOReferenceVectors.litecoinP2WPKH519        let l = try load(v)520        let outputs = l.utxos.map(\.output)521        try BitcoinVerifier.verify(transaction: l.reference, spentOutputs: outputs, scheme: .bip143)522        var ours = l.unsigned523        try l.account.sign(transaction: &ours, spending: l.utxos)524        #expect(ours.hex == v.raw && ours.txid == v.txid && ours.hasWitness)525526        var psbt = try PSBT(base64: try #require(v.unsignedPSBT))527        #expect(try l.account.sign(psbt: &psbt) == 2)528        try psbt.finalize()529        #expect(try psbt.extractTransaction().hex == v.raw)530531        // BIP-143 commits to the amounts: a wrong one invalidates the signature532        var wrong = outputs533        wrong[0].value -= 1534        #expect(!BitcoinVerifier.isValid(transaction: l.reference, spentOutputs: wrong, scheme: .bip143))535        // witness programs mean nothing under the other schemes536        #expect(throws: BitcoinVerifier.Error.unsupportedScript) { try BitcoinVerifier.verify(transaction: l.reference, spentOutputs: outputs, scheme: .legacy) }537        #expect(throws: BitcoinVerifier.Error.unsupportedScript) { try BitcoinVerifier.verify(transaction: l.reference, spentOutputs: outputs, scheme: .bip143ForkID) }538    }539540    /// Bitcoin Cash P2PKH, fork-id digest: the transaction signed by bitcash is reproduced byte for byte.541    @Test func bitcoinCashForkIDSignatureMatchesBitcash() throws {542        let v = UTXOReferenceVectors.bitcoinCashP2PKH543        let l = try load(v)544        let outputs = l.utxos.map(\.output)545        try BitcoinVerifier.verify(transaction: l.reference, spentOutputs: outputs, scheme: .bip143ForkID)546        var ours = l.unsigned547        // no previous transaction needed: the digest commits to the amounts548        try l.account.sign(transaction: &ours, spending: l.utxos)549        #expect(ours.hex == v.raw)550        // signature byte 0x41 = SIGHASH_ALL | SIGHASH_FORKID551        for input in ours.inputs {552            let signatureLength = Int(input.scriptSig[0])553            #expect(input.scriptSig[signatureLength] == 0x41)554        }555        // replay protection, both ways: these signatures are invalid under Bitcoin's and Dogecoin's rules556        #expect(!BitcoinVerifier.isValid(transaction: l.reference, spentOutputs: outputs, scheme: .legacy))557        #expect(!BitcoinVerifier.isValid(transaction: l.reference, spentOutputs: outputs, scheme: .bip143))558        // the amount is committed559        var wrong = outputs560        wrong[1].value += 1561        #expect(throws: BitcoinVerifier.Error.invalidSignature) { try BitcoinVerifier.verify(transaction: l.reference, spentOutputs: wrong, scheme: .bip143ForkID) }562        var tampered = l.reference563        tampered.outputs[1].value += 1564        #expect(!BitcoinVerifier.isValid(transaction: tampered, spentOutputs: outputs, scheme: .bip143ForkID))565566        // digest level: the fork-id digest is the BIP-143 preimage with hash type 0x41567        let digest = try BitcoinSighash.forkID(transaction: l.unsigned, inputIndex: 0, scriptCode: outputs[0].scriptPubKey, value: outputs[0].value)568        let preimage = try BitcoinSighash.segwitV0Preimage(transaction: l.unsigned, inputIndex: 0, scriptCode: outputs[0].scriptPubKey, value: outputs[0].value,569                                                           type: .allForkID)570        #expect(digest == SHA256.double(preimage))571        #expect(Bytes(preimage.suffix(4)) == [0x41, 0, 0, 0])572        #expect(throws: BitcoinSighash.Error.sighashTypeMismatch) {573            try BitcoinSighash.forkID(transaction: l.unsigned, inputIndex: 0, scriptCode: outputs[0].scriptPubKey, value: 1, type: .all)574        }575        // a signature made the Bitcoin way (no fork id) for the same input is refused on Bitcoin Cash576        var legacySigned = l.unsigned577        var key = try l.account.privateKey(chain: .receive, index: 0)578        defer { SecureMemory.zero(&key) }579        for k in legacySigned.inputs.indices {580            try BitcoinSigner.signP2PKH(transaction: &legacySigned, inputIndex: k, privateKey: key, value: outputs[k].value,581                                        spentScriptPubKey: outputs[k].scriptPubKey, scheme: .legacy)582        }583        #expect(BitcoinVerifier.isValid(transaction: legacySigned, spentOutputs: outputs, scheme: .legacy))584        #expect(!BitcoinVerifier.isValid(transaction: legacySigned, spentOutputs: outputs, scheme: .bip143ForkID))585    }586587    /// The BIP-174 route for Bitcoin Cash: plan → PSBT with previous transactions → serialized → signed → extracted.588    @Test func bitcoinCashPSBTRoundTrip() throws {589        let account = try UTXOAccount(master: try abandonMaster(), network: .bitcoinCash)590        let a = try coin(account, index: 0, value: 400_000, salt: 0x31), b = try coin(account, chain: .change, index: 4, value: 90_000, salt: 0x32)591        let previous = [a.utxo.outPoint.txid: a.previous, b.utxo.outPoint.txid: b.previous]592        let destination = try BitcoinAddress("bitcoincash:qpm2qsznhks23z7629mms6s4cwef74vcwvy22gdx6a", network: .bitcoinCash)593        var request = BitcoinSpendRequest(network: .bitcoinCash, recipients: [BitcoinTransaction.Output(value: 450_000, scriptPubKey: destination.scriptPubKey)],594                                          utxos: [a.utxo, b.utxo], feeRate: FeeRate(satPerVByte: 2), changeScript: try account.scriptPubKey(chain: .change, index: 5))595        request.seed = 7596        let plan = try BitcoinTransactionBuilder.build(request)597        #expect(plan.inputs.count == 2 && plan.network == .bitcoinCash)598        let direct = try account.sign(plan: plan)599600        #expect(throws: PSBTError.nonWitnessUTXORequired) { try account.psbt(for: plan) }601        let created = try account.psbt(for: plan, previousTransactions: previous)602        #expect(created.sighashScheme == .bip143ForkID)603        // across the air gap only the BIP-174 bytes travel: the scheme is set again by the signer's account604        var received = try PSBT(parsing: created.serialized())605        #expect(received.sighashScheme == .bip143)606        #expect(received.fee == plan.fee)607        #expect(try account.sign(psbt: &received) == 2)608        #expect(received.inputs.allSatisfy { $0.partialSignatures.allSatisfy { $0.signature.last == 0x41 } })609        try received.finalize()610        let extracted = try received.extractTransaction()611        #expect(extracted == direct)612        try BitcoinVerifier.verify(transaction: extracted, spentOutputs: plan.inputs.map(\.output), scheme: .bip143ForkID)613614        // PSBT_IN_SIGHASH_TYPE: 0x41 is the only declaration accepted on Bitcoin Cash615        var declared = try PSBT(parsing: created.serialized())616        try declared.setSighashType(.allForkID, inputIndex: 0)617        #expect(try account.sign(psbt: &declared) == 2)618        var bitcoinStyle = try PSBT(parsing: created.serialized())619        try bitcoinStyle.setSighashType(.all, inputIndex: 0)620        #expect(throws: PSBTError.sighashTypeNotAllowed) { try account.sign(psbt: &bitcoinStyle) }621        // a previous transaction that is not the one spent is refused when the PSBT is created622        #expect(throws: PSBTError.nonWitnessUTXOMismatch) {623            try account.psbt(for: plan, previousTransactions: [a.utxo.outPoint.txid: b.previous, b.utxo.outPoint.txid: b.previous])624        }625        // a plan of another network is not signed626        let dogecoin = try UTXOAccount(master: try abandonMaster(), network: .dogecoin)627        #expect(throws: BitcoinAccountError.networkMismatch) { try dogecoin.sign(plan: plan) }628    }629630    /// Bitcoin Cash Node's signature hash vectors: the fork-id algorithm (amount 0, any hash type) and the original one.631    @Test func bitcoinCashNodeSighashVectors() throws {632        var fork = 0, plain = 0633        for c in BCHNSighashVectors.cases {634            let tx = try BitcoinTransaction(hex: c.transaction, allowWitness: false)635            let script = unhex(c.script)636            let type = BitcoinSighashType(rawValue: UInt32(bitPattern: c.hashType))637            let original = try BitcoinSighash.legacy(transaction: tx, inputIndex: c.inputIndex, scriptCode: script, type: type)638            #expect(Bytes(original.reversed()).hex == c.withoutForkFlag, "legacy, hash type \(c.hashType)")639            if type.hasForkID {640                let preimage = try BitcoinSighash.segwitV0Preimage(transaction: tx, inputIndex: c.inputIndex, scriptCode: script, value: 0, type: type)641                #expect(Bytes(SHA256.double(preimage).reversed()).hex == c.withForkFlag, "fork id, hash type \(c.hashType)")642                fork += 1643            } else {644                #expect(c.withForkFlag == c.withoutForkFlag)645                plain += 1646            }647        }648        #expect(fork == 60 && plain == 60)649    }650}651652// MARK: - Real transactions653654@Suite struct UTXORealTransactionTests {655    /// Public mainnet transactions of each coin: strict parsing, txid, fee, and every signature under the coin's scheme.656    @Test func mainnetTransactionsParseAndVerify() throws {657        #expect(UTXOReferenceVectors.real.count == 4)658        var verifiedInputs = 0659        for r in UTXOReferenceVectors.real {660            let n = try network(r.network)661            let tx = try BitcoinTransaction(hex: r.raw)662            #expect(tx.txid == r.txid, "\(r.name)")663            #expect(tx.hex == r.raw)664            #expect(try BitcoinTransaction(parsing: tx.serialized()) == tx)665            try tx.checkSanity(maximumMoney: n.maximumMoney)666            #expect(tx.inputs.count == r.inputs.count)667            var spent = [BitcoinTransaction.Output]()668            var total: UInt64 = 0669            for (k, i) in r.inputs.enumerated() {670                // the previous transaction is authenticated by its hash, then gives the amount and the script671                let previous = try BitcoinTransaction(hex: try #require(i.previousTransaction))672                #expect(previous.txid == i.txid)673                #expect(tx.inputs[k].previousOutput == BitcoinOutPoint(txid: i.txid, vout: i.vout))674                let output = previous.outputs[Int(i.vout)]675                #expect(output.value == i.value && output.scriptPubKey == unhex(i.script))676                let utxo = BitcoinUTXO(outPoint: tx.inputs[k].previousOutput, value: i.value, scriptPubKey: output.scriptPubKey, confirmations: 1)677                #expect(utxo.isAuthenticated(by: previous))678                #expect(!utxo.isAuthenticated(by: tx))679                spent.append(output)680                total += output.value681            }682            #expect(total - (try #require(tx.outputValue(maximumMoney: n.maximumMoney))) == r.fee, "\(r.name)")683            try BitcoinVerifier.verify(transaction: tx, spentOutputs: spent, scheme: n.sighashScheme)684            verifiedInputs += tx.inputs.count685            // any other scheme rejects them, and so does a changed output686            for other in UTXOSighashScheme.allCases where other != n.sighashScheme {687                let segwitInput = BitcoinScript.witnessProgram(of: spent[0].scriptPubKey) != nil688                // (a legacy input of Litecoin is the same under .bip143 and .legacy)689                if !segwitInput, Set([other, n.sighashScheme]) == [.bip143, .legacy] { continue }690                #expect(!BitcoinVerifier.isValid(transaction: tx, spentOutputs: spent, scheme: other), "\(r.name) under \(other)")691            }692            var tampered = tx693            tampered.outputs[0].value ^= 1694            #expect(!BitcoinVerifier.isValid(transaction: tampered, spentOutputs: spent, scheme: n.sighashScheme))695            // every output has an address on its own network696            for o in tx.outputs where !BitcoinScript.isUnspendable(o.scriptPubKey) {697                let address = try BitcoinAddress(scriptPubKey: o.scriptPubKey, network: n)698                #expect(try BitcoinAddress(address.string, network: n).scriptPubKey == o.scriptPubKey)699            }700        }701        #expect(verifiedInputs == 4)702        // the Dogecoin one pays about 0.01 DOGE per kilobyte, the recommended rate703        let doge = try #require(UTXOReferenceVectors.real.first { $0.network == "dogecoin" })704        #expect(doge.fee * 1000 / UInt64(doge.raw.utf8.count / 2) >= 1_000_000)705    }706707    @Test func truncatedAndPaddedTransactionsAreRefused() throws {708        for r in UTXOReferenceVectors.real {709            let bytes = unhex(r.raw)710            for cut in [1, 4, 5, bytes.count / 2, bytes.count - 1] {711                #expect(throws: (any Error).self) { try BitcoinTransaction(parsing: Bytes(bytes.prefix(cut))) }712            }713            #expect(throws: (any Error).self) { try BitcoinTransaction(parsing: bytes + [0]) }714        }715    }716}717718// MARK: - Fees, dust, sizes, coin selection719720@Suite struct UTXOFeeAndBuilderTests {721    @Test func dustThresholdsPerCoin() throws {722        let h20 = Bytes(repeating: 1, count: 20), h32 = Bytes(repeating: 1, count: 32)723        let p2pkh = try BitcoinScript.p2pkh(publicKeyHash: h20), p2sh = try BitcoinScript.p2sh(scriptHash: h20)724        let p2wpkh = try BitcoinScript.p2wpkh(publicKeyHash: h20), p2wsh = try BitcoinScript.p2wsh(scriptHash: h32)725        let data = try BitcoinScript.nullData([1, 2, 3])726        // Bitcoin: unchanged727        #expect(BitcoinSizeEstimator.dustThreshold(scriptPubKey: p2wpkh, network: .mainnet) == 294)728        #expect(BitcoinSizeEstimator.dustThreshold(scriptPubKey: p2pkh, network: .mainnet) == 546)729        #expect(BitcoinSizeEstimator.dustThreshold(scriptPubKey: p2sh, network: .signet) == 540)730        #expect(BitcoinSizeEstimator.dustThreshold(scriptPubKey: p2wsh, network: .testnet) == 330)731        for script in [p2pkh, p2sh, p2wpkh, p2wsh] {732            #expect(BitcoinSizeEstimator.dustThreshold(scriptPubKey: script, network: .mainnet) == BitcoinSizeEstimator.dustThreshold(scriptPubKey: script))733        }734        // Litecoin: ten times Bitcoin's dust relay fee735        #expect(BitcoinSizeEstimator.dustThreshold(scriptPubKey: p2wpkh, network: .litecoin) == 2_940)736        #expect(BitcoinSizeEstimator.dustThreshold(scriptPubKey: p2pkh, network: .litecoin) == 5_460)737        #expect(BitcoinSizeEstimator.dustThreshold(scriptPubKey: p2sh, network: .litecoinTestnet) == 5_400)738        #expect(BitcoinSizeEstimator.dustThreshold(scriptPubKey: p2wsh, network: .litecoin) == 3_300)739        // Dogecoin: 0.01 DOGE whatever the script; Bitcoin Cash: 546 sat740        for script in [p2pkh, p2sh] {741            #expect(BitcoinSizeEstimator.dustThreshold(scriptPubKey: script, network: .dogecoin) == 1_000_000)742            #expect(BitcoinSizeEstimator.dustThreshold(scriptPubKey: script, network: .dogecoinTestnet) == 1_000_000)743            #expect(BitcoinSizeEstimator.dustThreshold(scriptPubKey: script, network: .bitcoinCash) == 546)744            #expect(BitcoinSizeEstimator.dustThreshold(scriptPubKey: script, network: .bitcoinCashTestnet) == 546)745        }746        for n in BitcoinNetwork.allCases { #expect(BitcoinSizeEstimator.dustThreshold(scriptPubKey: data, network: n) == 0) }747        #expect(BitcoinSizeEstimator.isDust(BitcoinTransaction.Output(value: 999_999, scriptPubKey: p2pkh), network: .dogecoin))748        #expect(!BitcoinSizeEstimator.isDust(BitcoinTransaction.Output(value: 1_000_000, scriptPubKey: p2pkh), network: .dogecoin))749        #expect(BitcoinSizeEstimator.isDust(BitcoinTransaction.Output(value: 545, scriptPubKey: p2pkh), network: .bitcoinCash))750        #expect(!BitcoinSizeEstimator.isDust(BitcoinTransaction.Output(value: 546, scriptPubKey: p2pkh), network: .bitcoinCash))751    }752753    @Test func feeRatesPerCoin() throws {754        #expect(FeeRate.minimum(for: .mainnet) == .minimumRelay)755        #expect(FeeRate.minimum(for: .litecoin) == FeeRate(satPerVByte: 1))756        #expect(FeeRate.minimum(for: .bitcoinCash) == FeeRate(satPerVByte: 1))757        // 0.01 DOGE per 1000 bytes: a 226-byte transaction pays 226 000 koinu, and the fee follows the exact size758        let doge = FeeRate.minimum(for: .dogecoin)759        #expect(doge == FeeRate(satPerKiloVByte: 1_000_000))760        #expect(doge.fee(vsize: 226) == 226_000 && doge.fee(vsize: 192) == 192_000)761        #expect(FeeRate.maximum(for: .dogecoin).fee(vsize: 1000) == 100_000_000)762        #expect(FeeRate.maximum(for: .bitcoinCash) == FeeRate(satPerVByte: 1_000))763        // node estimates come in coins per kB764        #expect(FeeRate.fromEstimate(coinsPerKiloByte: 0.00001) == FeeRate(satPerVByte: 1))765        #expect(FeeRate.fromEstimate(coinsPerKiloByte: 0.01) == FeeRate(satPerKiloVByte: 1_000_000))766        #expect(FeeRate.fromEstimate(coinsPerKiloByte: 0.50729503) == FeeRate(satPerKiloVByte: 50_729_503))767        #expect(FeeRate.fromEstimate(coinsPerKiloByte: 0.000009971) == FeeRate(satPerKiloVByte: 998))768        for bad in [0, -1, Double.nan, Double.infinity, 1_000.5, 1e300] { #expect(FeeRate.fromEstimate(coinsPerKiloByte: bad) == nil) }769        // an inflated estimate is brought back inside the network's bounds, a low one up to the floor770        #expect(FeeRate(satPerKiloVByte: 50_729_503).clamped(to: .dogecoin) == FeeRate(satPerKiloVByte: 50_729_503))771        #expect(FeeRate(satPerKiloVByte: 500_000_000).clamped(to: .dogecoin) == .maximum(for: .dogecoin))772        #expect(FeeRate(satPerKiloVByte: 998).clamped(to: .litecoin) == FeeRate(satPerVByte: 1))773        #expect(FeeRate(satPerKiloVByte: 10).clamped(to: .dogecoin) == doge)774    }775776    @Test func sizesWithoutSegWit() throws {777        let p2pkh = try BitcoinScript.p2pkh(publicKeyHash: Bytes(repeating: 1, count: 20))778        // 148 bytes for a P2PKH input (72-byte signature), 34 for its output, 10 of overhead779        #expect(BitcoinSizeEstimator.inputWeight(scriptPubKey: p2pkh, inWitnessTransaction: false) == 148 * 4)780        #expect(BitcoinSizeEstimator.inputWeight(scriptPubKey: p2pkh) == 148 * 4 + 1)781        let weight = BitcoinSizeEstimator.transactionWeight(inputWeights: [148 * 4], outputScripts: [p2pkh, p2pkh], hasWitness: false)782        #expect(weight == (10 + 148 + 34 + 34) * 4)783        #expect(BitcoinSizeEstimator.transactionWeight(inputWeights: [148 * 4], outputScripts: [p2pkh, p2pkh]) == weight + 2)784    }785786    /// What the builder guarantees on each network, over many random wallets: the plan balances, respects the fee787    /// floor and the dust rule of the coin, never under-pays for its real size, and its signed form is valid.788    @Test func coinSelectionPropertiesOnEveryNetwork() throws {789        let master = try abandonMaster()790        var rng = LCG(state: 20261205)791        var built = 0, refused = 0792        for n in BitcoinNetwork.allCases {793            let account = try UTXOAccount(master: master, network: n)794            let policy = n.feePolicy795            let floor = FeeRate.minimum(for: n)796            let dust = BitcoinSizeEstimator.dustThreshold(scriptPubKey: try account.scriptPubKey(chain: .receive, index: 0), network: n)797            for trial in 0..<24 {798                let count = 1 + Int(rng.below(9))799                var utxos = [BitcoinUTXO]()800                var previous = [String: BitcoinTransaction]()801                for k in 0..<count {802                    let value = dust * (2 + rng.below(4_000)) + rng.below(dust)803                    let c = try coin(account, chain: rng.below(2) == 0 ? .receive : .change, index: UInt32(rng.below(8)), value: value,804                                     salt: UInt8(truncatingIfNeeded: trial * 16 + k + 1))805                    guard previous[c.utxo.outPoint.txid] == nil else { continue }806                    utxos.append(c.utxo)807                    previous[c.utxo.outPoint.txid] = c.previous808                }809                let total = utxos.reduce(UInt64(0)) { $0 + $1.value }810                let amount = max(dust, total / (2 + rng.below(6)))811                let rate = FeeRate(milliSatPerVByte: floor.milliSatPerVByte * (1 + rng.below(5)))812                let destination = try account.scriptPubKey(chain: .receive, index: 30 + UInt32(rng.below(5)))813                let sendMax = trial % 6 == 5814                var request = BitcoinSpendRequest(network: n, recipients: sendMax ? [] : [BitcoinTransaction.Output(value: amount, scriptPubKey: destination)],815                                                  utxos: utxos, feeRate: rate, changeScript: try account.scriptPubKey(chain: .change, index: 9),816                                                  sendMaxScript: sendMax ? destination : nil)817                request.seed = rng.next()818                request.currentHeight = 1_000_000819                let plan: BitcoinTransactionPlan820                do { plan = try BitcoinTransactionBuilder.build(request) } catch is BitcoinBuildError {821                    refused += 1822                    continue823                }824                built += 1825                let tx = plan.transaction826                // balance and fee827                let outputTotal = try #require(tx.outputValue(maximumMoney: n.maximumMoney))828                #expect(plan.inputValue == outputTotal + plan.fee)829                #expect(plan.network == n)830                #expect(plan.fee >= rate.fee(vsize: plan.estimatedVSize))831                #expect(plan.fee <= request.maximumFee)832                // dust: no output below the coin's threshold833                for o in tx.outputs { #expect(!BitcoinSizeEstimator.isDust(o, rule: policy.dust), "\(n) output \(o.value)") }834                // no witness program on a chain without SegWit; replacement signalled only where it exists835                if !n.supportsSegWit { #expect(tx.outputs.allSatisfy { BitcoinScript.witnessProgram(of: $0.scriptPubKey) == nil }) }836                #expect(tx.signalsRBF == n.supportsRBF)837                #expect(tx.inputs.allSatisfy { $0.sequence == (n.supportsRBF ? BitcoinTransaction.Input.sequenceRBF : BitcoinTransaction.Input.sequenceLockTimeOnly) })838                if sendMax { #expect(plan.inputs.count == utxos.count && plan.changeIndex == nil) }839                // signed: valid under the coin's scheme, and never larger than what the fee was computed for840                let signed = try account.sign(plan: plan, previousTransactions: previous)841                try BitcoinVerifier.verify(transaction: signed, spentOutputs: plan.inputs.map(\.output), scheme: n.sighashScheme)842                #expect(signed.vsize <= plan.estimatedVSize)843                #expect(plan.estimatedVSize - signed.vsize <= 2 * plan.inputs.count + 1)844                #expect(signed.hasWitness == n.supportsSegWit)845                #expect(plan.fee * 1000 >= floor.milliSatPerVByte * UInt64(signed.vsize))846                // the same request gives the same transaction847                #expect(try BitcoinTransactionBuilder.build(request) == plan)848            }849        }850        #expect(built >= 150, "built \(built), refused \(refused)")851    }852853    @Test func networkRulesAreEnforcedByTheBuilder() throws {854        let master = try abandonMaster()855        let doge = try UTXOAccount(master: master, network: .dogecoin)856        let c = try coin(doge, index: 0, value: 50_000_000_000, salt: 0x41)857        let to = try doge.scriptPubKey(chain: .receive, index: 1), change = try doge.scriptPubKey(chain: .change, index: 0)858        func request(_ value: UInt64, rate: FeeRate = .minimum(for: .dogecoin), to script: Bytes? = nil) -> BitcoinSpendRequest {859            var r = BitcoinSpendRequest(network: .dogecoin, recipients: [BitcoinTransaction.Output(value: value, scriptPubKey: script ?? to)], utxos: [c.utxo],860                                        feeRate: rate, changeScript: change)861            r.seed = 1862            return r863        }864        // fee floor: 0.01 DOGE/kB, not Bitcoin's 1 sat/vB865        #expect(throws: BitcoinBuildError.feeRateOutOfRange) { try BitcoinTransactionBuilder.build(request(10_000_000_000, rate: FeeRate(satPerKiloVByte: 999_999))) }866        #expect(throws: BitcoinBuildError.feeRateOutOfRange) { try BitcoinTransactionBuilder.build(request(10_000_000_000, rate: FeeRate(satPerVByte: 1))) }867        #expect(throws: BitcoinBuildError.feeRateOutOfRange) { try BitcoinTransactionBuilder.build(request(10_000_000_000, rate: FeeRate(satPerKiloVByte: 100_000_001))) }868        let plan = try BitcoinTransactionBuilder.build(request(10_000_000_000))869        // one P2PKH input, two P2PKH outputs: 226 bytes at most, 0.00226 DOGE870        #expect(plan.estimatedVSize == 226 && plan.fee == 226_000)871        // dust: 0.01 DOGE872        #expect(throws: BitcoinBuildError.dustOutput(index: 0)) { try BitcoinTransactionBuilder.build(request(999_999)) }873        #expect((try? BitcoinTransactionBuilder.build(request(1_000_000))) != nil)874        // change below 0.01 DOGE is left to the fee rather than created875        let tight = try BitcoinTransactionBuilder.build(request(50_000_000_000 - 226_000 - 500_000))876        #expect(tight.changeIndex == nil && tight.transaction.outputs.count == 1)877        // a SegWit script would be spendable by anyone on Dogecoin878        let witness = try BitcoinScript.p2wpkh(publicKeyHash: Bytes(repeating: 3, count: 20))879        #expect(throws: BitcoinBuildError.witnessScriptNotSupported) { try BitcoinTransactionBuilder.build(request(10_000_000_000, to: witness)) }880        var witnessChange = request(10_000_000_000)881        witnessChange.changeScript = witness882        #expect(throws: BitcoinBuildError.witnessScriptNotSupported) { try BitcoinTransactionBuilder.build(witnessChange) }883        var witnessMax = BitcoinSpendRequest(network: .bitcoinCash, recipients: [], utxos: [c.utxo], feeRate: FeeRate(satPerVByte: 1), changeScript: nil, sendMaxScript: witness)884        witnessMax.seed = 1885        #expect(throws: BitcoinBuildError.witnessScriptNotSupported) { try BitcoinTransactionBuilder.build(witnessMax) }886        // a coin sitting on a witness script is not spendable there either887        let segwitCoin = BitcoinUTXO(outPoint: BitcoinOutPoint(hash: Bytes(repeating: 9, count: 32), index: 0)!, value: 50_000_000_000, scriptPubKey: witness, confirmations: 6)888        var onlySegwit = request(10_000_000_000)889        onlySegwit.utxos = [segwitCoin]890        #expect(throws: (any Error).self) { try BitcoinTransactionBuilder.build(onlySegwit) }891892        // amounts: Dogecoin's range is 10 billion DOGE per transaction, far above 21 million coins893        let whale = try coin(doge, index: 2, value: 400_000_000_00000000, salt: 0x42)894        var large = BitcoinSpendRequest(network: .dogecoin, recipients: [BitcoinTransaction.Output(value: 300_000_000_00000000, scriptPubKey: to)], utxos: [whale.utxo],895                                        feeRate: .minimum(for: .dogecoin), changeScript: change)896        large.seed = 3897        let largePlan = try BitcoinTransactionBuilder.build(large)898        #expect(largePlan.inputValue == 400_000_000_00000000)899        let signed = try doge.sign(plan: largePlan, previousTransactions: [whale.utxo.outPoint.txid: whale.previous])900        try BitcoinVerifier.verify(transaction: signed, spentOutputs: [whale.utxo.output], scheme: .legacy)901        // the same figures are outside Bitcoin's range902        var bitcoinStyle = BitcoinSpendRequest(recipients: large.recipients, utxos: large.utxos, feeRate: FeeRate(satPerVByte: 1), changeScript: change)903        bitcoinStyle.seed = 3904        #expect(throws: (any Error).self) { try BitcoinTransactionBuilder.build(bitcoinStyle) }905        // and above Dogecoin's own range nothing is built906        let absurd = BitcoinUTXO(outPoint: BitcoinOutPoint(hash: Bytes(repeating: 8, count: 32), index: 0)!, value: 2_000_000_000_000_000_000, scriptPubKey: to, confirmations: 6)907        var beyond = request(10_000_000_000)908        beyond.utxos = [absurd]909        #expect(throws: BitcoinBuildError.invalidAmount) { try BitcoinTransactionBuilder.build(beyond) }910911        // Bitcoin Cash: no replacement signal, 1 sat/byte floor, dust 546912        let cash = try UTXOAccount(master: master, network: .bitcoinCash)913        let cc = try coin(cash, index: 0, value: 1_000_000, salt: 0x43)914        var cashRequest = BitcoinSpendRequest(network: .bitcoinCash, recipients: [BitcoinTransaction.Output(value: 600, scriptPubKey: try cash.scriptPubKey(chain: .receive, index: 1))],915                                              utxos: [cc.utxo], feeRate: FeeRate(satPerVByte: 1), changeScript: try cash.scriptPubKey(chain: .change, index: 0))916        cashRequest.seed = 5917        let cashPlan = try BitcoinTransactionBuilder.build(cashRequest)918        #expect(!cashPlan.transaction.signalsRBF && cashPlan.fee == 226)919        cashRequest.recipients[0].value = 545920        #expect(throws: BitcoinBuildError.dustOutput(index: 0)) { try BitcoinTransactionBuilder.build(cashRequest) }921        cashRequest.recipients[0].value = 600922        cashRequest.feeRate = FeeRate(satPerKiloVByte: 999)923        #expect(throws: BitcoinBuildError.feeRateOutOfRange) { try BitcoinTransactionBuilder.build(cashRequest) }924925        // Litecoin: Bitcoin's builder with Litecoin's dust926        let lite = try UTXOAccount(master: master, network: .litecoin)927        let lc = try coin(lite, index: 0, value: 10_000_000, salt: 0x44)928        var liteRequest = BitcoinSpendRequest(network: .litecoin, recipients: [BitcoinTransaction.Output(value: 2_939, scriptPubKey: try lite.scriptPubKey(chain: .receive, index: 1))],929                                              utxos: [lc.utxo], feeRate: FeeRate(satPerVByte: 1), changeScript: try lite.scriptPubKey(chain: .change, index: 0))930        liteRequest.seed = 6931        #expect(throws: BitcoinBuildError.dustOutput(index: 0)) { try BitcoinTransactionBuilder.build(liteRequest) }932        liteRequest.recipients[0].value = 2_940933        let litePlan = try BitcoinTransactionBuilder.build(liteRequest)934        #expect(litePlan.transaction.signalsRBF && litePlan.estimatedVSize == 141)935936        // Bitcoin through the network initialiser is Bitcoin as before937        let bitcoin = try BIP84Account(master: master, network: .mainnet)938        let bc = try coin(bitcoin, index: 0, value: 1_000_000, salt: 0x45)939        let recipients = [BitcoinTransaction.Output(value: 300_000, scriptPubKey: try bitcoin.scriptPubKey(chain: .receive, index: 1))]940        var old = BitcoinSpendRequest(recipients: recipients, utxos: [bc.utxo], feeRate: FeeRate(satPerVByte: 3), changeScript: try bitcoin.scriptPubKey(chain: .change, index: 0))941        var new = BitcoinSpendRequest(network: .mainnet, recipients: recipients, utxos: [bc.utxo], feeRate: FeeRate(satPerVByte: 3),942                                      changeScript: try bitcoin.scriptPubKey(chain: .change, index: 0))943        old.seed = 9944        new.seed = 9945        let oldPlan = try BitcoinTransactionBuilder.build(old), newPlan = try BitcoinTransactionBuilder.build(new)946        #expect(oldPlan.transaction == newPlan.transaction && oldPlan.fee == newPlan.fee && oldPlan.estimatedWeight == newPlan.estimatedWeight)947        #expect(oldPlan.network == nil && newPlan.network == .mainnet)948    }949950    /// Exposure analysis is unchanged in principle: a P2PKH key stays behind its hash until the first spend.951    @Test func exposureOfLegacyAddresses() throws {952        for n in [BitcoinNetwork.dogecoin, .bitcoinCash, .litecoin] {953            let account = try UTXOAccount(master: try abandonMaster(), network: n, purpose: .bip44)954            let script = try account.scriptPubKey(chain: .receive, index: 0)955            #expect(BitcoinPrivacyAnalysis.publicKeyExposure(scriptPubKey: script, hasSpend: false).exposure == .hashedUnrevealed)956            #expect(BitcoinPrivacyAnalysis.publicKeyExposure(scriptPubKey: script, hasSpend: true).exposure == .revealedBySpend)957            #expect(BitcoinPrivacyAnalysis.publicKeyExposure(scriptPubKey: script, hasSpend: false).scriptType == .p2pkh)958        }959    }960}961
Files main
Menu

Theme