SPB Git

Repository Public

CoinSelectionTests.swift 41.5 KB 645 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Tests/QyvoraBitcoinTests/CoinSelectionTests.swift8// Module           : Tests9// Repository       : https://git.spboucher.ai/qyvora10// Project Website  : Not specified11// Created          : 2026-12-0412// Last Modified    : 2026-12-0413//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 Testing42import QyvoraMath43import QyvoraSymmetric44import QyvoraSecp256k145import QyvoraCore46@testable import QyvoraBitcoin4748@Suite struct CoinSelectionTests {49    static let walletScript: Bytes = [0x00, 0x14] + Bytes(repeating: 0x11, count: 20)50    static let changeScript: Bytes = [0x00, 0x14] + Bytes(repeating: 0x22, count: 20)51    static let payScript: Bytes = [0x00, 0x14] + Bytes(repeating: 0x33, count: 20)5253    static func utxo(_ n: Int, _ value: UInt64, confirmations: UInt32 = 6, script: Bytes = walletScript, coinbase: Bool = false) -> BitcoinUTXO {54        var hash = Bytes(repeating: 0, count: 32)55        hash[0] = UInt8(n & 0xff)56        hash[1] = UInt8((n >> 8) & 0xff)57        hash[31] = 0xee58        return BitcoinUTXO(outPoint: BitcoinOutPoint(hash: hash, index: UInt32(n % 3))!, value: value, scriptPubKey: script,59                           confirmations: confirmations, isCoinbase: coinbase)60    }6162    static func request(_ amounts: [UInt64], utxos: [BitcoinUTXO], rate: UInt64 = 5, seed: UInt64 = 1) -> BitcoinSpendRequest {63        var r = BitcoinSpendRequest(recipients: amounts.map { .init(value: $0, scriptPubKey: payScript) }, utxos: utxos,64                                    feeRate: FeeRate(satPerVByte: rate), changeScript: changeScript)65        r.seed = seed66        return r67    }6869    /// The invariants every plan must satisfy.70    static func checkInvariants(_ plan: BitcoinTransactionPlan, _ request: BitcoinSpendRequest, sourceLocation: SourceLocation = #_sourceLocation) {71        let tx = plan.transaction72        let inputTotal = plan.inputs.reduce(UInt64(0)) { $0 + $1.value }73        let outputTotal = tx.outputs.reduce(UInt64(0)) { $0 + $1.value }74        #expect(inputTotal == outputTotal + plan.fee, sourceLocation: sourceLocation)75        #expect(inputTotal >= outputTotal + plan.fee, sourceLocation: sourceLocation)76        #expect(plan.fee >= request.feeRate.fee(weight: plan.estimatedWeight), "fee below target", sourceLocation: sourceLocation)77        #expect(plan.effectiveFeeRate >= request.feeRate, sourceLocation: sourceLocation)78        #expect(plan.fee <= request.maximumFee, sourceLocation: sourceLocation)79        #expect(tx.outputs.allSatisfy { !BitcoinSizeEstimator.isDust($0) }, "dust output", sourceLocation: sourceLocation)80        #expect(tx.inputs.map(\.previousOutput) == plan.inputs.map(\.outPoint), sourceLocation: sourceLocation)81        #expect(Set(tx.inputs.map(\.previousOutput)).count == tx.inputs.count, sourceLocation: sourceLocation)82        #expect(tx.inputs.allSatisfy { $0.scriptSig.isEmpty && $0.witness.isEmpty }, sourceLocation: sourceLocation)83        // every recipient is paid exactly once84        var remaining = tx.outputs.enumerated().filter { $0.offset != plan.changeIndex && $0.offset != plan.sendMaxIndex }.map(\.element)85        for r in request.recipients {86            let i = remaining.firstIndex(of: r)87            #expect(i != nil, "recipient missing", sourceLocation: sourceLocation)88            if let i { remaining.remove(at: i) }89        }90        #expect(remaining.isEmpty, sourceLocation: sourceLocation)91        if let c = plan.changeIndex {92            #expect(tx.outputs[c].scriptPubKey == request.changeScript, sourceLocation: sourceLocation)93            #expect(plan.changeValue == tx.outputs[c].value, sourceLocation: sourceLocation)94        } else {95            #expect(plan.changeValue == 0, sourceLocation: sourceLocation)96        }97        // exact size model: the estimated weight is what a fully signed transaction weighs at most98        let exact = BitcoinSizeEstimator.transactionWeight(inputWeights: plan.inputs.map { $0.inputWeight! }, outputScripts: tx.outputs.map(\.scriptPubKey))99        #expect(exact == plan.estimatedWeight, sourceLocation: sourceLocation)100    }101102    @Test func feeRateArithmetic() {103        #expect(FeeRate(satPerVByte: 1).fee(vsize: 141) == 141)104        #expect(FeeRate(milliSatPerVByte: 1500).fee(vsize: 141) == 212)   // 211.5 rounded up105        #expect(FeeRate(milliSatPerVByte: 1).fee(vsize: 1) == 1)106        #expect(FeeRate(satPerVByte: 0).fee(vsize: 1000) == 0)107        #expect(FeeRate(satPerVByte: 2).fee(weight: 561) == 282)          // 140.25 vB → 141 vB108        #expect(FeeRate(satPerVByte: 2).fee(weight: 560) == 280)109        #expect(FeeRate(satPerKiloVByte: 1000) == FeeRate(satPerVByte: 1))110        #expect(FeeRate(satPerVByte: 3) > FeeRate(milliSatPerVByte: 2999))111        #expect(FeeRate.fromEstimate(satPerVByte: 1.0) == FeeRate(satPerVByte: 1))112        #expect(FeeRate.fromEstimate(satPerVByte: 2.0001) == FeeRate(milliSatPerVByte: 2001))113        #expect(FeeRate.fromEstimate(satPerVByte: 12.345) == FeeRate(milliSatPerVByte: 12345) || FeeRate.fromEstimate(satPerVByte: 12.345) == FeeRate(milliSatPerVByte: 12346))114        #expect(FeeRate.fromEstimate(satPerVByte: .nan) == nil)115        #expect(FeeRate.fromEstimate(satPerVByte: .infinity) == nil)116        #expect(FeeRate.fromEstimate(satPerVByte: -1) == nil)117        #expect(FeeRate.fromEstimate(satPerVByte: 1e9) == nil)118        #expect(FeeRate(satPerVByte: 12).description == "12 sat/vB")119        #expect(FeeRate(milliSatPerVByte: 1050).description == "1.050 sat/vB")120        // no overflow trap on absurd inputs121        #expect(FeeRate(satPerVByte: UInt64.max).fee(vsize: Int.max) > 0)122    }123124    @Test func sizesAndDustThresholds() throws {125        let p2pkh = try BitcoinScript.p2pkh(publicKeyHash: Bytes(repeating: 1, count: 20))126        let p2sh = try BitcoinScript.p2sh(scriptHash: Bytes(repeating: 1, count: 20))127        let p2wpkh = try BitcoinScript.p2wpkh(publicKeyHash: Bytes(repeating: 1, count: 20))128        let p2wsh = try BitcoinScript.p2wsh(scriptHash: Bytes(repeating: 1, count: 32))129        let p2tr = try BitcoinScript.p2tr(outputKey: Bytes(repeating: 1, count: 32))130        // Bitcoin Core's well-known thresholds at the 3 sat/vB dust relay fee131        #expect(BitcoinSizeEstimator.dustThreshold(scriptPubKey: p2pkh) == 546)132        #expect(BitcoinSizeEstimator.dustThreshold(scriptPubKey: p2sh) == 540)133        #expect(BitcoinSizeEstimator.dustThreshold(scriptPubKey: p2wpkh) == 294)134        #expect(BitcoinSizeEstimator.dustThreshold(scriptPubKey: p2wsh) == 330)135        #expect(BitcoinSizeEstimator.dustThreshold(scriptPubKey: p2tr) == 330)136        #expect(BitcoinSizeEstimator.dustThreshold(scriptPubKey: try BitcoinScript.nullData([1])) == 0)137        #expect(BitcoinSizeEstimator.isDust(.init(value: 293, scriptPubKey: p2wpkh)))138        #expect(!BitcoinSizeEstimator.isDust(.init(value: 294, scriptPubKey: p2wpkh)))139        // output sizes in bytes: 34, 32, 31, 43, 43140        #expect([p2pkh, p2sh, p2wpkh, p2wsh, p2tr].map { BitcoinSizeEstimator.outputWeight(scriptPubKey: $0) / 4 } == [34, 32, 31, 43, 43])141        // input weights: P2WPKH 68 vB, P2PKH 148 bytes, P2SH-P2WPKH 91 vB, P2TR 57.5 vB142        #expect(BitcoinSizeEstimator.inputWeight(scriptPubKey: p2wpkh) == 272)143        #expect(BitcoinSizeEstimator.inputWeight(scriptPubKey: p2pkh) == 148 * 4 + 1)144        #expect(BitcoinSizeEstimator.inputWeight(scriptPubKey: p2sh, redeemScript: p2wpkh) == 364)145        #expect(BitcoinSizeEstimator.inputWeight(scriptPubKey: p2tr) == 230)146        #expect(BitcoinSizeEstimator.inputWeight(scriptPubKey: p2wsh) == nil)147        #expect(BitcoinSizeEstimator.inputWeight(scriptPubKey: p2sh) == nil)148        #expect(BitcoinSizeEstimator.inputWeight(scriptPubKey: [0x51]) == nil)149        let multisig = try BitcoinScript.multisig(required: 2, publicKeys: (1...3).map { testPublicKey($0) }, sorted: true)150        // 41 bytes + witness: count, empty, 2 × (1 + 72), 1 + 105-byte script151        #expect(BitcoinSizeEstimator.inputWeight(scriptPubKey: try BitcoinScript.p2wsh(witnessScript: multisig), witnessScript: multisig) == 164 + 2 + 146 + 106)152        // 1-input 2-output P2WPKH transaction: 10.5 + 68 + 62 = 140.5 → 141 vB153        let w = BitcoinSizeEstimator.transactionWeight(inputWeights: [272], outputScripts: [p2wpkh, p2wpkh])154        #expect(w == 562 && (w + 3) / 4 == 141)155        #expect(BitcoinSizeEstimator.overheadWeight(inputCount: 253, outputCount: 1, hasWitness: false) == 48)156    }157158    @Test func branchAndBoundFindsExactMatch() throws {159        // fee at 5 sat/vB: fixed part 10.5 + 31 → 42 vB = 210, each input 68 vB = 340160        // 30 000 + 70 000 − 2·340 − 210 = 99 110 exactly161        let utxos = [Self.utxo(1, 30_000), Self.utxo(2, 55_000), Self.utxo(3, 70_000), Self.utxo(4, 120_000), Self.utxo(5, 8_000)]162        let request = Self.request([99_110], utxos: utxos)163        let plan = try BitcoinTransactionBuilder.build(request)164        Self.checkInvariants(plan, request)165        #expect(plan.algorithm == .branchAndBound)166        #expect(plan.changeIndex == nil && plan.transaction.outputs.count == 1)167        #expect(Set(plan.inputs.map(\.value)) == [30_000, 70_000])168        // 2 inputs + 1 output: 10.5 + 136 + 31 = 177.5 → 178 vB → 890 sat required; the per-part rounding leaves 0 extra169        #expect(plan.estimatedVSize == 178 && plan.fee == 890)170171        // a target a few satoshis lower is still changeless: the remainder goes to the fee, bounded by the cost of change172        let near = Self.request([99_000], utxos: utxos)173        let nearPlan = try BitcoinTransactionBuilder.build(near)174        Self.checkInvariants(nearPlan, near)175        #expect(nearPlan.algorithm == .branchAndBound && nearPlan.changeIndex == nil && nearPlan.fee == 1_000)176177        // single-coin exact match178        let single = Self.request([55_000 - 340 - 210], utxos: utxos)179        let singlePlan = try BitcoinTransactionBuilder.build(single)180        #expect(singlePlan.algorithm == .branchAndBound && singlePlan.inputs.map(\.value) == [55_000])181        Self.checkInvariants(singlePlan, single)182    }183184    @Test func branchAndBoundCore() {185        func candidate(_ n: Int, _ value: UInt64) -> BitcoinCoinSelection.Candidate {186            .init(utxo: Self.utxo(n, value), weight: 272, fee: 0, longTermFee: 0)187        }188        let pool = [1, 2, 3, 4].enumerated().map { candidate($0.offset, UInt64($0.element) * 100_000_000) }189        func pick(_ target: Int64, cost: Int64 = 0) -> Set<UInt64>? {190            BitcoinCoinSelection.branchAndBound(candidates: pool, target: target, costOfChange: cost).map { Set($0.map { pool[$0].utxo.value }) }191        }192        // cases of Bitcoin Core's coinselector_tests (bnb_search_test): values 1, 2, 3, 4 CENT-like units193        #expect(pick(100_000_000) == [100_000_000])194        #expect(pick(200_000_000) == [200_000_000])195        #expect(pick(500_000_000) == [400_000_000, 100_000_000] || pick(500_000_000) == [300_000_000, 200_000_000])196        #expect(pick(1_000_000_000) == [100_000_000, 200_000_000, 300_000_000, 400_000_000])197        #expect(pick(1_100_000_000) == nil)                 // more than everything198        #expect(pick(25_000_000) == nil)                    // nothing small enough, no tolerance199        #expect(pick(90_000_000, cost: 10_000_000) == [100_000_000])   // within the cost of change200        #expect(pick(90_000_000, cost: 9_999_999) == nil)201        #expect(pick(0) == nil && pick(-5) == nil)202        #expect(BitcoinCoinSelection.branchAndBound(candidates: [], target: 1, costOfChange: 0) == nil)203        // many equal coins: the equivalent-branch skip keeps the search within its budget204        let equal = (0..<60).map { candidate($0, 7_000) }205        let found = BitcoinCoinSelection.branchAndBound(candidates: equal, target: 7_000 * 23, costOfChange: 0)206        #expect(found?.count == 23)207        #expect(BitcoinCoinSelection.branchAndBound(candidates: equal, target: 7_000 * 23 + 1, costOfChange: 0) == nil)208    }209210    @Test func largestFirstWithChange() throws {211        let utxos = [Self.utxo(1, 30_000), Self.utxo(2, 55_000), Self.utxo(3, 70_000), Self.utxo(4, 120_000), Self.utxo(5, 8_000)]212        let request = Self.request([60_000], utxos: utxos)213        let plan = try BitcoinTransactionBuilder.build(request)214        Self.checkInvariants(plan, request)215        #expect(plan.algorithm == .largestFirst)216        #expect(plan.inputs.map(\.value) == [120_000])217        let change = try #require(plan.changeIndex)218        // 1 input, 2 outputs: 141 vB → 705 sat, paid exactly219        #expect(plan.fee == 705 && plan.transaction.outputs[change].value == 120_000 - 60_000 - 705)220        // needs two coins221        let two = Self.request([150_000], utxos: utxos)222        let twoPlan = try BitcoinTransactionBuilder.build(two)223        Self.checkInvariants(twoPlan, two)224        #expect(Set(twoPlan.inputs.map(\.value)) == [120_000, 70_000] && twoPlan.changeIndex != nil)225    }226227    @Test func changeBelowDustGoesToFee() throws {228        // one coin at 1 sat/vB; after payment and the 1-output fee only 200 sat remain: more than Branch and Bound tolerates229        // (cost of change 31 + 68 = 99 sat) and below the 294 sat dust threshold of a change output230        let coin = Self.utxo(1, 50_000)231        let rate = FeeRate(satPerVByte: 1)232        let fee1 = rate.fee(weight: BitcoinSizeEstimator.transactionWeight(inputWeights: [272], outputScripts: [Self.payScript]))233        #expect(fee1 == 110)234        var request = Self.request([50_000 - fee1 - 200], utxos: [coin], rate: 1)235        var plan = try BitcoinTransactionBuilder.build(request)236        Self.checkInvariants(plan, request)237        #expect(plan.changeIndex == nil && plan.fee == fee1 + 200 && plan.algorithm == .largestFirst)238        // exactly at the threshold where change (after paying for its own output) is 294 sat: change is created239        let fee2 = rate.fee(weight: BitcoinSizeEstimator.transactionWeight(inputWeights: [272], outputScripts: [Self.payScript, Self.changeScript]))240        request = Self.request([50_000 - fee2 - 294], utxos: [coin], rate: 1)241        plan = try BitcoinTransactionBuilder.build(request)242        Self.checkInvariants(plan, request)243        #expect(plan.changeValue == 294 && plan.fee == fee2)244        // one satoshi less of change: dropped245        request = Self.request([50_000 - fee2 - 293], utxos: [coin], rate: 1)246        plan = try BitcoinTransactionBuilder.build(request)247        Self.checkInvariants(plan, request)248        #expect(plan.changeIndex == nil && plan.fee == fee2 + 293)249        // at 5 sat/vB a 294 sat change would cost 340 sat to spend later: Branch and Bound prefers to leave it to the fee250        request = Self.request([50_000 - 705 - 294], utxos: [coin], rate: 5)251        plan = try BitcoinTransactionBuilder.build(request)252        Self.checkInvariants(plan, request)253        #expect(plan.changeIndex == nil && plan.algorithm == .branchAndBound && plan.fee == 705 + 294)254    }255256    @Test func insufficientFundsAndValidation() throws {257        let utxos = [Self.utxo(1, 30_000), Self.utxo(2, 55_000)]258        #expect(throws: BitcoinBuildError.insufficientFunds(available: 85_000, required: 85_000 + 890)) {259            try BitcoinTransactionBuilder.build(Self.request([85_000], utxos: utxos))260        }261        // spendable only without paying the fee262        #expect(throws: BitcoinBuildError.self) { try BitcoinTransactionBuilder.build(Self.request([84_500], utxos: utxos)) }263        #expect(throws: BitcoinBuildError.insufficientFunds(available: 0, required: 1_000 + 210)) {264            try BitcoinTransactionBuilder.build(Self.request([1_000], utxos: []))265        }266        #expect(throws: BitcoinBuildError.noRecipients) { try BitcoinTransactionBuilder.build(Self.request([], utxos: utxos)) }267        #expect(throws: BitcoinBuildError.dustOutput(index: 1)) { try BitcoinTransactionBuilder.build(Self.request([5_000, 293], utxos: utxos)) }268        #expect(throws: BitcoinBuildError.dustOutput(index: 0)) { try BitcoinTransactionBuilder.build(Self.request([0], utxos: utxos)) }269        #expect(throws: BitcoinBuildError.dustOutput(index: 0)) {270            try BitcoinTransactionBuilder.build(Self.request([BitcoinLimits.maxMoney + 1], utxos: utxos))271        }272        #expect(throws: BitcoinBuildError.invalidAmount) {273            try BitcoinTransactionBuilder.build(Self.request([BitcoinLimits.maxMoney, BitcoinLimits.maxMoney], utxos: utxos))274        }275        #expect(throws: BitcoinBuildError.duplicateUTXO) { try BitcoinTransactionBuilder.build(Self.request([5_000], utxos: utxos + [utxos[0]])) }276        // OP_RETURN outputs may carry zero value277        var data = Self.request([20_000], utxos: utxos)278        data.recipients.append(.init(value: 0, scriptPubKey: try BitcoinScript.nullData(Bytes("hello".utf8))))279        let plan = try BitcoinTransactionBuilder.build(data)280        #expect(plan.transaction.outputs.contains { $0.value == 0 && $0.scriptPubKey.first == 0x6a })281        #expect(plan.fee >= data.feeRate.fee(weight: plan.estimatedWeight))282        // coins that cost more to spend than they hold are never selected283        var expensive = Self.request([1_000], utxos: [Self.utxo(1, 300), Self.utxo(2, 330)], rate: 5)284        #expect(throws: BitcoinBuildError.insufficientFunds(available: 0, required: 1_000 + 210)) { try BitcoinTransactionBuilder.build(expensive) }285        expensive.utxos.append(Self.utxo(3, 9_000))286        #expect(try BitcoinTransactionBuilder.build(expensive).inputs.map(\.value) == [9_000])287        // a coin whose input cannot be sized is skipped automatically, and refused when imposed288        let odd = Self.utxo(9, 500_000, script: [0x51])289        var withOdd = Self.request([20_000], utxos: utxos + [odd])290        #expect(try !BitcoinTransactionBuilder.build(withOdd).inputs.contains(odd))291        withOdd.coinControl.required = [odd.outPoint]292        #expect(throws: BitcoinBuildError.unknownInputSize(odd.outPoint)) { try BitcoinTransactionBuilder.build(withOdd) }293    }294295    @Test func feeLimits() throws {296        let utxos = [Self.utxo(1, 3_000_000)]297        var r = Self.request([100_000], utxos: utxos, rate: 5)298        r.maximumFee = 704299        #expect(throws: BitcoinBuildError.feeExceedsCap(fee: 705, cap: 704)) { try BitcoinTransactionBuilder.build(r) }300        r.maximumFee = 705301        #expect(try BitcoinTransactionBuilder.build(r).fee == 705)302        // target rate outside the allowed band303        r = Self.request([100_000], utxos: utxos, rate: 5_001)304        #expect(throws: BitcoinBuildError.feeRateOutOfRange) { try BitcoinTransactionBuilder.build(r) }305        r.feeRate = FeeRate(milliSatPerVByte: 999)306        #expect(throws: BitcoinBuildError.feeRateOutOfRange) { try BitcoinTransactionBuilder.build(r) }307        r.feeRate = FeeRate(satPerVByte: 0)308        r.minimumFeeRate = FeeRate(satPerVByte: 0)309        #expect(throws: BitcoinBuildError.feeRateOutOfRange) { try BitcoinTransactionBuilder.build(r) }310        // sub-1 sat/vB when the caller lowers the floor311        r.feeRate = FeeRate(milliSatPerVByte: 100)312        r.minimumFeeRate = FeeRate(milliSatPerVByte: 100)313        #expect(try BitcoinTransactionBuilder.build(r).fee == 15)   // 141 vB × 0.1 = 14.1 → 15314        // the default cap of 1 000 000 sat stops a mistyped rate315        r = Self.request([100_000], utxos: utxos, rate: 5_000)316        r.maximumFeeRate = FeeRate(satPerVByte: 10_000)317        r.feeRate = FeeRate(satPerVByte: 8_000)318        #expect(throws: BitcoinBuildError.feeExceedsCap(fee: 1_128_000, cap: 1_000_000)) { try BitcoinTransactionBuilder.build(r) }319        // without change script a remainder larger than dust is never given away to miners320        var noChange = Self.request([100_000], utxos: utxos)321        noChange.changeScript = nil322        #expect(throws: BitcoinBuildError.changeScriptRequired) { try BitcoinTransactionBuilder.build(noChange) }323        noChange.recipients = [.init(value: 3_000_000 - 550, scriptPubKey: Self.payScript)]324        #expect(try BitcoinTransactionBuilder.build(noChange).fee == 550)325    }326327    @Test func coinControl() throws {328        let utxos = [Self.utxo(1, 30_000), Self.utxo(2, 55_000), Self.utxo(3, 70_000), Self.utxo(4, 120_000), Self.utxo(5, 8_000, confirmations: 0),329                     Self.utxo(6, 900_000, confirmations: 50, coinbase: true)]330        // frozen coins are never used331        var r = Self.request([60_000], utxos: utxos)332        r.coinControl.excluded = [utxos[3].outPoint]333        var plan = try BitcoinTransactionBuilder.build(r)334        Self.checkInvariants(plan, r)335        #expect(!plan.inputs.contains(utxos[3]) && plan.inputs.map(\.value) == [70_000])336        // a required coin is always spent, the rest is completed automatically337        r = Self.request([60_000], utxos: utxos)338        r.coinControl.required = [utxos[0].outPoint]339        plan = try BitcoinTransactionBuilder.build(r)340        Self.checkInvariants(plan, r)341        #expect(plan.inputs.contains(utxos[0]) && plan.inputs.count == 2)342        // exactly the imposed set343        r.coinControl.required = [utxos[0].outPoint, utxos[1].outPoint]344        r.coinControl.useOnlyRequired = true345        plan = try BitcoinTransactionBuilder.build(r)346        Self.checkInvariants(plan, r)347        #expect(plan.algorithm == .manual && Set(plan.inputs) == [utxos[0], utxos[1]])348        r.recipients = [.init(value: 90_000, scriptPubKey: Self.payScript)]349        #expect(throws: BitcoinBuildError.insufficientFunds(available: 85_000, required: 90_000 + 890)) { try BitcoinTransactionBuilder.build(r) }350        r.coinControl.required = []351        #expect(throws: BitcoinBuildError.insufficientFunds(available: 0, required: 90_000)) { try BitcoinTransactionBuilder.build(r) }352        // required coin that is frozen, unknown or listed twice353        r = Self.request([60_000], utxos: utxos)354        r.coinControl.required = [utxos[0].outPoint]355        r.coinControl.excluded = [utxos[0].outPoint]356        #expect(throws: BitcoinBuildError.requiredInputUnavailable(utxos[0].outPoint)) { try BitcoinTransactionBuilder.build(r) }357        let stranger = Self.utxo(77, 1).outPoint358        r.coinControl = .init(required: [stranger])359        #expect(throws: BitcoinBuildError.requiredInputUnavailable(stranger)) { try BitcoinTransactionBuilder.build(r) }360        r.coinControl = .init(required: [utxos[0].outPoint, utxos[0].outPoint])361        #expect(throws: BitcoinBuildError.duplicateUTXO) { try BitcoinTransactionBuilder.build(r) }362        // immature coinbase: never automatic, refused when imposed; unconfirmed coins need minimumConfirmations 0363        r = Self.request([200_000], utxos: utxos)364        plan = try BitcoinTransactionBuilder.build(r)365        #expect(!plan.inputs.contains(utxos[5]) && !plan.inputs.contains(utxos[4]))366        r.coinControl.required = [utxos[5].outPoint]367        #expect(throws: BitcoinBuildError.requiredInputUnavailable(utxos[5].outPoint)) { try BitcoinTransactionBuilder.build(r) }368        r = Self.request([280_000], utxos: Array(utxos.prefix(5)))369        #expect(throws: BitcoinBuildError.self) { try BitcoinTransactionBuilder.build(r) }370        r.coinControl.minimumConfirmations = 0371        plan = try BitcoinTransactionBuilder.build(r)372        Self.checkInvariants(plan, r)373        #expect(plan.inputs.count == 5)374        // an unconfirmed coin may be imposed whatever the minimum375        r = Self.request([5_000], utxos: utxos)376        r.coinControl = .init(required: [utxos[4].outPoint], useOnlyRequired: true)377        #expect(try BitcoinTransactionBuilder.build(r).inputs == [utxos[4]])378    }379380    @Test func sendMax() throws {381        let utxos = [Self.utxo(1, 30_000), Self.utxo(2, 55_000), Self.utxo(3, 70_000), Self.utxo(4, 200), Self.utxo(5, 8_000, confirmations: 0)]382        var r = BitcoinSpendRequest(recipients: [], utxos: utxos, feeRate: FeeRate(satPerVByte: 5), changeScript: nil, sendMaxScript: Self.payScript)383        r.seed = 3384        var plan = try BitcoinTransactionBuilder.build(r)385        Self.checkInvariants(plan, r)386        // 3 confirmed economical coins, 1 output: 10.5 + 204 + 31 = 245.5 → 246 vB → 1 230 sat387        #expect(plan.algorithm == .sendMax && plan.inputs.count == 3 && plan.fee == 1_230)388        #expect(plan.changeIndex == nil && plan.sendMaxIndex == 0)389        #expect(plan.transaction.outputs == [.init(value: 155_000 - 1_230, scriptPubKey: Self.payScript)])390        // a fixed payment besides the swept remainder391        r.recipients = [.init(value: 10_000, scriptPubKey: Self.changeScript)]392        plan = try BitcoinTransactionBuilder.build(r)393        Self.checkInvariants(plan, r)394        let max = try #require(plan.sendMaxIndex)395        #expect(plan.transaction.outputs.count == 2 && plan.transaction.outputs[max].scriptPubKey == Self.payScript)396        #expect(plan.transaction.outputs[max].value == 155_000 - 10_000 - plan.fee && plan.fee == 1_385)397        // sweep of an explicit set398        r.recipients = []399        r.coinControl = .init(required: [utxos[0].outPoint], useOnlyRequired: true)400        plan = try BitcoinTransactionBuilder.build(r)401        #expect(plan.inputs == [utxos[0]] && plan.transaction.outputs[0].value == 30_000 - 550 && plan.algorithm == .manual)402        // nothing left after the fee403        r.coinControl = .init()404        r.utxos = [Self.utxo(1, 800)]405        #expect(throws: BitcoinBuildError.sendMaxBelowDust) { try BitcoinTransactionBuilder.build(r) }406        r.utxos = [Self.utxo(1, 550 + 294)]407        #expect(try BitcoinTransactionBuilder.build(r).transaction.outputs[0].value == 294)408        r.utxos = []409        #expect(throws: BitcoinBuildError.insufficientFunds(available: 0, required: 0)) { try BitcoinTransactionBuilder.build(r) }410        r.utxos = utxos411        r.sendMaxScript = try BitcoinScript.nullData([1])412        #expect(throws: BitcoinBuildError.sendMaxBelowDust) { try BitcoinTransactionBuilder.build(r) }413    }414415    @Test func rbfLockTimeAndOrdering() throws {416        let utxos = (1...8).map { Self.utxo($0, 40_000 + UInt64($0) * 1_111) }417        var r = Self.request([150_000, 20_000, 31_000], utxos: utxos)418        var plan = try BitcoinTransactionBuilder.build(r)419        Self.checkInvariants(plan, r)420        #expect(plan.transaction.inputs.allSatisfy { $0.sequence == 0xffff_fffd } && plan.transaction.signalsRBF)421        #expect(plan.transaction.lockTime == 0 && plan.transaction.version == 2)422        r.enableRBF = false423        plan = try BitcoinTransactionBuilder.build(r)424        #expect(plan.transaction.inputs.allSatisfy { $0.sequence == 0xffff_fffe } && !plan.transaction.signalsRBF)425        // anti-fee-sniping: the lock time is the tip height, occasionally up to 99 blocks earlier, never later426        r.currentHeight = 900_000427        var exact = 0428        for seed in 0..<200 as Range<UInt64> {429            r.seed = seed430            let lock = try BitcoinTransactionBuilder.build(r).transaction.lockTime431            #expect(lock <= 900_000 && lock > 900_000 - 100)432            if lock == 900_000 { exact += 1 }433        }434        #expect(exact >= 150 && exact < 200)435        r.currentHeight = 5436        r.seed = 0437        #expect(try BitcoinTransactionBuilder.build(r).transaction.lockTime <= 5)438439        // determinism: the same seed gives the same transaction, whatever the order of the candidates440        r.seed = 1234441        let a = try BitcoinTransactionBuilder.build(r)442        let b = try BitcoinTransactionBuilder.build(r)443        #expect(a == b)444        var shuffled = r445        shuffled.utxos = utxos.reversed()446        #expect(try BitcoinTransactionBuilder.build(shuffled) == a)447        var generator = SeededGenerator(seed: 99)448        for _ in 0..<10 {449            generator.shuffle(&shuffled.utxos)450            #expect(try BitcoinTransactionBuilder.build(shuffled) == a)451        }452        // different seeds: same coins and amounts, and the change output visits every position453        var positions = Set<Int>()454        for seed in 0..<60 as Range<UInt64> {455            r.seed = seed456            let p = try BitcoinTransactionBuilder.build(r)457            #expect(Set(p.inputs) == Set(a.inputs) && p.fee == a.fee)458            positions.insert(try #require(p.changeIndex))459        }460        #expect(positions == [0, 1, 2, 3])461        // without seed the system generator is used: still a valid plan462        r.seed = nil463        Self.checkInvariants(try BitcoinTransactionBuilder.build(r), r)464    }465466    @Test func seededGeneratorIsDeterministicAndUniformEnough() {467        var a = SeededGenerator(seed: 7), b = SeededGenerator(seed: 7), c = SeededGenerator(seed: 8)468        let xs = (0..<5).map { _ in a.next() }469        #expect(xs == (0..<5).map { _ in b.next() })470        #expect(xs != (0..<5).map { _ in c.next() })471        var counts = [Int](repeating: 0, count: 6)472        for _ in 0..<6_000 { counts[Int(a.below(6))] += 1 }473        #expect(counts.allSatisfy { $0 > 850 && $0 < 1_150 })474        var items = Array(0..<20)475        a.shuffle(&items)476        #expect(items.sorted() == Array(0..<20) && items != Array(0..<20))477    }478479    /// Property test over random wallets, amounts and fee rates (seeded, hence reproducible).480    @Test func randomisedInvariants() throws {481        var rng = SeededGenerator(seed: 0x51_59_56_4f_52_41)482        var built = 0, changeless = 0, bnb = 0, insufficient = 0483        for round in 0..<400 {484            let count = 1 + Int(rng.below(14))485            var utxos = [BitcoinUTXO]()486            for i in 0..<count {487                let magnitude = [1_000, 20_000, 300_000, 5_000_000][Int(rng.below(4))] as UInt64488                utxos.append(Self.utxo(round * 16 + i, 300 + rng.below(magnitude)))489            }490            let total = utxos.reduce(UInt64(0)) { $0 + $1.value }491            let recipients = 1 + Int(rng.below(3))492            let amounts = (0..<recipients).map { _ in 294 + rng.below(max(1, total / UInt64(recipients))) }493            var request = Self.request(amounts, utxos: utxos, rate: 1 + rng.below(60), seed: rng.next())494            request.maximumFee = 10_000_000495            if rng.below(4) == 0 { request.longTermFeeRate = FeeRate(satPerVByte: 3) }496            do {497                let plan = try BitcoinTransactionBuilder.build(request)498                Self.checkInvariants(plan, request)499                built += 1500                if plan.changeIndex == nil {501                    changeless += 1502                    // what is left to the fee beyond the requirement never exceeds the cost of change bound503                    let required = request.feeRate.fee(weight: plan.estimatedWeight)504                    let longTerm = request.longTermFeeRate ?? request.feeRate505                    let bound = request.feeRate.fee(vsize: 31) + max(294, longTerm.fee(vsize: 68)) + UInt64(plan.inputs.count + 1) * (request.feeRate.milliSatPerVByte / 1000 + 1)506                    #expect(plan.fee - required <= bound, "round \(round): excess \(plan.fee - required) > \(bound)")507                } else {508                    #expect(plan.fee == request.feeRate.fee(weight: plan.estimatedWeight), "round \(round)")509                }510                if plan.algorithm == .branchAndBound { bnb += 1 }511                #expect(try BitcoinTransactionBuilder.build(request) == plan)512            } catch let error as BitcoinBuildError {513                guard case .insufficientFunds(let available, let required) = error else {514                    Issue.record("round \(round): unexpected \(error)")515                    continue516                }517                #expect(available < required, "round \(round)")518                insufficient += 1519            }520        }521        #expect(built > 200 && changeless > 0 && insufficient > 0 && built + insufficient == 400)522        _ = bnb523    }524525    /// Plans are signed for real: the fee rate actually paid, measured on the signed transaction, reaches the target.526    @Test func signedTransactionsMeetTheTargetRate() throws {527        let account = try BIP84Account(master: try abandonMaster(), network: .testnet)528        var utxos = [BitcoinUTXO]()529        for i in 0..<6 as Range<UInt32> {530            utxos.append(BitcoinUTXO(outPoint: BitcoinOutPoint(hash: Bytes(repeating: UInt8(0x40 + i), count: 32), index: i)!, value: 20_000 + UInt64(i) * 13_337,531                                     scriptPubKey: try account.scriptPubKey(chain: .receive, index: i), confirmations: 2, derivation: .init(chain: 0, index: i)))532        }533        for (amount, rate) in [(15_000, 1), (61_234, 7), (150_000, 33), (250_000, 2)] as [(UInt64, UInt64)] {534            var request = BitcoinSpendRequest(recipients: [.init(value: amount, scriptPubKey: Self.payScript)], utxos: utxos,535                                              feeRate: FeeRate(satPerVByte: rate), changeScript: try account.scriptPubKey(chain: .change, index: 0))536            request.seed = amount537            let plan = try BitcoinTransactionBuilder.build(request)538            Self.checkInvariants(plan, request)539            let tx = try account.sign(plan: plan)540            #expect(tx.weight <= plan.estimatedWeight)541            #expect(plan.fee >= request.feeRate.fee(weight: tx.weight))542            #expect(plan.fee * 1000 >= request.feeRate.milliSatPerVByte * UInt64(tx.vsize))543            try BitcoinVerifier.verify(transaction: tx, spentOutputs: plan.inputs.map(\.output))544            try tx.checkSanity()545        }546        // a wrong derivation hint is corrected by searching; a foreign coin is refused; watch-only cannot sign547        var request = BitcoinSpendRequest(recipients: [.init(value: 15_000, scriptPubKey: Self.payScript)], utxos: [utxos[2]],548                                          feeRate: FeeRate(satPerVByte: 2), changeScript: Self.changeScript)549        request.seed = 1550        let plan = try BitcoinTransactionBuilder.build(request)551        var tx = plan.transaction552        let wrongHint = BitcoinUTXO(outPoint: utxos[2].outPoint, value: utxos[2].value, scriptPubKey: utxos[2].scriptPubKey, confirmations: 2,553                                    derivation: .init(chain: 1, index: 40))554        try account.sign(transaction: &tx, spending: [wrongHint], searchLimit: 5)555        #expect(tx == (try account.sign(plan: plan)))556        var untouched = plan.transaction557        #expect(throws: BitcoinAccountError.inputCountMismatch) { try account.sign(transaction: &untouched, spending: []) }558        let foreign = BitcoinUTXO(outPoint: utxos[2].outPoint, value: 1, scriptPubKey: Self.walletScript, confirmations: 1)559        #expect(throws: BitcoinAccountError.foreignInput(index: 0)) { try account.sign(transaction: &untouched, spending: [foreign], searchLimit: 3) }560        #expect(throws: BitcoinAccountError.foreignInput(index: 0)) { try account.sign(transaction: &untouched, spending: [utxos[1]], searchLimit: 3) }561        #expect(untouched == plan.transaction)562        let watch = try BIP84Account(extendedKey: account.extendedPublicKey(), network: .testnet)563        #expect(throws: BitcoinAccountError.watchOnly) { try watch.sign(plan: plan) }564    }565}566567@Suite struct PrivacyAnalysisTests {568    static let p2wpkh: Bytes = [0x00, 0x14] + Bytes(repeating: 1, count: 20)569570    @Test func exposureClassification() throws {571        let hashed: [Bytes] = [try BitcoinScript.p2pkh(publicKeyHash: Bytes(repeating: 1, count: 20)), try BitcoinScript.p2sh(scriptHash: Bytes(repeating: 1, count: 20)),572                               Self.p2wpkh, try BitcoinScript.p2wsh(scriptHash: Bytes(repeating: 1, count: 32))]573        for script in hashed {574            let fresh = BitcoinPrivacyAnalysis.publicKeyExposure(scriptPubKey: script, hasSpend: false)575            #expect(fresh.exposure == .hashedUnrevealed && !fresh.explanation.isEmpty)576            #expect(fresh.scriptType == BitcoinScript.classify(script).type)577            let spent = BitcoinPrivacyAnalysis.publicKeyExposure(scriptPubKey: script, hasSpend: true)578            #expect(spent.exposure == .revealedBySpend && spent.explanation != fresh.explanation)579        }580        let inScript: [Bytes] = [try BitcoinScript.p2pk(publicKey: generatorKey), try BitcoinScript.p2pk(publicKey: generatorKeyUncompressed),581                                 try BitcoinScript.p2tr(outputKey: Bytes(repeating: 1, count: 32)),582                                 try BitcoinScript.multisig(required: 1, publicKeys: [generatorKey, testPublicKey(2)], sorted: false)]583        for script in inScript {584            for hasSpend in [false, true] {585                #expect(BitcoinPrivacyAnalysis.publicKeyExposure(scriptPubKey: script, hasSpend: hasSpend).exposure == .revealedByScript)586            }587        }588        for script in [try BitcoinScript.nullData([1]), [0x51], [], unhex("6002751e")] as [Bytes] {589            #expect(BitcoinPrivacyAnalysis.publicKeyExposure(scriptPubKey: script, hasSpend: false).exposure == .undetermined)590        }591        #expect(PublicKeyExposure.allCases.count == 4)592    }593594    @Test func exposurePerUTXO() throws {595        let other: Bytes = [0x00, 0x14] + Bytes(repeating: 2, count: 20)596        let taproot = try BitcoinScript.p2tr(outputKey: Bytes(repeating: 3, count: 32))597        let utxos = [CoinSelectionTests.utxo(1, 1_000, script: Self.p2wpkh), CoinSelectionTests.utxo(2, 1_000, script: other),598                     CoinSelectionTests.utxo(3, 1_000, script: taproot)]599        let activity = [ScriptActivity(scriptPubKey: Self.p2wpkh, kind: .funded, txid: "a", height: 10),600                        ScriptActivity(scriptPubKey: Self.p2wpkh, kind: .spent, txid: "b", height: nil),601                        ScriptActivity(scriptPubKey: other, kind: .funded, txid: "c", height: 11)]602        let result = BitcoinPrivacyAnalysis.publicKeyExposure(utxos: utxos, activity: activity)603        #expect(result.count == 3)604        #expect(result[utxos[0].outPoint]?.exposure == .revealedBySpend)605        #expect(result[utxos[1].outPoint]?.exposure == .hashedUnrevealed)606        #expect(result[utxos[2].outPoint]?.exposure == .revealedByScript)607    }608609    @Test func addressReuseDetection() {610        let a = Self.p2wpkh611        let b: Bytes = [0x00, 0x14] + Bytes(repeating: 2, count: 20)612        let c: Bytes = [0x00, 0x14] + Bytes(repeating: 3, count: 20)613        let d: Bytes = [0x00, 0x14] + Bytes(repeating: 4, count: 20)614        func f(_ s: Bytes, _ txid: String, _ h: UInt32?) -> ScriptActivity { .init(scriptPubKey: s, kind: .funded, txid: txid, height: h) }615        func s(_ s: Bytes, _ txid: String, _ h: UInt32?) -> ScriptActivity { .init(scriptPubKey: s, kind: .spent, txid: txid, height: h) }616        // a: funded once, spent once → clean617        #expect(BitcoinPrivacyAnalysis.addressReuse(activity: [f(a, "t1", 100), s(a, "t2", 105)]).isEmpty)618        #expect(!BitcoinPrivacyAnalysis.isReused(scriptPubKey: a, activity: [f(a, "t1", 100), s(a, "t2", 105)]))619        // two outputs of the same transaction are one funding transaction620        #expect(BitcoinPrivacyAnalysis.addressReuse(activity: [f(a, "t1", 100), f(a, "t1", 100)]).isEmpty)621        // b: funded by two transactions622        var findings = BitcoinPrivacyAnalysis.addressReuse(activity: [f(b, "t1", 100), f(b, "t3", 101)])623        #expect(findings == [AddressReuseFinding(scriptPubKey: b, fundingTransactionCount: 2, fundedByMultipleTransactions: true, fundedAfterSpend: false)])624        // c: funded again after a spend625        findings = BitcoinPrivacyAnalysis.addressReuse(activity: [f(c, "t1", 100), s(c, "t2", 105), f(c, "t9", 110)])626        #expect(findings.count == 1 && findings[0].fundedAfterSpend && findings[0].fundedByMultipleTransactions && findings[0].fundingTransactionCount == 2)627        // unconfirmed funding after a confirmed spend628        findings = BitcoinPrivacyAnalysis.addressReuse(activity: [f(d, "t1", 100), s(d, "t2", 105), f(d, "t7", nil)])629        #expect(findings.first?.fundedAfterSpend == true)630        // funded twice, both before the spend: reuse, but not "after spend"631        findings = BitcoinPrivacyAnalysis.addressReuse(activity: [f(d, "t1", 100), f(d, "t4", 102), s(d, "t2", 105)])632        #expect(findings.first?.fundedByMultipleTransactions == true && findings.first?.fundedAfterSpend == false)633        // same block and mempool-only chains cannot be ordered: not flagged634        #expect(BitcoinPrivacyAnalysis.addressReuse(activity: [f(a, "t1", 100), s(a, "t2", 100)]).isEmpty)635        #expect(BitcoinPrivacyAnalysis.addressReuse(activity: [f(a, "t1", nil), s(a, "t2", nil)]).isEmpty)636        // several scripts at once: only the reused ones, in a stable order637        let all = [f(a, "t1", 100), s(a, "t2", 105), f(c, "t1", 100), s(c, "t2", 105), f(c, "t9", 110), f(b, "t1", 100), f(b, "t3", 101)]638        let mixed = BitcoinPrivacyAnalysis.addressReuse(activity: all)639        #expect(mixed.map(\.scriptPubKey) == [b, c])640        #expect(BitcoinPrivacyAnalysis.addressReuse(activity: all.reversed()) == mixed)641        #expect(BitcoinPrivacyAnalysis.isReused(scriptPubKey: c, activity: all) && !BitcoinPrivacyAnalysis.isReused(scriptPubKey: a, activity: all))642        #expect(BitcoinPrivacyAnalysis.addressReuse(activity: []).isEmpty)643    }644}645
Files main
Menu

Theme