Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Tests/QyvoraWalletTests/UTXOCoinsAuditRegressionTests.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 QyvoraCore45@testable import QyvoraBitcoin46import QyvoraNetworking47@testable import QyvoraWallet4849/// Multi-chain security audit, UTXO coins in the wallet service: the ceilings of an unaudited build hold at prepare50/// and at sign on Litecoin, Dogecoin and Bitcoin Cash even when the plan object is altered (which only code inside51/// the module can do: `BitcoinSendPlan` and `BitcoinTransactionPlan` have no public initializer and no mutable52/// property); a lying indexer cannot make the wallet pay more fee than it shows (QYV-SVC-062, QYV-SVC-063).53/// In the serialized suite: `MainnetPolicy` is process-wide.54extension MainnetPolicyTests {55 struct CoinCase {56 let chain: ChainID57 let network: BitcoinNetwork58 let address0: String59 let priceID: String60 /// USD per coin: the 150 USD ceiling is then `ceiling` base units.61 let price: String62 let ceiling: UInt6463 let funded: UInt6464 }6566 static let coinCases = [67 CoinCase(chain: .litecoin, network: .litecoin, address0: CoinFixture.litecoin0, priceID: "litecoin", price: "100", ceiling: 150_000_000, funded: 2_000_000_000),68 CoinCase(chain: .dogecoin, network: .dogecoin, address0: CoinFixture.dogecoin0, priceID: "dogecoin", price: "0.5", ceiling: 30_000_000_000, funded: 200_000_000_000),69 CoinCase(chain: .bitcoinCash, network: .bitcoinCash, address0: CoinFixture.bitcoinCash0, priceID: "bitcoin-cash", price: "500", ceiling: 30_000_000, funded: 400_000_000),70 ]7172 /// A plan object rebuilt around another transaction plan, as only code inside the module can make one.73 static func wrap(_ original: BitcoinSendPlan, _ plan: BitcoinTransactionPlan, amount: UInt64? = nil, fee: UInt64? = nil) -> BitcoinSendPlan {74 BitcoinSendPlan(id: UUID(), purpose: original.purpose, network: original.network, createdAt: original.createdAt, plan: plan, recipient: original.recipient,75 amount: amount ?? original.amount, fee: fee ?? plan.fee, virtualSize: plan.estimatedVSize, targetFeeRate: plan.targetFeeRate,76 effectiveFeeRate: plan.effectiveFeeRate, inputs: original.inputs, outputs: original.outputs, changeAddress: original.changeAddress,77 changeValue: plan.changeValue, isSendMax: false, warnings: original.warnings)78 }7980 @Test func coinLimitsHoldAtPrepareAndAtSignEvenWithAnAlteredPlan() async throws {81 for c in Self.coinCases {82 Self.reset()83 defer { Self.reset() }84 let h = try await Self.coinMainnetWallet(c.chain, c.network)85 defer { h.cleanup() }86 h.backend.markets = ServiceTests.market([(c.priceID, c.price)])87 h.backend.fundReal(c.address0, c.funded)88 try await h.service.synchronize(chain: c.chain)89 let limits = try #require(MainnetPolicy.utxoLimits(c.network))90 let recipient = CoinFixture.external(c.network)91 let recipientScript = try BitcoinAddress(recipient, network: c.network).scriptPubKey92 let small = c.ceiling / 109394 // prepare: the value ceiling, exactly at and one unit above95 let review = try await h.service.prepareSend(chain: c.chain, asset: .native, to: recipient, amount: UInt256(small))96 let honest = try CoinFixture.plan(review)97 #expect(review.unauditedMainnet && honest.fee <= limits.feePerTransaction)98 _ = try await h.service.prepareSend(chain: c.chain, asset: .native, to: recipient, amount: UInt256(c.ceiling))99 guard case .exceedsUnauditedLimit? = await walletError({ try await h.service.prepareSend(chain: c.chain, asset: .native, to: recipient, amount: UInt256(c.ceiling + 1)) }) else {100 Issue.record("\(c.network): prepared above the value ceiling")101 continue102 }103 // prepare: a fee rate above the ceiling of the build104 #expect(await walletError { try await h.service.prepareSend(chain: c.chain, asset: .native, to: recipient, amount: UInt256(small),105 options: { var o = SendOptions(); o.bitcoinFeeRate = FeeRate(satPerVByte: limits.feeRatePerVByte + 1); return o }()) }106 == .bitcoinBuild(.feeRateOutOfRange), "\(c.network)")107108 // the same coins, the wallet's own change script109 let coins = honest.plan.inputs110 let changeIndex = try #require(honest.plan.changeIndex)111 let changeScript = honest.plan.transaction.outputs[changeIndex].scriptPubKey112 func build(_ value: UInt64, to script: Bytes, change: Bytes, rate: FeeRate? = nil, maximumFee: UInt64? = nil) throws -> BitcoinTransactionPlan {113 var request = BitcoinSpendRequest(network: c.network, recipients: [.init(value: value, scriptPubKey: script)], utxos: coins,114 feeRate: rate ?? honest.targetFeeRate, changeScript: change)115 request.seed = 7116 if let maximumFee { request.maximumFee = maximumFee }117 return try BitcoinTransactionBuilder.build(request)118 }119 func refusal(_ plan: BitcoinSendPlan) async -> WalletError? {120 let before = h.backend.broadcastBitcoin.count121 let e = await walletError { try await h.service.signAndBroadcast(h.service.review(for: plan)) }122 #expect(h.backend.broadcastBitcoin.count == before, "\(c.network): something was broadcast")123 return e124 }125126 // 1. the transaction pays more than the ceiling while the plan says the small amount127 let large = Self.wrap(honest, try build(c.ceiling + 1, to: recipientScript, change: changeScript), amount: small)128 guard case .exceedsUnauditedLimit? = await refusal(large) else {129 Issue.record("\(c.network): a transaction above the value ceiling was signed")130 continue131 }132 // 2. the "change" of the plan pays the recipient: the value ceiling would not see it (QYV-SVC-063)133 let profile = await h.service.currentProfile()134 let stored = try #require(profile.bitcoinAccounts[WalletService.accountKey(c.network)])135 let ownScript = try UTXOAccount(extendedKey: stored.extendedPublicKey, network: c.network).scriptPubKey(chain: .receive, index: 5)136 let disguised = try build(small, to: ownScript, change: recipientScript)137 #expect(disguised.changeIndex != nil && disguised.changeValue > c.ceiling)138 guard case .stalePlan? = await refusal(Self.wrap(honest, disguised)) else {139 Issue.record("\(c.network): a plan whose change pays someone else was signed")140 continue141 }142 // 3. the fee written in the plan is not the fee of the transaction143 guard case .stalePlan? = await refusal(Self.wrap(honest, honest.plan, fee: honest.fee - 1)) else {144 Issue.record("\(c.network): a plan with a false fee was signed")145 continue146 }147 // 4. a transaction without change: everything above the payment would go to the miners148 let burning = BitcoinTransaction(version: 2, inputs: coins.map { .init(previousOutput: $0.outPoint, sequence: 0xffff_fffe) },149 outputs: [.init(value: small, scriptPubKey: recipientScript)])150 let total = coins.reduce(UInt64(0)) { $0 + $1.value }151 let costly = BitcoinTransactionPlan(transaction: burning, inputs: coins, changeIndex: nil, sendMaxIndex: nil, fee: total - small, estimatedWeight: 4 * 250,152 targetFeeRate: honest.targetFeeRate, algorithm: .manual, network: c.network)153 #expect(costly.fee > limits.feePerTransaction)154 guard case .exceedsUnauditedLimit? = await refusal(Self.wrap(honest, costly)) else {155 Issue.record("\(c.network): a fee above the ceiling was signed")156 continue157 }158 // 5. a plan of another network, and one whose inputs are not the wallet's coins as last seen159 let foreign = BitcoinSendPlan(id: UUID(), purpose: .payment, network: c.network == .litecoin ? .dogecoin : .litecoin, createdAt: honest.createdAt, plan: honest.plan,160 recipient: honest.recipient, amount: honest.amount, fee: honest.fee, virtualSize: honest.virtualSize, targetFeeRate: honest.targetFeeRate,161 effectiveFeeRate: honest.effectiveFeeRate, inputs: honest.inputs, outputs: honest.outputs, changeAddress: honest.changeAddress,162 changeValue: honest.changeValue, isSendMax: false, warnings: honest.warnings)163 #expect(await refusal(foreign) != nil, "\(c.network)")164 let inflated = coins.map { BitcoinUTXO(outPoint: $0.outPoint, value: $0.value + 1_000, scriptPubKey: $0.scriptPubKey, confirmations: $0.confirmations, derivation: $0.derivation) }165 var request = BitcoinSpendRequest(network: c.network, recipients: [.init(value: small, scriptPubKey: recipientScript)], utxos: inflated,166 feeRate: honest.targetFeeRate, changeScript: changeScript)167 request.seed = 7168 guard case .stalePlan? = await refusal(Self.wrap(honest, try BitcoinTransactionBuilder.build(request))) else {169 Issue.record("\(c.network): a plan over coins the wallet does not know was signed")170 continue171 }172173 // the honest plan is still signed, pays what was reviewed, and carries the coin's kind of signature174 let sent = try await h.service.signAndBroadcast(review)175 #expect(h.backend.broadcastBitcoin.count == 1)176 let tx = try BitcoinTransaction(hex: h.backend.broadcastBitcoin[0], allowWitness: c.network.supportsSegWit)177 #expect(tx.txid == sent.id && tx.outputs.contains { $0.value == small && $0.scriptPubKey == recipientScript })178 try BitcoinVerifier.verify(transaction: tx, spentOutputs: coins.map(\.output), scheme: c.network.sighashScheme)179 #expect(total - (try #require(tx.outputValue(maximumMoney: c.network.maximumMoney))) == honest.fee)180 if !c.network.supportsSegWit {181 #expect(!tx.hasWitness && tx.inputs.allSatisfy { $0.witness.isEmpty && !$0.scriptSig.isEmpty })182 let byte: UInt8 = c.network.sighashScheme == .bip143ForkID ? 0x41 : 0x01183 #expect(tx.inputs.allSatisfy { $0.scriptSig[Int($0.scriptSig[0])] == byte })184 }185 }186 }187188 /// The classic fee-burn attack: the indexer understates (or overstates) a coin so that the difference becomes189 /// fee. Dogecoin signatures do not commit to amounts: the wallet reads the previous transaction, recomputes its190 /// identifier and refuses. Litecoin (BIP-143) and Bitcoin Cash (fork id) signatures commit to the amount: what191 /// the wallet signs under a false amount is not a valid transaction of the network.192 @Test func aLyingIndexerCannotBurnFees() async throws {193 // Dogecoin194 for factor in [UInt64(10), 0] {195 Self.reset()196 defer { Self.reset() }197 let h = try await Self.coinMainnetWallet(.dogecoin, .dogecoin)198 defer { h.cleanup() }199 h.backend.markets = ServiceTests.market([("dogecoin", "0.5")])200 let real: UInt64 = 100_000_000_000201 let funding = h.backend.fundReal(CoinFixture.dogecoin0, real)202 // what the indexer says the coin is worth: a tenth of the truth, or twice the truth203 let claimed = factor == 0 ? real * 2 : real / factor204 let k = try #require(h.backend.txs.firstIndex { $0.txid == funding })205 h.backend.txs[k].outputs[0].value = claimed206 try await h.service.synchronize(chain: .dogecoin)207 #expect(await h.service.snapshot().chain(.dogecoin)?.data.value?.native.confirmed == UInt256(claimed))208 let review = try await h.service.prepareSend(chain: .dogecoin, asset: .native, to: CoinFixture.external(.dogecoin), amount: UInt256(1_000_000_000))209 #expect(try CoinFixture.plan(review).fee <= 500_000_000)210 #expect(await walletError { try await h.service.signAndBroadcast(review) }211 == .untrustedResponse("a coin of this payment does not match the transaction that created it; nothing was signed"))212 #expect(h.backend.broadcastBitcoin.isEmpty)213 }214 // Litecoin and Bitcoin Cash: the signature made under the claimed amount is invalid under any other amount215 for c in Self.coinCases where c.network != .dogecoin {216 Self.reset()217 defer { Self.reset() }218 let h = try await Self.coinMainnetWallet(c.chain, c.network)219 defer { h.cleanup() }220 h.backend.markets = ServiceTests.market([(c.priceID, c.price)])221 h.backend.fund(c.address0, c.funded)222 try await h.service.synchronize(chain: c.chain)223 let review = try await h.service.prepareSend(chain: c.chain, asset: .native, to: CoinFixture.external(c.network), amount: UInt256(c.ceiling / 10))224 let plan = try CoinFixture.plan(review)225 _ = try await h.service.signAndBroadcast(review)226 let tx = try BitcoinTransaction(hex: h.backend.broadcastBitcoin[0], allowWitness: c.network.supportsSegWit)227 let claimed = plan.plan.inputs.map(\.output)228 try BitcoinVerifier.verify(transaction: tx, spentOutputs: claimed, scheme: c.network.sighashScheme)229 for delta in [UInt64(1), 1_000, c.funded] {230 let truth = claimed.map { BitcoinTransaction.Output(value: $0.value + delta, scriptPubKey: $0.scriptPubKey) }231 #expect(!BitcoinVerifier.isValid(transaction: tx, spentOutputs: truth, scheme: c.network.sighashScheme), "\(c.network): the signature does not commit to the amount")232 }233 }234 }235236 /// QYV-SVC-062. The plan check before signing used Bitcoin's monetary range (21 million coins) for every coin: a237 /// Dogecoin payment whose outputs exceed 21 million DOGE — ordinary on that chain — was refused as "inconsistent238 /// amounts". The range is now the network's. (Test network: no value ceiling applies there.)239 @Test func plansAboveBitcoinsMonetaryRangeAreValidOnDogecoin() async throws {240 Self.reset()241 defer { Self.reset() }242 // the Dogecoin test network has no built-in indexer: the test serves one243 let h = try await Harness.abandonWallet()244 defer { h.cleanup() }245 try await h.service.setEndpoints(CoinFixture.endpoints([.dogecoinTestnet]))246 try await h.service.setChainEnabled(.dogecoin, enabled: true)247 CoinFixture.serve(h.backend, .dogecoinTestnet)248 let fifty: UInt64 = 5_000_000_000_000_000 // 50 million DOGE, above 21 million coins in base units249 #expect(fifty > BitcoinLimits.maxMoney && fifty < BitcoinNetwork.dogecoinTestnet.maximumMoney)250 h.backend.fundReal(CoinFixture.dogecoinTestnet0, fifty)251 try await h.service.synchronize(chain: .dogecoinTestnet)252 let review = try await h.service.prepareSend(chain: .dogecoinTestnet, asset: .native, to: CoinFixture.external(.dogecoinTestnet), amount: UInt256(fifty / 2))253 let sent = try await h.service.signAndBroadcast(review)254 let tx = try BitcoinTransaction(hex: h.backend.broadcastBitcoin[0], allowWitness: false)255 #expect(tx.txid == sent.id && tx.outputs.contains { $0.value == fifty / 2 })256 #expect(try #require(tx.outputValue(maximumMoney: BitcoinNetwork.dogecoinTestnet.maximumMoney)) > BitcoinLimits.maxMoney && tx.outputValue == nil)257 }258259 /// QYV-APP-062. Bitcoin SV and eCash kept Bitcoin Cash's fork id: a payment whose coins all predate a split is260 /// valid on the other chain too. The wallet cannot prevent it; the review now says so, as a critical warning.261 @Test func bitcoinCashCoinsOlderThanAChainSplitRaiseACriticalWarning() async throws {262 // (heights of the coins, chains named by the warning; nil = no warning)263 let cases: [(heights: [Int], names: String?)] = [264 ([500_000], "eCash (XEC) and Bitcoin SV"), ([556_766], "eCash (XEC) and Bitcoin SV"), ([556_767], "eCash (XEC)"), ([661_647], "eCash (XEC)"),265 ([661_648], nil), ([900_000], nil), ([500_000, 600_000], "eCash (XEC)"), ([500_000, 700_000], nil),266 ]267 for c in cases {268 Self.reset()269 defer { Self.reset() }270 let h = try await Self.coinMainnetWallet(.bitcoinCash, .bitcoinCash)271 defer { h.cleanup() }272 h.backend.markets = ServiceTests.market([("bitcoin-cash", "500")])273 h.backend.tip = 950_000274 for height in c.heights { h.backend.fund(CoinFixture.bitcoinCash0, 2_000_000, height: height) }275 try await h.service.synchronize(chain: .bitcoinCash)276 // an amount that needs every coin277 let review = try await h.service.prepareSend(chain: .bitcoinCash, asset: .native, to: CoinFixture.external(.bitcoinCash), amount: UInt256(UInt64(2_000_000 * c.heights.count - 100_000)))278 #expect(try CoinFixture.plan(review).inputs.count == c.heights.count)279 let warning = review.warnings.first { $0.id == "bch.replayable-on-forks" }280 if let names = c.names {281 #expect(warning?.isCritical == true && warning?.message.contains("separated from \(names).") == true, "\(c.heights): \(warning?.message ?? "no warning")")282 } else {283 #expect(warning == nil, "\(c.heights)")284 }285 }286 // an unconfirmed coin, and the test network: no warning287 #expect(WalletService.lastBlockSharedWithECash == 661_647 && WalletService.lastBlockSharedWithBitcoinSV == 556_766)288 let t = try await CoinFixture.wallet(chain: .bitcoinCash, network: .bitcoinCashTestnet)289 defer { t.cleanup() }290 let receive = try #require(await t.service.snapshot().chain(.bitcoinCashTestnet)?.receive)291 t.backend.fund(receive.address, 400_000, height: 10)292 try await t.service.synchronize(chain: .bitcoinCashTestnet)293 let review = try await t.service.prepareSend(chain: .bitcoinCashTestnet, asset: .native, to: CoinFixture.external(.bitcoinCashTestnet), amount: UInt256(100_000))294 #expect(!review.warnings.contains { $0.id == "bch.replayable-on-forks" })295 }296}297