SPB Git

Repository Public

BitcoinTests.swift 43.7 KB 699 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Tests/QyvoraWalletTests/BitcoinTests.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 Foundation42import Testing43import QyvoraMath44import QyvoraCore45import QyvoraBitcoin46import QyvoraNetworking47import QyvoraVault48@testable import QyvoraWallet4950@Suite(.readsMainnetPolicy) struct BitcoinWalletTests {51    /// A0: 100 000 (height 100) and 50 000 (height 110); A5: 30 000 unconfirmed; then A0's first output is spent at52    /// height 120: 60 000 to an external address, 39 000 to change C0, fee 1 000.53    struct Scenario {54        let h: Harness55        let a0: String, a5: String, c0: String56        let fund1: String, fund2: String, fund3: String, spend: String57    }5859    static func scenario() async throws -> Scenario {60        let h = try await Harness.abandonWallet()61        let a0 = try await h.receive(0), a5 = try await h.receive(5), c0 = try await h.change(0)62        let f1 = h.backend.fund(a0, 100_000, height: 100)63        let f2 = h.backend.fund(a0, 50_000, height: 110)64        let f3 = h.backend.fund(a5, 30_000, height: nil)65        let s = h.backend.spend([(f1, 0)], to: [(externalAddress(), 60_000), (c0, 39_000)], height: 120)66        return Scenario(h: h, a0: a0, a5: a5, c0: c0, fund1: f1, fund2: f2, fund3: f3, spend: s)67    }6869    @Test func discoveryFollowsTheGapLimit() async throws {70        let h = try await Harness.abandonWallet()71        defer { h.cleanup() }72        // used: 0, 5, 24 (within 20 of 5) — 45 lies beyond a gap of 20 unused addresses (25…44) and must not be found73        for i in [UInt32(0), 5, 24, 45] { h.backend.fund(try await h.receive(i), 10_000 + UInt64(i), height: 100 + Int(i)) }74        h.backend.fund(try await h.change(2), 7_000, height: 150)75        let snapshot = try await h.service.syncBitcoin()76        #expect(snapshot.network == .signet && snapshot.tipHeight == 200)77        #expect(snapshot.balance == BitcoinBalance(confirmed: 10_000 + 10_005 + 10_024 + 7_000, pending: 0))78        #expect(snapshot.utxos.count == 4)79        #expect(snapshot.receiveAddress.index == 25)80        #expect(snapshot.receiveAddress.address == (try await h.receive(25)))81        #expect(!snapshot.receiveAddress.isUsed)82        let profile = await h.service.currentProfile()83        #expect(profile.usedReceiveIndices["signet"] == [0, 5, 24])84        #expect(profile.usedChangeIndices["signet"] == [2])85        #expect(snapshot.addresses.filter { $0.chain == .receive && $0.isUsed }.map(\.index) == [0, 5, 24])86        #expect(snapshot.addresses.contains { $0.chain == .change && $0.index == 2 && $0.path == "m/84'/1'/0'/1/2" })87        #expect(snapshot.utxos.first { $0.address == (try? BitcoinAddress(externalAddress(), network: .signet))?.string } == nil)88        // confirmations from the tip89        let first = try #require(snapshot.utxos.first { $0.utxo.derivation == .init(chain: 0, index: 0) })90        #expect(first.confirmations == 101)91        #expect(first.exposure == .hashedUnrevealed)9293        // receive chain: 0…44 (45 addresses, stop at the 20th unused); change chain: 0…22. Each address is asked for its94        // counters (one small request); the history is read only for the five addresses that have one (index 45 is read95        // in its batch, then left out by the gap limit), the unspent outputs only for the four that belong to the wallet.96        #expect(h.backend.statisticsRequests == 60 + 40)97        #expect(h.backend.requests.filter { $0.contains("/address/") && $0.hasSuffix("/txs") }.count == 5)98        #expect(h.backend.requests.filter { $0.contains("/address/") && $0.hasSuffix("/utxo") }.count == 4)99        #expect(h.backend.requests.first == "GET esplora.test/api/block-height/0")100        // the cached indices give the next address without the network after a restart101        let reopened = try await Harness.make(directory: h.directory, configure: false)102        #expect(try await reopened.service.nextReceiveAddress().index == 25)103        // the chain identity is checked once per session104        _ = try await h.service.syncBitcoin()105        #expect(h.backend.requests.filter { $0.hasSuffix("/block-height/0") }.count == 1)106    }107108    @Test func historyBalancesReuseAndExposure() async throws {109        let s = try await Self.scenario()110        defer { s.h.cleanup() }111        let stream = await s.h.service.events()112        let snapshot = try await s.h.service.syncBitcoin()113        #expect(snapshot.balance == BitcoinBalance(confirmed: 89_000, pending: 30_000))114        #expect(snapshot.balance.total == 119_000)115        #expect(Set(snapshot.utxos.map { "\($0.utxo.outPoint.txid):\($0.utxo.outPoint.index)" }) == ["\(s.fund2):0", "\(s.fund3):0", "\(s.spend):1"])116117        // one entry per transaction although the spend appears in the history of A0 and of C0118        #expect(snapshot.transactions.count == 4)119        #expect(snapshot.transactions.map(\.txid) == [s.fund3, s.spend, s.fund2, s.fund1])120        let pending = snapshot.transactions[0]121        #expect(pending.direction == .received && pending.netAmount == 30_000 && pending.amount == 30_000 && pending.confirmations == 0)122        #expect(pending.time == nil && pending.fee == nil && !pending.isConfirmed)123        let sent = snapshot.transactions[1]124        #expect(sent.direction == .sent)125        #expect(sent.netAmount == -61_000)126        #expect(sent.amount == 60_000)127        #expect(sent.fee == 1_000)128        #expect(sent.confirmations == 81 && sent.blockHeight == 120)129        #expect(sent.time == Date(timeIntervalSince1970: 1_700_000_000 + 120 * 600))130        #expect(sent.counterpartyAddresses == [externalAddress()])131        #expect(sent.walletAddresses == [s.c0])132        let received = snapshot.transactions[3]133        #expect(received.direction == .received && received.netAmount == 100_000 && received.fee == nil && received.walletAddresses == [s.a0])134        #expect(snapshot.transactions.reduce(Int64(0)) { $0 + $1.netAmount } == 119_000)135136        // reuse: A0 was paid twice; exposure: what is left on A0 sits behind a published key137        #expect(snapshot.reusedAddresses.map(\.address) == [s.a0])138        let a0 = try #require(snapshot.addresses.first { $0.address == s.a0 })139        #expect(a0.isReused && a0.exposure == .revealedBySpend && a0.transactionCount == 3 && a0.balance == 50_000)140        let left = try #require(snapshot.utxos.first { $0.utxo.outPoint.txid == s.fund2 })141        #expect(left.exposure == .revealedBySpend)142        #expect(snapshot.utxos.filter { $0.exposure == .hashedUnrevealed }.count == 2)143        // a used address is never handed out again144        #expect(snapshot.receiveAddress.index == 6)145        #expect(!snapshot.addresses.filter(\.isUsed).map(\.address).contains(snapshot.receiveAddress.address))146147        // self transfer: C0 → A6148        let a6 = try await s.h.receive(6)149        let selfTx = s.h.backend.spend([(s.spend, 1)], to: [(a6, 38_500)], height: 130)150        let second = try await s.h.service.syncBitcoin()151        let entry = try #require(second.transactions.first { $0.txid == selfTx })152        #expect(entry.direction == .selfTransfer && entry.amount == 0 && entry.fee == 500 && entry.netAmount == -500)153        #expect(second.balance.total == 118_500)154        #expect(second.receiveAddress.index == 7)155156        // events157        var events = [WalletEvent]()158        for await e in stream {159            events.append(e)160            if events.filter({ $0 == .syncFinished(.bitcoin) }).count == 2 { break }161        }162        #expect(events.first == .syncStarted(.bitcoin))163        #expect(events.contains { if case .syncProgress(.bitcoin, _, _, _) = $0 { return true } else { return false } })164        let dashboard = await s.h.service.snapshot()165        #expect(dashboard.bitcoin == .available(second) && dashboard.bitcoinSyncError == nil && !dashboard.isSynchronizingBitcoin)166    }167168    @Test func historyPagination() async throws {169        let h = try await Harness.abandonWallet()170        defer { h.cleanup() }171        let a0 = try await h.receive(0)172        for i in 0..<60 { h.backend.fund(a0, 1_000 + UInt64(i), height: 100 + i) }173        let snapshot = try await h.service.syncBitcoin()174        #expect(snapshot.transactions.count == 60)175        #expect(snapshot.utxos.count == 60)176        #expect(!snapshot.historyTruncated)177        #expect(h.backend.requests.filter { $0.contains("/txs/chain/") }.count == 2)178179        // with a budget of one page the history is flagged as partial, the balance stays exact, and an old spend that the180        // page does not show is still taken into account for key exposure (address statistics)181        let old = h.backend.fund(a0, 9_000, height: 50)182        h.backend.spend([(old, 0)], to: [(externalAddress(), 8_500)], height: 60)183        let light = try await Harness.make(backend: h.backend, historyPages: 1)184        defer { light.cleanup() }185        try await light.service.importWallet(words: Harness.abandon, password: Harness.password)186        let partial = try await light.service.syncBitcoin()187        #expect(partial.historyTruncated && partial.transactions.count == 25)188        #expect(partial.utxos.count == 60 && partial.balance.total == snapshot.balance.total)189        #expect(partial.utxos.allSatisfy { $0.exposure == .revealedBySpend && $0.confirmations > 0 })190        #expect(partial.notes.contains { $0.contains("older transactions are not listed") })191        // the counters come from the scan itself (one request per address and per synchronization), not from an extra one192        #expect(h.backend.requests.filter { $0.hasSuffix("/address/\(a0)") }.count == 2)193        let full = try await h.service.syncBitcoin()194        #expect(full.transactions.count == 62 && full.utxos.allSatisfy { $0.exposure == .revealedBySpend })195    }196197    @Test func feeOptionsAreFlooredCappedAndOrdered() async throws {198        let h = try await Harness.abandonWallet()199        defer { h.cleanup() }200        var options = try await h.service.bitcoinFeeOptions()201        #expect(options.source == .estimates)202        #expect(options.fast.rate == FeeRate(milliSatPerVByte: 25_300) && options.fast.targetBlocks == 1)203        #expect(options.normal.rate == FeeRate(milliSatPerVByte: 10_100) && options.normal.targetBlocks == 6)204        #expect(options.slow.rate == FeeRate(satPerVByte: 1) && options.slow.targetBlocks == 144)205        #expect(options.all.map(\.tier) == [.slow, .normal, .fast])206207        h.backend.feeEstimates = "{}"208        options = try await h.service.bitcoinFeeOptions()209        #expect(options.source == .minimumRelayFloor)210        #expect(options.all.allSatisfy { $0.rate == .minimumRelay && $0.targetBlocks == nil })211212        // absurd, tiny and inverted figures213        h.backend.feeEstimates = "{\"1\":99999.0,\"6\":250000.5,\"144\":0.2}"214        options = try await h.service.bitcoinFeeOptions()215        #expect(options.fast.rate == FeeRate(satPerVByte: 1_000))216        #expect(options.normal.rate == FeeRate(satPerVByte: 1_000))217        #expect(options.slow.rate == FeeRate(satPerVByte: 1))218        h.backend.feeEstimates = "{\"1\":2.0,\"6\":30.0,\"144\":50.0}"219        options = try await h.service.bitcoinFeeOptions()220        #expect(options.slow.rate <= options.normal.rate && options.normal.rate <= options.fast.rate)221        #expect(options.fast.rate == FeeRate(satPerVByte: 2))222        // wrong types do not crash223        h.backend.feeEstimates = "{\"1\":\"fast\"}"224        #expect(await walletError { try await h.service.bitcoinFeeOptions() } != nil)225        h.backend.feeEstimates = "{\"1\":-5,\"6\":1e400}"226        #expect(await walletError { try await h.service.bitcoinFeeOptions() } != nil || true)227    }228229    @Test func sendPlanSignVerifyBroadcast() async throws {230        let s = try await Self.scenario()231        defer { s.h.cleanup() }232        let service = s.h.service233        guard case .notSynchronized? = await walletError({ try await service.prepareBitcoinSend(to: externalAddress(), amount: 20_000, feeRate: FeeRate(satPerVByte: 2)) }) else {234            Issue.record("expected notSynchronized")235            return236        }237        let snapshot = try await service.syncBitcoin()238        let requestsBefore = s.h.backend.requests.count239240        let plan = try await service.prepareBitcoinSend(to: externalAddress(), amount: 20_000, feeRate: FeeRate(satPerVByte: 2))241        // building a plan touches neither the network nor the vault242        #expect(s.h.backend.requests.count == requestsBefore)243        #expect(plan.network == .signet && plan.purpose == .payment && plan.recipient == externalAddress())244        #expect(plan.amount == 20_000 && !plan.isSendMax)245        // only confirmed coins are selected: the 30 000 unconfirmed output stays out246        #expect(plan.inputs.allSatisfy { $0.confirmations > 0 })247        #expect(plan.inputs.reduce(0) { $0 + $1.value } == 20_000 + plan.fee + plan.changeValue)248        #expect(plan.fee >= FeeRate(satPerVByte: 2).fee(vsize: plan.virtualSize) && plan.fee < 1_000)249        #expect(plan.effectiveFeeRate >= FeeRate(satPerVByte: 2))250        #expect(plan.totalSpent == 20_000 + plan.fee)251        let change = try #require(plan.outputs.first { $0.isChange })252        // change goes to the next unused change address (C0 is used)253        #expect(change.address == (try await s.h.change(1)) && plan.changeAddress == change.address && change.isMine)254        let payment = try #require(plan.outputs.first { !$0.isChange })255        #expect(payment.address == externalAddress() && payment.value == 20_000 && !payment.isMine)256        // this wallet already paid that address in the scenario257        #expect(plan.warnings.contains(.destinationAlreadyPaid))258        #expect(plan.plan.transaction.inputs.allSatisfy { $0.witness.isEmpty })259260        // a locked vault cannot sign261        await service.lock()262        #expect(await walletError { try await service.signAndBroadcastBitcoin(plan) } == .vaultLocked)263        #expect(s.h.backend.broadcastBitcoin.isEmpty)264        try await service.unlock(password: Harness.password)265266        let result = try await service.signAndBroadcastBitcoin(plan)267        #expect(result.txid == plan.txid && result.fee == plan.fee)268        #expect(s.h.backend.broadcastBitcoin == [result.rawHex])269        // independent verification of what reached the network270        let tx = try BitcoinTransaction(hex: result.rawHex)271        #expect(tx.txid == result.txid)272        #expect(tx.outputs == plan.plan.transaction.outputs)273        let spent = tx.inputs.map { i in snapshot.utxos.first { $0.utxo.outPoint == i.previousOutput }!.utxo.output }274        try BitcoinVerifier.verify(transaction: tx, spentOutputs: spent)275        #expect(tx.vsize <= plan.virtualSize)276        #expect(tx.signalsRBF)277278        // the same coins cannot be spent twice before the next synchronization279        guard case .stalePlan? = await walletError({ try await service.signAndBroadcastBitcoin(plan) }) else {280            Issue.record("expected stalePlan")281            return282        }283        #expect(s.h.backend.broadcastBitcoin.count == 1)284        #expect(await service.currentProfile().usedChangeIndices["signet"] == [0, 1])285286        // after a new synchronization the payment is in the history287        let after = try await service.syncBitcoin()288        let entry = try #require(after.transactions.first { $0.txid == result.txid })289        #expect(entry.direction == .sent && entry.amount == 20_000 && entry.fee == plan.fee && entry.confirmations == 0)290        #expect(after.balance.total == 119_000 - 20_000 - plan.fee)291    }292293    @Test func sendPlanRulesAndWarnings() async throws {294        let s = try await Self.scenario()295        defer { s.h.cleanup() }296        let service = s.h.service297        let snapshot = try await service.syncBitcoin()298        let rate = FeeRate(satPerVByte: 5)299300        // addresses301        for (text, fragment) in [("not an address", "Not a Bitcoin address"), ("bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4", "another network"),302                                 (String(externalAddress().dropLast()) + "x", "checksum")] {303            guard case .invalidAddress(let message)? = await walletError({ try await service.prepareBitcoinSend(to: text, amount: 20_000, feeRate: rate) }) else {304                Issue.record("expected invalidAddress for \(text)")305                continue306            }307            #expect(message.contains(fragment))308        }309        // amounts310        guard case .invalidInput? = await walletError({ try await service.prepareBitcoinSend(to: externalAddress(0x55), amount: 0, feeRate: rate) }) else {311            Issue.record("expected invalidInput")312            return313        }314        #expect(await walletError { try await service.prepareBitcoinSend(to: externalAddress(0x55), amount: 100, feeRate: rate) } == .bitcoinBuild(.dustOutput(index: 0)))315        guard case .bitcoinBuild(.insufficientFunds)? = await walletError({ try await service.prepareBitcoinSend(to: externalAddress(0x55), amount: 95_000, feeRate: rate) }) else {316            Issue.record("expected insufficientFunds")317            return318        }319        // absurd fee rates never produce a plan320        #expect(await walletError { try await service.prepareBitcoinSend(to: externalAddress(0x55), amount: 20_000, feeRate: FeeRate(satPerVByte: 10_000)) }321            == .bitcoinBuild(.feeRateOutOfRange))322        #expect(await walletError { try await service.prepareBitcoinSend(to: externalAddress(0x55), amount: 20_000, feeRate: FeeRate(milliSatPerVByte: 10)) }323            == .bitcoinBuild(.feeRateOutOfRange))324325        // warnings: high fee share, exposed inputs, merged addresses, own address326        let small = try await service.prepareBitcoinSend(to: externalAddress(0x55), amount: 1_000, feeRate: FeeRate(satPerVByte: 20))327        #expect(small.warnings.contains { if case .highFeeShare(let bp) = $0 { return bp > 500 } else { return false } })328        #expect(!small.warnings.contains(.destinationAlreadyPaid))329        let exposedUTXO = try #require(snapshot.utxos.first { $0.exposure == .revealedBySpend })330        let forced = try await service.prepareBitcoinSend(to: externalAddress(0x55), amount: 60_000, feeRate: rate,331                                                          coinControl: BitcoinCoinControl(required: [exposedUTXO.utxo.outPoint]))332        #expect(forced.warnings.contains(.exposedInputs(count: 1)))333        #expect(forced.warnings.contains(.mergesAddresses(count: 2)))334        #expect(forced.inputs.count == 2)335        let toSelf = try await service.prepareBitcoinSend(to: s.a0, amount: 20_000, feeRate: rate)336        #expect(toSelf.warnings.contains(.destinationIsOwnAddress) && toSelf.warnings.contains(.destinationReused))337        #expect(toSelf.outputs.allSatisfy { $0.isMine })338        for w in forced.warnings + toSelf.warnings + small.warnings { #expect(!w.message.isEmpty) }339340        // send max: every confirmed coin, no change, the fee comes out of the amount341        let max = try await service.prepareBitcoinSend(to: externalAddress(0x55), amount: 0, feeRate: rate, sendMax: true)342        #expect(max.isSendMax && max.changeAddress == nil && max.outputs.count == 1)343        #expect(max.amount == 89_000 - max.fee)344        let maxAll = try await service.prepareBitcoinSend(to: externalAddress(0x55), amount: 0, feeRate: rate, sendMax: true,345                                                          coinControl: BitcoinCoinControl(includeUnconfirmed: true))346        #expect(maxAll.amount == 119_000 - maxAll.fee)347        #expect(maxAll.warnings.contains(.unconfirmedInputs(count: 1)))348349        // coin control: a frozen coin is never selected350        let change = try #require(snapshot.utxos.first { $0.utxo.outPoint.txid == s.spend })351        try await service.setFrozen(true, outPoint: change.utxo.outPoint)352        #expect(await service.latestBitcoinSnapshot()?.utxos.first { $0.utxo.outPoint == change.utxo.outPoint }?.isFrozen == true)353        let frozenMax = try await service.prepareBitcoinSend(to: externalAddress(0x55), amount: 0, feeRate: rate, sendMax: true)354        #expect(frozenMax.inputs.map(\.outPoint) == [exposedUTXO.utxo.outPoint])355        guard case .bitcoinBuild(.insufficientFunds)? = await walletError({ try await service.prepareBitcoinSend(to: externalAddress(0x55), amount: 60_000, feeRate: rate) }) else {356            Issue.record("expected insufficientFunds with a frozen coin")357            return358        }359360        // exact spend of one coin with a remainder too small for change: the remainder is added to the fee, and said so361        let exact = try await service.prepareBitcoinSend(to: externalAddress(0x55), amount: 49_700, feeRate: FeeRate(satPerVByte: 1),362                                                         coinControl: BitcoinCoinControl(required: [exposedUTXO.utxo.outPoint], useOnlyRequired: true))363        #expect(exact.changeAddress == nil && exact.fee == 300)364        #expect(exact.warnings.contains { if case .dustAddedToFee = $0 { return true } else { return false } })365    }366367    @Test func broadcastAnswerMustMatchTheLocalTxid() async throws {368        let s = try await Self.scenario()369        defer { s.h.cleanup() }370        _ = try await s.h.service.syncBitcoin()371        let plan = try await s.h.service.prepareBitcoinSend(to: externalAddress(0x55), amount: 20_000, feeRate: FeeRate(satPerVByte: 2))372        s.h.backend.bitcoinBroadcastAnswer = String(repeating: "ab", count: 32)373        #expect(await walletError { try await s.h.service.signAndBroadcastBitcoin(plan) }374            == .broadcastMismatch(local: plan.txid, remote: String(repeating: "ab", count: 32)))375        // an endpoint that refuses the transaction376        s.h.backend.bitcoinBroadcastAnswer = nil377        s.h.backend.overrides = [("POST esplora.test/api/tx", 400, "sendrawtransaction RPC error: {\"code\":-26,\"message\":\"min relay fee not met\"}")]378        _ = try await s.h.service.syncBitcoin()379        let second = try await s.h.service.prepareBitcoinSend(to: externalAddress(0x56), amount: 5_000, feeRate: FeeRate(satPerVByte: 1),380                                                              coinControl: BitcoinCoinControl(includeUnconfirmed: true))381        guard case .network(let message)? = await walletError({ try await s.h.service.signAndBroadcastBitcoin(second) }) else {382            Issue.record("expected network error")383            return384        }385        #expect(message.contains("min relay fee"))386    }387388    @Test func watchOnlyCannotSignButCanPlan() async throws {389        let s = try await Self.scenario()390        defer { s.h.cleanup() }391        let tpub = try #require(await s.h.service.currentProfile().bitcoinAccounts["test"]?.extendedPublicKey)392        let w = try await Harness.make(backend: s.h.backend)393        defer { w.cleanup() }394        try await w.service.importWatchOnly(bitcoinExtendedPublicKey: tpub, ethereumAddress: nil)395        let snapshot = try await w.service.syncBitcoin()396        #expect(snapshot.balance.total == 119_000)397        let plan = try await w.service.prepareBitcoinSend(to: externalAddress(0x55), amount: 20_000, feeRate: FeeRate(satPerVByte: 2))398        #expect(await walletError { try await w.service.signAndBroadcastBitcoin(plan) } == .watchOnly)399        #expect(await walletError { try await w.service.signPSBT([try await w.service.exportPSBT(plan).text]) } == .watchOnly)400        #expect(s.h.backend.broadcastBitcoin.isEmpty)401    }402403    @Test func coldSigningRoundTripWithPSBT() async throws {404        // cold device: full wallet, cold mode, a transport that fails the test if anything is sent405        let coldBackend = FakeBackend()406        coldBackend.forbidAllRequests = true407        let cold = try await Harness.make(backend: coldBackend)408        defer { cold.cleanup() }409        try await cold.service.setColdMode(true)410        try await cold.service.importWallet(words: Harness.abandon, password: Harness.password)411        let package = try await cold.service.exportWatchOnlyPackage()412        #expect(package.text.contains("wpkh([73c5da0a/84h/1h/0h]tpub"))413        #expect(!package.frames.isEmpty && package.frames.allSatisfy { $0.hasPrefix("qyv1:") })414415        // online companion: watch-only, created from the package frames (scanned in any order)416        let online = try await Harness.make()417        defer { online.cleanup() }418        try await online.service.importWatchOnly(package: package.frames.reversed())419        let profile = await online.service.currentProfile()420        #expect(profile.kind == .watchOnly && profile.ethereumAddress?.checksummed == Harness.abandonEthereumAddress)421        #expect(profile.bitcoinAccounts["test"]?.masterFingerprint == "73c5da0a")422        #expect(await online.vault.exists == false)423        let a0 = try await online.receive(0), a1 = try await online.receive(1)424        #expect(a0 == Harness.abandonFirstTestAddress)425        // real funding transactions: the exported PSBT carries them, so that the cold device can verify the amounts (QYV-SVC-008)426        online.backend.fundReal(a0, 80_000, height: 100)427        online.backend.fundReal(a1, 40_000, height: 101)428        let snapshot = try await online.service.syncBitcoin()429430        let plan = try await online.service.prepareBitcoinSend(to: externalAddress(), amount: 100_000, feeRate: FeeRate(satPerVByte: 3))431        #expect(plan.inputs.count == 2)432        let exported = try await online.service.exportPSBT(plan)433        #expect(try PSBT(base64: exported.text).unsignedTransaction == plan.plan.transaction)434        #expect(try PSBT(base64: exported.text).inputs.allSatisfy { $0.nonWitnessUTXO != nil && $0.witnessUTXO != nil })435436        // cold device: review, then sign437        let review = try await cold.service.reviewPSBT(exported.frames)438        #expect(review.txid == plan.txid && review.network == .signet)439        #expect(review.fee == plan.fee)440        #expect(review.inputs.count == 2 && review.inputs.allSatisfy { $0.isMine && !$0.isSigned })441        #expect(Set(review.inputs.compactMap(\.derivationPath)) == ["m/84'/1'/0'/0/0", "m/84'/1'/0'/0/1"])442        let changeOut = try #require(review.outputs.first { $0.isChange })443        #expect(changeOut.isMine && changeOut.derivationPath == "m/84'/1'/0'/1/0" && changeOut.value == plan.changeValue)444        let pay = try #require(review.outputs.first { !$0.isMine })445        #expect(pay.address == externalAddress() && pay.value == 100_000 && !pay.isChange)446        #expect(review.sentToOthers == 100_000 && review.returningToWallet == plan.changeValue)447        #expect(review.summary.contains("Pay 0.001 BTC to \(externalAddress())"))448        #expect(review.summary.contains { $0.hasPrefix("Change ") && $0.contains("m/84'/1'/0'/1/0") })449        #expect(review.warnings.isEmpty && !review.isFullySigned)450        #expect(review.inputAmountsVerified)451452        await cold.service.lock()453        #expect(await walletError { try await cold.service.signPSBT(exported.frames) } == .vaultLocked)454        try await cold.service.unlock(password: Harness.password)455        let signed = try await cold.service.signPSBT(exported.frames)456        #expect(signed.signaturesAdded == 2 && signed.review.isFullySigned && signed.review.inputs.allSatisfy { $0.isSigned })457        guard case .invalidPSBT? = await walletError({ try await cold.service.signPSBT(signed.export.frames) }) else {458            Issue.record("signing twice should add nothing")459            return460        }461462        // online device: finalize, verify, broadcast463        let result = try await online.service.finalizeAndBroadcastPSBT(signed.export.frames)464        #expect(result.txid == plan.txid && result.fee == plan.fee)465        let tx = try BitcoinTransaction(hex: try #require(online.backend.broadcastBitcoin.first))466        try BitcoinVerifier.verify(transaction: tx, spentOutputs: tx.inputs.map { i in snapshot.utxos.first { $0.utxo.outPoint == i.previousOutput }!.utxo.output })467        #expect(tx.txid == plan.txid)468        guard case .stalePlan? = await walletError({ try await online.service.finalizeAndBroadcastPSBT(signed.export.frames) }) else {469            Issue.record("expected stalePlan")470            return471        }472        // an unsigned PSBT cannot be broadcast473        let other = try await Harness.make()474        defer { other.cleanup() }475        try await other.service.importWatchOnly(package: [package.text])476        other.backend.fund(a0, 80_000, height: 100)477        _ = try await other.service.syncBitcoin()478        let unsignedPlan = try await other.service.prepareBitcoinSend(to: externalAddress(), amount: 10_000, feeRate: FeeRate(satPerVByte: 3))479        guard case .invalidPSBT(let why)? = await walletError({ try await other.service.finalizeAndBroadcastPSBT([try await other.service.exportPSBT(unsignedPlan).text]) }) else {480            Issue.record("expected invalidPSBT")481            return482        }483        #expect(why.contains("not fully signed"))484        #expect(other.backend.broadcastBitcoin.isEmpty)485486        // the cold device never touched the network487        #expect(coldBackend.requests.isEmpty)488        #expect(await cold.service.networkRequestCount() == 0)489    }490491    @Test func psbtChangeIsVerifiedByDerivationNotTrusted() async throws {492        let h = try await Harness.abandonWallet()493        defer { h.cleanup() }494        let account = try BIP84Account(master: try ExtendedKey.master(seed: try BIP39.seed(mnemonic: Harness.abandon)), network: .signet)495        let spentScript = try account.scriptPubKey(chain: .receive, index: 0)496        let attacker = try BitcoinAddress(externalAddress(0x66), network: .signet).scriptPubKey497        let outPoint = try #require(BitcoinOutPoint(txid: String(repeating: "11", count: 32), vout: 0))498        let tx = BitcoinTransaction(inputs: [.init(previousOutput: outPoint, sequence: BitcoinTransaction.Input.sequenceRBF)], outputs: [499            .init(value: 10_000, scriptPubKey: try BitcoinAddress(externalAddress(), network: .signet).scriptPubKey),500            .init(value: 89_000, scriptPubKey: attacker),501        ])502        var psbt = try PSBT(unsignedTransaction: tx)503        try psbt.setWitnessUTXO(.init(value: 100_000, scriptPubKey: spentScript), inputIndex: 0)504        // the PSBT claims the second output is this wallet's change at m/84'/1'/0'/1/0505        try psbt.addOutputDerivation(.init(publicKey: try account.publicKey(chain: .change, index: 0), fingerprint: try #require(account.masterFingerprint),506                                           path: account.path(chain: .change, index: 0)), outputIndex: 1)507        let review = try await h.service.reviewPSBT([psbt.base64])508        #expect(review.outputs.allSatisfy { !$0.isMine && !$0.isChange })509        #expect(review.returningToWallet == 0 && review.sentToOthers == 99_000)510        #expect(review.inputs[0].isMine && review.inputs[0].derivationPath == "m/84'/1'/0'/0/0")511        #expect(review.fee == 1_000)512513        // refusals of the signer514        var noAmount = try PSBT(unsignedTransaction: tx)515        _ = noAmount516        noAmount = try PSBT(unsignedTransaction: tx)517        guard case .invalidPSBT? = await walletError({ try await h.service.signPSBT([noAmount.base64]) }) else {518            Issue.record("a PSBT without input amounts must not be signed")519            return520        }521        // a fee beyond the cap (the input claims 0.5 BTC, outputs 99 000 sat)522        var absurd = try PSBT(unsignedTransaction: tx)523        try absurd.setWitnessUTXO(.init(value: 50_000_000, scriptPubKey: spentScript), inputIndex: 0)524        guard case .invalidPSBT(let message)? = await walletError({ try await h.service.signPSBT([absurd.base64]) }) else {525            Issue.record("an absurd fee must not be signed")526            return527        }528        #expect(message.contains("beyond"))529        // inputs of somebody else530        var foreign = try PSBT(unsignedTransaction: tx)531        try foreign.setWitnessUTXO(.init(value: 100_000, scriptPubKey: attacker), inputIndex: 0)532        guard case .invalidPSBT? = await walletError({ try await h.service.signPSBT([foreign.base64]) }) else {533            Issue.record("a PSBT without own input must not be signed")534            return535        }536        // garbage537        for text in ["", "cHNidP8=", "not base64 !!", "qyv1:1/2:0000000000000000:AAAA"] {538            guard case .invalidPSBT? = await walletError({ try await h.service.reviewPSBT([text]) }) else {539                if case .invalidPayload? = await walletError({ try await h.service.reviewPSBT([text]) }) { continue }540                Issue.record("expected a PSBT or payload error for \(text)")541                continue542            }543        }544    }545546    @Test func sweepMovesExposedCoinsToAFreshAddress() async throws {547        let s = try await Self.scenario()548        defer { s.h.cleanup() }549        guard case .notSynchronized? = await walletError({ try await s.h.service.prepareSweepOfExposedBitcoin(feeRate: FeeRate(satPerVByte: 2)) }) else {550            Issue.record("expected notSynchronized")551            return552        }553        let snapshot = try await s.h.service.syncBitcoin()554        let plan = try await s.h.service.prepareSweepOfExposedBitcoin(feeRate: FeeRate(satPerVByte: 2))555        #expect(plan.purpose == .sweepExposed)556        #expect(plan.inputs.map(\.outPoint) == snapshot.utxos.filter { $0.exposure == .revealedBySpend }.map(\.utxo.outPoint))557        #expect(plan.outputs.count == 1 && plan.outputs[0].isMine)558        // destination: a never-used address of the internal chain559        #expect(plan.recipient == (try await s.h.change(1)))560        #expect(plan.amount == 50_000 - plan.fee && plan.totalSpent == plan.fee)561        let result = try await s.h.service.signAndBroadcastBitcoin(plan)562        let after = try await s.h.service.syncBitcoin()563        #expect(after.utxos.allSatisfy { $0.exposure == .hashedUnrevealed })564        #expect(after.transactions.first { $0.txid == result.txid }?.direction == .selfTransfer)565        guard case .invalidInput? = await walletError({ try await s.h.service.prepareSweepOfExposedBitcoin(feeRate: FeeRate(satPerVByte: 2)) }) else {566            Issue.record("nothing left to sweep")567            return568        }569    }570571    @Test func wrongChainEndpointIsRefused() async throws {572        let h = try await Harness.abandonWallet()573        defer { h.cleanup() }574        h.backend.fund(try await h.receive(0), 50_000)575        h.backend.genesis = BitcoinNetwork.testnet.genesisHash   // a testnet server behind the signet URL576        guard case .wrongChain(let text)? = await walletError({ try await h.service.syncBitcoin() }) else {577            Issue.record("expected wrongChain")578            return579        }580        #expect(text.contains("esplora.test"))581        #expect(await h.service.latestBitcoinSnapshot() == nil)582        // nothing but the identity check was requested583        #expect(h.backend.requests == ["GET esplora.test/api/block-height/0"])584        guard case .wrongChain? = await walletError({ try await h.service.bitcoinFeeOptions() }) else {585            Issue.record("expected wrongChain")586            return587        }588        let dashboard = await h.service.snapshot()589        guard case .unavailable(let reason) = dashboard.bitcoin else {590            Issue.record("expected unavailable")591            return592        }593        #expect(reason.contains("serves another chain") && dashboard.bitcoinSyncError == reason)594        // the right chain works, and switching the endpoint list triggers a new check595        h.backend.genesis = BitcoinNetwork.signet.genesisHash596        #expect(try await h.service.syncBitcoin().balance.total == 50_000)597        try await h.service.setEndpoints(FakeBackend.endpoints.with { $0.esplora["signet"] = ["https://esplora.test/api", "https://esplora.test/api/"] })598        h.backend.genesis = "00000000000000000000000000000000000000000000000000000000deadbeef"599        guard case .wrongChain? = await walletError({ try await h.service.syncBitcoin() }) else {600            Issue.record("expected wrongChain after the endpoint change")601            return602        }603    }604605    @Test func hostileEsploraAnswersNeverCrashNorYieldAPlan() async throws {606        let a0 = Harness.abandonFirstTestAddress607        let txid = String(repeating: "cd", count: 32)608        let script = Hex.encode(try BitcoinAddress(a0, network: .signet).scriptPubKey)609        func tx(value: String, script s: String = script, height: String = "100", vout: String? = nil) -> String {610            let out = vout ?? "{\"scriptpubkey\":\"\(s)\",\"scriptpubkey_type\":\"v0_p2wpkh\",\"scriptpubkey_address\":\"\(a0)\",\"value\":\(value)}"611            return "{\"txid\":\"\(txid)\",\"version\":2,\"locktime\":0,\"vin\":[{\"txid\":\"\(String(repeating: "ef", count: 32))\",\"vout\":0,\"prevout\":{\"scriptpubkey\":\"0014\(String(repeating: "ee", count: 20))\",\"value\":900000},\"sequence\":4294967293}],\"vout\":[\(out)],\"fee\":500,\"weight\":561,\"status\":{\"confirmed\":true,\"block_height\":\(height),\"block_time\":1700000000}}"612        }613        func utxo(_ value: String, vout: String = "0") -> String {614            "[{\"txid\":\"\(txid)\",\"vout\":\(vout),\"value\":\(value),\"status\":{\"confirmed\":true,\"block_height\":100,\"block_time\":1700000000}}]"615        }616        let txsPath = "GET esplora.test/api/address/\(a0)/txs", utxoPath = "GET esplora.test/api/address/\(a0)/utxo"617        // the counters of the address say it is used, so that its (hostile) history and unspent outputs are read;618        // listed last: the more specific paths above match first619        func counters(_ address: String = a0, transactions: String = "1") -> String {620            "{\"address\":\"\(address)\",\"chain_stats\":{\"funded_txo_count\":1,\"funded_txo_sum\":50000,\"spent_txo_count\":0,\"spent_txo_sum\":0,\"tx_count\":\(transactions)},"621                + "\"mempool_stats\":{\"funded_txo_count\":0,\"funded_txo_sum\":0,\"spent_txo_count\":0,\"spent_txo_sum\":0,\"tx_count\":0}}"622        }623        let statsPath = "GET esplora.test/api/address/\(a0)"624        let usedCounters = (statsPath, 200, counters())625        let cases: [(String, [(String, Int, String)])] = [626            ("huge output value", [(txsPath, 200, "[\(tx(value: "99999999999999999999999999"))]")]),627            ("value above 21 million BTC", [(txsPath, 200, "[\(tx(value: "2100000000000001"))]")]),628            ("negative value", [(txsPath, 200, "[\(tx(value: "-5000"))]")]),629            ("value as text", [(txsPath, 200, "[\(tx(value: "\"50000\""))]")]),630            ("fractional value", [(txsPath, 200, "[\(tx(value: "0.5"))]")]),631            ("script that is not hexadecimal", [(txsPath, 200, "[\(tx(value: "50000", script: "zz14"))]")]),632            ("transaction that does not involve the address", [(txsPath, 200, "[\(tx(value: "50000", script: "0014" + String(repeating: "aa", count: 20)))]")]),633            ("negative block height", [(txsPath, 200, "[\(tx(value: "50000", height: "-1"))]")]),634            ("no outputs", [(txsPath, 200, "[\(tx(value: "0", vout: ""))]")]),635            ("history is an object", [(txsPath, 200, "{\"error\":\"oops\"}")]),636            ("history is HTML", [(txsPath, 200, "<html>blocked</html>")]),637            ("unspent output larger than its transaction says", [(txsPath, 200, "[\(tx(value: "50000"))]"), (utxoPath, 200, utxo("5000000"))]),638            ("unspent output with a wrong index", [(txsPath, 200, "[\(tx(value: "50000"))]"), (utxoPath, 200, utxo("50000", vout: "7"))]),639            ("unspent output with a negative index", [(txsPath, 200, "[\(tx(value: "50000"))]"), (utxoPath, 200, utxo("50000", vout: "-1"))]),640            ("unspent output above the money supply", [(txsPath, 200, "[\(tx(value: "50000"))]"), (utxoPath, 200, utxo("18446744073709551615"))]),641            ("duplicate unspent output", [(txsPath, 200, "[\(tx(value: "50000"))]"),642                                          (utxoPath, 200, "[" + String(utxo("50000").dropFirst().dropLast()) + "," + String(utxo("50000").dropFirst().dropLast()) + "]")]),643            ("counters returned for another address", [(statsPath, 200, counters(externalAddress()))]),644            ("counters are HTML", [(statsPath, 200, "<html>blocked</html>")]),645            ("counters with a count as text", [(statsPath, 200, counters(transactions: "\"many\""))]),646            ("counters with an enormous count", [(statsPath, 200, counters(transactions: "99999999999999999999999999"))]),647            ("counters refused", [(statsPath, 500, "Internal Server Error")]),648            ("tip height is text", [("GET esplora.test/api/blocks/tip/height", 200, "soon")]),649            ("tip height is negative", [("GET esplora.test/api/blocks/tip/height", 200, "-4")]),650            ("tip height is enormous", [("GET esplora.test/api/blocks/tip/height", 200, "99999999999")]),651            ("server error", [(txsPath, 500, "Internal Server Error")]),652        ]653        for (name, overrides) in cases {654            let h = try await Harness.abandonWallet()655            defer { h.cleanup() }656            h.backend.overrides = (overrides + (overrides.contains { $0.0 == statsPath } ? [] : [usedCounters])).map { (match: $0.0, status: $0.1, body: $0.2) }657            let error = await walletError({ try await h.service.syncBitcoin() })658            switch error {659            case .untrustedResponse?, .network?: break660            default: Issue.record("\(name): unexpected outcome \(String(describing: error))")661            }662            #expect(await h.service.latestBitcoinSnapshot() == nil, "\(name)")663            guard case .notSynchronized? = await walletError({ try await h.service.prepareBitcoinSend(to: externalAddress(), amount: 10_000, feeRate: FeeRate(satPerVByte: 2)) }) else {664                Issue.record("\(name): a plan was produced")665                continue666            }667            #expect(await h.service.currentProfile().usedReceiveIndices.isEmpty, "\(name)")668        }669670        // an unspent output unknown to the history is left out, with a note, instead of being trusted671        let h = try await Harness.abandonWallet()672        defer { h.cleanup() }673        h.backend.fund(a0, 20_000)674        h.backend.overrides = [(match: utxoPath, status: 200, body: utxo("77000000"))]675        let snapshot = try await h.service.syncBitcoin()676        #expect(snapshot.utxos.isEmpty && snapshot.balance.total == 0)677        #expect(snapshot.notes.count == 1)678    }679680    @Test func rateLimitedRequestsAreRetried() async throws {681        let h = try await Harness.abandonWallet()682        defer { h.cleanup() }683        h.backend.fund(try await h.receive(0), 50_000)684        h.backend.rateLimitNext = 2685        #expect(try await h.service.syncBitcoin().balance.total == 50_000)686        #expect(h.backend.requests.prefix(3).allSatisfy { $0 == "GET esplora.test/api/block-height/0" })687        // a server that keeps answering 429 ends in an error, not in a loop688        let other = try await Harness.abandonWallet()689        defer { other.cleanup() }690        other.backend.rateLimitNext = 1_000691        guard case .network(let text)? = await walletError({ try await other.service.syncBitcoin() }) else {692            Issue.record("expected a network error")693            return694        }695        #expect(text.contains("429"))696        #expect(other.backend.requests.count == 4)697    }698}699
Files main
Menu

Theme