Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Tests/QyvoraWalletTests/NewEntryPointsAuditRegressionTests.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 QyvoraEthereum47import QyvoraNetworking48import QyvoraSolana49import QyvoraStorage50import QyvoraTron51@testable import QyvoraWallet5253/// Multi-chain security audit, entry points brought by the merge of `main` (4ac4e69): the sweep of exposed coins of54/// Litecoin, Dogecoin and Bitcoin Cash, fee quotes, `acceptUnverifiedAmounts` of the unified cold signing.55/// In the serialized suite: `MainnetPolicy` is process-wide.56extension MainnetPolicyTests {57 /// The sweep obeys the ceilings of an unaudited mainnet build at prepare and at sign (it is a send-max plan), and58 /// a plan presented as a sweep is signed only when every output returns to the wallet (QYV-SVC-101).59 @Test func aSweepObeysTheCeilingsAndPaysOnlyTheWalletOnEveryCoin() async throws {60 for c in Self.coinCases {61 Self.reset()62 defer { Self.reset() }63 let h = try await Self.coinMainnetWallet(c.chain, c.network)64 defer { h.cleanup() }65 h.backend.markets = ServiceTests.market([(c.priceID, c.price)])66 h.backend.fundReal(c.address0, c.funded)67 try await h.service.synchronize(chain: c.chain)68 let rate = FeeRate.minimum(for: c.network)6970 // expose the first address: a small payment from it, then a coin under the ceiling received on it again71 let payment = try await h.service.prepareSend(chain: c.chain, asset: .native, to: CoinFixture.external(c.network), amount: UInt256(c.ceiling / 10))72 _ = try await h.service.signAndBroadcast(payment)73 h.backend.confirmAll(at: 130)74 h.backend.fundReal(c.address0, c.ceiling / 5, height: 131)75 try await h.service.synchronize(chain: c.chain)76 let sweep = try await h.service.prepareSweepOfExposed(chain: c.chain, feeRate: rate)77 #expect(sweep.purpose == .sweepExposed && sweep.plan.inputs.count == 1 && sweep.plan.transaction.outputs.count == 1 && sweep.plan.changeIndex == nil, "\(c.network)")78 let ownScript = sweep.plan.transaction.outputs[0].scriptPubKey79 let profile = await h.service.currentProfile()80 let stored = try #require(profile.bitcoinAccounts[WalletService.accountKey(c.network)])81 let account = try UTXOAccount(extendedKey: stored.extendedPublicKey, network: c.network)82 #expect(account.locate(scriptPubKey: ownScript, searchLimit: 40)?.chain == .change, "\(c.network): the sweep does not pay the internal chain")83 #expect(sweep.amount + sweep.fee == c.ceiling / 5 && sweep.amount <= c.ceiling)8485 func refusal(_ plan: BitcoinSendPlan) async -> WalletError? {86 let before = h.backend.broadcastBitcoin.count87 let e = await walletError { try await h.service.signAndBroadcast(h.service.review(for: plan)) }88 #expect(h.backend.broadcastBitcoin.count == before, "\(c.network): something was broadcast")89 return e90 }91 func sendMax(_ coins: [BitcoinUTXO], to script: Bytes) throws -> BitcoinTransactionPlan {92 var request = BitcoinSpendRequest(network: c.network, recipients: [], utxos: coins, feeRate: rate, changeScript: ownScript, sendMaxScript: script)93 request.seed = 794 return try BitcoinTransactionBuilder.build(request)95 }9697 // 1. a plan presented as a sweep whose only output pays someone else (QYV-SVC-101): under every ceiling,98 // and still refused99 let foreignScript = try BitcoinAddress(CoinFixture.external(c.network, 0x55), network: c.network).scriptPubKey100 let redirected = Self.wrap(sweep, try sendMax(sweep.plan.inputs, to: foreignScript))101 #expect(redirected.purpose == .sweepExposed)102 guard case .stalePlan(let why)? = await refusal(redirected) else {103 Issue.record("\(c.network): a sweep paying someone else was signed")104 continue105 }106 #expect(why.contains("does not pay an address of this wallet"))107108 // 2. more exposed coins than the ceiling: refused at prepare…109 h.backend.fundReal(c.address0, c.ceiling * 2, height: 132)110 try await h.service.synchronize(chain: c.chain)111 guard case .exceedsUnauditedLimit? = await walletError({ try await h.service.prepareSweepOfExposed(chain: c.chain, feeRate: rate) }) else {112 Issue.record("\(c.network): a sweep above the value ceiling was prepared")113 continue114 }115 // …and at sign, for a plan object made inside the module that states a small amount (send-max path: the116 // ceiling is applied to what the transaction pays, there is no change output to hide it in)117 let exposed = try #require(await h.service.utxoCoinStates[c.network]?.snapshot?.utxos.filter { $0.exposure == .revealedBySpend }.map(\.utxo))118 #expect(exposed.count == 2)119 let large = try sendMax(exposed, to: ownScript)120 #expect(large.changeIndex == nil && large.transaction.outputs[0].value > c.ceiling)121 guard case .exceedsUnauditedLimit? = await refusal(Self.wrap(sweep, large, amount: 1)) else {122 Issue.record("\(c.network): a sweep above the value ceiling was signed")123 continue124 }125 // the same transaction presented as a payment with its output declared as change: the change check of126 // QYV-SVC-063 accepts the script (it is the wallet's), so the fee ceilings are what is left to check —127 // nothing leaves the wallet. A fee above the ceiling is refused.128 let limits = try #require(MainnetPolicy.utxoLimits(c.network))129 let total = exposed.reduce(UInt64(0)) { $0 + $1.value }130 let burning = BitcoinTransaction(version: 2, inputs: exposed.map { .init(previousOutput: $0.outPoint, sequence: 0xffff_fffe) },131 outputs: [.init(value: total - limits.feePerTransaction - 1, scriptPubKey: ownScript)])132 let costly = BitcoinTransactionPlan(transaction: burning, inputs: exposed, changeIndex: 0, sendMaxIndex: nil, fee: limits.feePerTransaction + 1, estimatedWeight: 4 * 400,133 targetFeeRate: rate, algorithm: .manual, network: c.network)134 guard case .exceedsUnauditedLimit? = await refusal(Self.wrap(sweep, costly)) else {135 Issue.record("\(c.network): a sweep with a fee above the ceiling was signed")136 continue137 }138139 // 3. the honest sweep under the ceiling is still signed, and pays the wallet's own fresh address140 let before = h.backend.broadcastBitcoin.count141 let sent = try await h.service.signAndBroadcast(h.service.review(for: sweep))142 #expect(h.backend.broadcastBitcoin.count == before + 1)143 let tx = try BitcoinTransaction(hex: try #require(h.backend.broadcastBitcoin.last), allowWitness: c.network.supportsSegWit)144 #expect(tx.txid == sent.id && tx.outputs.count == 1 && tx.outputs[0].scriptPubKey == ownScript && tx.outputs[0].value == sweep.amount)145 try BitcoinVerifier.verify(transaction: tx, spentOutputs: sweep.plan.inputs.map(\.output), scheme: c.network.sighashScheme)146 }147 }148149 /// The Dogecoin sweep authenticates the coins against their previous transactions like a payment (QYV-SVC-064):150 /// an indexer that misstates an exposed coin gets no signature.151 @Test func aDogecoinSweepChecksItsCoinsAgainstTheirPreviousTransactions() async throws {152 Self.reset()153 defer { Self.reset() }154 let h = try await Self.coinMainnetWallet(.dogecoin, .dogecoin)155 defer { h.cleanup() }156 h.backend.markets = ServiceTests.market([("dogecoin", "0.5")])157 h.backend.fundReal(CoinFixture.dogecoin0, 100_000_000_000)158 try await h.service.synchronize(chain: .dogecoin)159 let payment = try await h.service.prepareSend(chain: .dogecoin, asset: .native, to: CoinFixture.external(.dogecoin), amount: UInt256(1_000_000_000))160 _ = try await h.service.signAndBroadcast(payment)161 h.backend.confirmAll(at: 130)162 let real: UInt64 = 20_000_000_000163 let funding = h.backend.fundReal(CoinFixture.dogecoin0, real, height: 131)164 // the indexer says the exposed coin is worth a tenth of the truth: the rest would be fee165 let k = try #require(h.backend.txs.firstIndex { $0.txid == funding })166 h.backend.txs[k].outputs[0].value = real / 10167 try await h.service.synchronize(chain: .dogecoin)168 let sweep = try await h.service.prepareSweepOfExposed(chain: .dogecoin, feeRate: .minimum(for: .dogecoin))169 #expect(sweep.amount + sweep.fee == real / 10)170 let before = h.backend.broadcastBitcoin.count171 #expect(await walletError { try await h.service.signAndBroadcast(h.service.review(for: sweep)) }172 == .untrustedResponse("a coin of this payment does not match the transaction that created it; nothing was signed"))173 #expect(h.backend.broadcastBitcoin.count == before)174 }175176 /// `feeQuote` is behind the mainnet gate: without the opt-in a main network gives `mainnetDisabled` and no request.177 @Test func feeQuoteIsBehindTheMainnetGateAndSilentInColdMode() async throws {178 Self.reset()179 defer { Self.reset() }180 let h = try await MultiHarness.wallet(chains: [.ethereum, .base, .solana, .tron])181 defer { h.cleanup() }182 let requests = h.backend.requests.count183 for chain in [ChainID.ethereum, .base, .arbitrum, .polygon, .solana, .tron, .bitcoin, .litecoin, .dogecoin, .bitcoinCash] {184 guard case .mainnetDisabled? = await walletError({ try await h.service.feeQuote(chain: chain) }) else {185 Issue.record("\(chain.rawValue): a fee quote on a main network without the opt-in")186 continue187 }188 }189 #expect(await walletError { try await h.service.feeQuote(chain: ChainID("nowhere")) } == .unknownChain("nowhere"))190 #expect(h.backend.requests.count == requests)191 // cold mode: no request leaves the device for an estimate192 try await h.service.setColdMode(true)193 h.backend.forbidAllRequests = true194 for chain in [ChainID.ethereumSepolia, .baseSepolia, .solanaDevnet, .tronNile] {195 #expect(await walletError { try await h.service.feeQuote(chain: chain) } == .offline, "\(chain.rawValue)")196 }197 #expect(h.backend.requests.count == requests)198 }199200 /// `acceptUnverifiedAmounts` of the unified cold signing lifts one refusal only (amounts stated by the PSBT alone,201 /// on a test network). On an unaudited mainnet build it changes nothing: unverified amounts are refused whatever202 /// is passed, and a PSBT whose amounts are verified stays under the value ceiling.203 @Test func acceptUnverifiedAmountsLiftsNoLimit() async throws {204 Self.reset()205 defer { Self.reset() }206 let h = try await Self.mainnetWallet()207 defer { h.cleanup() }208 let account = try BIP84Account(master: try ExtendedKey.master(seed: try BIP39.seed(mnemonic: Harness.abandon)), network: .mainnet)209 let s = try PSBTAmountVerificationTests.Scenario(account, network: .mainnet)210 var unverified = try PSBT(unsignedTransaction: s.tx)211 try unverified.setWitnessUTXO(s.a.outputs[0], inputIndex: 0)212 try unverified.setWitnessUTXO(s.b.outputs[0], inputIndex: 1)213 for blind in [false, true] {214 guard case .invalidPSBT(let why)? = await walletError({215 try await h.service.signColdTransaction([unverified.base64], allowBlindSigning: blind, acceptUnverifiedAmounts: true)216 }) else {217 Issue.record("unverified amounts were signed on unaudited mainnet through the unified call")218 continue219 }220 #expect(why.contains("On mainnet this build does not sign"))221 }222 // verified amounts, above the value ceiling of the build: the flag is no way around the ceiling223 let limit = try #require(MainnetPolicy.utxoLimits(.mainnet))224 guard case .baseUnits(let ceiling) = limit.value else {225 Issue.record("Bitcoin's ceiling is expected in base units")226 return227 }228 let big = try PSBTAmountVerificationTests.funding(account, index: 0, value: ceiling * 3, salt: 0xc3)229 let external = try BitcoinAddress(scriptPubKey: try BitcoinScript.p2wpkh(publicKeyHash: Bytes(repeating: 0x77, count: 20)), network: .mainnet)230 let tx = BitcoinTransaction(inputs: [.init(previousOutput: BitcoinOutPoint(txid: big.txid, vout: 0)!, sequence: BitcoinTransaction.Input.sequenceRBF)],231 outputs: [.init(value: ceiling + 1, scriptPubKey: external.scriptPubKey),232 .init(value: ceiling * 2 - 2_000, scriptPubKey: try account.scriptPubKey(chain: .change, index: 0))])233 var verified = try PSBT(unsignedTransaction: tx)234 try verified.setNonWitnessUTXO(big, inputIndex: 0)235 #expect(try await h.service.reviewPSBT([verified.base64]).inputAmountsVerified)236 for accept in [false, true] {237 guard case .exceedsUnauditedLimit? = await walletError({ try await h.service.signColdTransaction([verified.base64], acceptUnverifiedAmounts: accept) }) else {238 Issue.record("a PSBT above the value ceiling was signed (acceptUnverifiedAmounts: \(accept))")239 continue240 }241 }242 }243}244245/// Entry points brought by the merge of `main`, on test networks.246@Suite(.readsMainnetPolicy) struct NewEntryPointsAuditRegressionTests {247 static let recordName = "utxo-sync-litecoinTestnet.json"248249 /// On a test network the flag accepts amounts the PSBT alone states, and nothing else: the absolute fee bound of250 /// the wallet still refuses the PSBT.251 @Test func acceptUnverifiedAmountsKeepsTheFeeBoundOnATestNetwork() async throws {252 let c = try await PSBTAmountVerificationTests.cold()253 defer { c.h.cleanup() }254 // two coins as the PSBT states them: 3 000 000 sat in, 100 000 out, 2 900 000 of fee (bound: 1 000 000)255 let a = try PSBTAmountVerificationTests.funding(c.account, index: 0, value: 1_500_000, salt: 0xa1)256 let b = try PSBTAmountVerificationTests.funding(c.account, index: 1, value: 1_500_000, salt: 0xb2)257 let external = try BitcoinAddress(scriptPubKey: try BitcoinScript.p2wpkh(publicKeyHash: Bytes(repeating: 0x77, count: 20)), network: .signet)258 let tx = BitcoinTransaction(inputs: [.init(previousOutput: BitcoinOutPoint(txid: a.txid, vout: 0)!, sequence: BitcoinTransaction.Input.sequenceRBF),259 .init(previousOutput: BitcoinOutPoint(txid: b.txid, vout: 0)!, sequence: BitcoinTransaction.Input.sequenceRBF)],260 outputs: [.init(value: 100_000, scriptPubKey: external.scriptPubKey)])261 var psbt = try PSBT(unsignedTransaction: tx)262 try psbt.setWitnessUTXO(a.outputs[0], inputIndex: 0)263 try psbt.setWitnessUTXO(b.outputs[0], inputIndex: 1)264 #expect(WalletService.bitcoinMaximumFee < 2_900_000)265 guard case .invalidPSBT(let why)? = await walletError({ try await c.h.service.signColdTransaction([psbt.base64], acceptUnverifiedAmounts: true) }) else {266 Issue.record("a fee beyond what the wallet signs was accepted with acceptUnverifiedAmounts")267 return268 }269 #expect(why.contains("beyond what QYVORA signs"))270 // the flag means nothing for the other families: an EVM, Solana or TRON payload is classified first271 guard case .some = await walletError({ try await c.h.service.signColdTransaction(["not a transaction"], acceptUnverifiedAmounts: true) }) else {272 Issue.record("text that is no transaction was accepted")273 return274 }275 }276277 /// A forged record of a coin synchronization is shown at most (flagged as the previous session's): no payment,278 /// sweep or signature is ever made from it, and no request is sent.279 @Test func aForgedCoinRecordNeverReachesASignature() async throws {280 let h = try await CoinFixture.wallet(chain: .litecoin, network: .litecoinTestnet)281 defer { h.cleanup() }282 h.backend.fund(CoinFixture.litecoinTestnet0, 500_000)283 #expect(await h.service.synchronize(chains: [.litecoinTestnet]).allSatisfy(\.succeeded))284 let honest = try await h.service.prepareSend(chain: .litecoinTestnet, asset: .native, to: CoinFixture.external(.litecoinTestnet), amount: UInt256(100_000))285 let store = try FileStore(root: h.directory)286 let original = try store.read(Self.recordName)287288 // the forgery: the coin and the output that created it are a thousand times larger (self-consistent)289 var object = try #require(try JSONSerialization.jsonObject(with: Data(original)) as? [String: Any])290 var entries = try #require(object["entries"] as? [[String: Any]])291 let used = try #require(entries.firstIndex { !(($0["coins"] as? [[String: Any]]) ?? []).isEmpty })292 var coins = try #require(entries[used]["coins"] as? [[String: Any]])293 coins[0]["value"] = 500_000_000294 entries[used]["coins"] = coins295 var transactions = try #require(entries[used]["transactions"] as? [[String: Any]])296 var outputs = try #require(transactions[0]["outputs"] as? [[String: Any]])297 for i in outputs.indices where (outputs[i]["value"] as? NSNumber)?.uint64Value == 500_000 { outputs[i]["value"] = 500_000_000 }298 transactions[0]["outputs"] = outputs299 entries[used]["transactions"] = transactions300 if entries[used]["confirmedBalance"] != nil { entries[used]["confirmedBalance"] = 500_000_000 }301 object["entries"] = entries302 try store.write(Bytes(try JSONSerialization.data(withJSONObject: object)), to: Self.recordName, keepPrevious: false)303304 let requests = h.backend.requests.count305 let reopened = try await Harness.make(backend: h.backend, clock: h.clock, directory: h.directory, configure: false)306 let shown = try #require(await reopened.service.snapshot().chain(.litecoinTestnet)?.data.value)307 // displayed, and said to be the previous session's308 #expect(shown.isFromPreviousSession && shown.native.confirmed == UInt256(500_000_000))309 try await reopened.service.unlock(password: Harness.password)310 // 1. no payment and no sweep is prepared from it311 var options = SendOptions()312 options.bitcoinFeeRate = .minimum(for: .litecoinTestnet)313 guard case .notSynchronized? = await walletError({314 try await reopened.service.prepareSend(chain: .litecoinTestnet, asset: .native, to: CoinFixture.external(.litecoinTestnet), amount: UInt256(400_000_000), options: options)315 }) else {316 Issue.record("a payment was prepared from a forged record")317 return318 }319 guard case .notSynchronized? = await walletError({ try await reopened.service.prepareSweepOfExposed(chain: .litecoinTestnet, feeRate: .minimum(for: .litecoinTestnet)) }) else {320 Issue.record("a sweep was prepared from a forged record")321 return322 }323 // 2. a plan of the previous session is not signed against it, nor one built over its coins inside the module324 let previous = try CoinFixture.plan(honest)325 guard case .notSynchronized? = await walletError({ try await reopened.service.signAndBroadcast(reopened.service.review(for: previous)) }) else {326 Issue.record("a plan was signed against a restored record")327 return328 }329 let forgedCoins = try #require(await reopened.service.utxoCoinStates[.litecoinTestnet]?.snapshot?.utxos.map(\.utxo))330 #expect(forgedCoins.map(\.value) == [500_000_000])331 var request = BitcoinSpendRequest(network: .litecoinTestnet, recipients: [.init(value: 400_000_000, scriptPubKey: try BitcoinAddress(CoinFixture.external(.litecoinTestnet), network: .litecoinTestnet).scriptPubKey)],332 utxos: forgedCoins, feeRate: .minimum(for: .litecoinTestnet), changeScript: previous.plan.transaction.outputs[try #require(previous.plan.changeIndex)].scriptPubKey)333 request.seed = 7334 let forgedPlan = MainnetPolicyTests.wrap(previous, try BitcoinTransactionBuilder.build(request), amount: 400_000_000)335 guard case .notSynchronized? = await walletError({ try await reopened.service.signAndBroadcast(reopened.service.review(for: forgedPlan)) }) else {336 Issue.record("a plan over forged coins was signed")337 return338 }339 #expect(h.backend.broadcastBitcoin.isEmpty && h.backend.requests.count == requests)340 // 3. a synchronization replaces it with what the chain says; the forged plan is then refused as stale341 #expect(await reopened.service.synchronize(chains: [.litecoinTestnet]).allSatisfy(\.succeeded))342 let fresh = try #require(await reopened.service.snapshot().chain(.litecoinTestnet)?.data.value)343 #expect(!fresh.isFromPreviousSession && fresh.native.confirmed == UInt256(500_000))344 guard case .stalePlan? = await walletError({ try await reopened.service.signAndBroadcast(reopened.service.review(for: forgedPlan)) }) else {345 Issue.record("a plan over forged coins was signed after a synchronization")346 return347 }348 #expect(h.backend.broadcastBitcoin.isEmpty)349 }350351 /// Hostile shapes of the record: none traps, each is either refused and removed or restored inside the bounds.352 @Test func hostileCoinRecordsAreRefusedOrBoundedAndNeverTrap() async throws {353 let h = try await CoinFixture.wallet(chain: .litecoin, network: .litecoinTestnet)354 defer { h.cleanup() }355 h.backend.fund(CoinFixture.litecoinTestnet0, 500_000)356 #expect(await h.service.synchronize(chains: [.litecoinTestnet]).allSatisfy(\.succeeded))357 let store = try FileStore(root: h.directory)358 let original = String(decoding: try store.read(Self.recordName), as: UTF8.self)359 let profile = await h.service.currentProfile()360 let object = try #require(try JSONSerialization.jsonObject(with: Data(original.utf8)) as? [String: Any])361 let entries = try #require(object["entries"] as? [[String: Any]])362 func with(_ change: (inout [String: Any]) -> Void) throws -> String {363 var copy = object364 change(©)365 return String(decoding: try JSONSerialization.data(withJSONObject: copy), as: UTF8.self)366 }367 func entry(_ change: (inout [String: Any]) -> Void) throws -> String {368 try with { o in369 var list = entries370 change(&list[0])371 o["entries"] = list372 }373 }374 var hostile: [String] = [375 "", "{}", "[]", "null", String(repeating: "[", count: 100_000), original.replacingOccurrences(of: "500000", with: "18446744073709551615"),376 original.replacingOccurrences(of: "500000", with: "18446744073709551616"), original.replacingOccurrences(of: "500000", with: "-1"),377 original.replacingOccurrences(of: "500000", with: "1e999"), original.replacingOccurrences(of: "\"litecoinTestnet\"", with: "\"litecoin\""),378 try with { $0["tipHeight"] = 4_294_967_295 as UInt64 }, try with { $0["tipHeight"] = 100_000_000 }, try with { $0["tipHeight"] = 0 },379 try with { $0["synchronizedAt"] = 1e300 }, try with { $0["synchronizedAt"] = -1e300 }, try with { $0["version"] = 0 }, try with { $0["version"] = -1 },380 try with { $0["notes"] = Array(repeating: "n", count: 51) }, try with { $0["identity"] = "utxo|v1|litecoinTestnet|xpub|" },381 try with { $0["entries"] = Array(repeating: entries[0], count: 4_001) }, try with { $0["entries"] = entries + entries },382 try entry { $0["index"] = 4_294_967_295 as UInt64 }, try entry { $0["chain"] = 7 }, try entry { $0["chain"] = 1 }, try entry { $0["transactionCount"] = Int.min },383 try entry { $0["transactionCount"] = Int.max }, try entry { $0["confirmedBalance"] = UInt64.max }, try entry { $0["address"] = "" },384 try entry { e in385 var coins = (e["coins"] as? [[String: Any]]) ?? []386 if !coins.isEmpty { coins[0]["height"] = Int.max; coins[0]["vout"] = 4_294_967_295 as UInt64 }387 e["coins"] = coins388 },389 try entry { e in390 var coins = (e["coins"] as? [[String: Any]]) ?? []391 if !coins.isEmpty { coins[0]["height"] = -5; coins[0]["txid"] = "zz" }392 e["coins"] = coins393 },394 try entry { e in395 var coins = (e["coins"] as? [[String: Any]]) ?? []396 if let first = coins.first { coins = Array(repeating: first, count: 3_000) }397 e["coins"] = coins398 },399 try entry { e in400 var txs = (e["transactions"] as? [[String: Any]]) ?? []401 if !txs.isEmpty { txs[0]["height"] = Int.max; txs[0]["time"] = Int.max; txs[0]["fee"] = UInt64.max; txs[0]["virtualSize"] = Int.min }402 e["transactions"] = txs403 },404 try entry { e in405 var txs = (e["transactions"] as? [[String: Any]]) ?? []406 if !txs.isEmpty { txs[0]["inputs"] = [[String: Any]](); txs[0]["outputs"] = [[String: Any]]() }407 e["transactions"] = txs408 },409 try entry { e in410 var txs = (e["transactions"] as? [[String: Any]]) ?? []411 if let first = txs.first { txs = Array(repeating: first, count: 2_000) }412 e["transactions"] = txs413 },414 ]415 // truncations of the honest record416 for cut in stride(from: 1, to: original.utf8.count, by: max(1, original.utf8.count / 40)) { hostile.append(String(original.prefix(cut))) }417 var restored = 0418 for (i, text) in hostile.enumerated() {419 try store.write(Bytes(text.utf8), to: Self.recordName, keepPrevious: false)420 if let state = WalletService.restoredUTXOCoin(fileStore: store, profile: profile, network: .litecoinTestnet) {421 restored += 1422 let snapshot = try #require(state.snapshot)423 #expect(snapshot.isFromPreviousSession && snapshot.network == .litecoinTestnet && state.paidScripts.isEmpty && state.locallySpent.isEmpty, "case \(i)")424 #expect(snapshot.tipHeight < 100_000_000 && snapshot.notes.count <= 60 && snapshot.addresses.count <= 2 * Int(WalletService.maximumScanIndex), "case \(i)")425 #expect(snapshot.utxos.allSatisfy { $0.utxo.value <= BitcoinNetwork.litecoinTestnet.maximumMoney }, "case \(i)")426 #expect(snapshot.balance.confirmed <= BitcoinNetwork.litecoinTestnet.maximumMoney && snapshot.balance.pending <= BitcoinNetwork.litecoinTestnet.maximumMoney, "case \(i)")427 } else {428 #expect(!store.exists(Self.recordName), "case \(i): a refused record was left on disk")429 }430 }431 // the honest record is the control: the loop is not refusing everything432 try store.write(Bytes(original.utf8), to: Self.recordName, keepPrevious: false)433 #expect(WalletService.restoredUTXOCoin(fileStore: store, profile: profile, network: .litecoinTestnet)?.snapshot?.balance.confirmed == 500_000)434 #expect(restored < hostile.count)435 // a record of this network is not read for another one, nor without the account436 try store.write(Bytes(original.utf8), to: "utxo-sync-dogecoinTestnet.json", keepPrevious: false)437 #expect(WalletService.restoredUTXOCoin(fileStore: store, profile: profile, network: .dogecoinTestnet) == nil && !store.exists("utxo-sync-dogecoinTestnet.json"))438 #expect(WalletService.restoredUTXOCoin(fileStore: store, profile: WalletProfile(), network: .litecoinTestnet) == nil && !store.exists(Self.recordName))439 }440441 /// QYV-SVC-100. The scripts a persisted record says were paid stayed in the session after a synchronization: a442 /// forged record silenced the first-payment warning of a later payment to an address the wallet never paid.443 @Test func aPersistedRecordDoesNotSilenceTheFirstPaymentWarning() async throws {444 let h = try await CoinFixture.wallet(chain: .litecoin, network: .litecoinTestnet)445 defer { h.cleanup() }446 h.backend.fund(CoinFixture.litecoinTestnet0, 500_000)447 #expect(await h.service.synchronize(chains: [.litecoinTestnet]).allSatisfy(\.succeeded))448 let stranger = CoinFixture.external(.litecoinTestnet, 0x66)449 let first = try CoinFixture.plan(try await h.service.prepareSend(chain: .litecoinTestnet, asset: .native, to: stranger, amount: UInt256(50_000)))450 #expect(first.warnings.contains(.firstPaymentToAddress))451 let sent = try await h.service.signAndBroadcast(h.service.review(for: first))452 h.backend.confirmAll(at: 130)453 #expect(await h.service.synchronize(chains: [.litecoinTestnet]).allSatisfy(\.succeeded))454 let again = try CoinFixture.plan(try await h.service.prepareSend(chain: .litecoinTestnet, asset: .native, to: stranger, amount: UInt256(50_000)))455 #expect(again.warnings.contains(.destinationAlreadyPaid) && !again.warnings.contains(.firstPaymentToAddress))456 // the record on disk now says the stranger was paid. The chain the next session reads never saw that payment:457 // for that session the record is a forgery458 h.backend.txs.removeAll { $0.txid == sent.id }459 let reopened = try await Harness.make(backend: h.backend, clock: h.clock, directory: h.directory, configure: false)460 #expect(await reopened.service.snapshot().chain(.litecoinTestnet)?.data.value?.isFromPreviousSession == true)461 #expect(await reopened.service.utxoCoinStates[.litecoinTestnet]?.paidScripts.isEmpty == true)462 try await reopened.service.unlock(password: Harness.password)463 #expect(await reopened.service.synchronize(chains: [.litecoinTestnet]).allSatisfy(\.succeeded))464 let plan = try CoinFixture.plan(try await reopened.service.prepareSend(chain: .litecoinTestnet, asset: .native, to: stranger, amount: UInt256(50_000)))465 #expect(plan.warnings.contains(.firstPaymentToAddress) && !plan.warnings.contains(.destinationAlreadyPaid))466 }467468 /// QYV-SVC-104. Address indices of the profile file were used as they came: 4 294 967 295 in a "used" list made469 /// `nextUnusedIndex` overflow (a trap) when a payment, a sweep or a receive address was prepared, and made the470 /// search window of a PSBT review overflow or cover billions of keys.471 @Test func hostileAddressIndicesOfAProfileNeitherTrapNorGrowTheSearch() async throws {472 var hostile = WalletProfile()473 for network in BitcoinNetwork.allCases {474 hostile.usedReceiveIndices[network.rawValue] = [3, UInt32.max, UInt32.max - 1, 0x8000_0000, 4_001, 4_000]475 hostile.usedChangeIndices[network.rawValue] = [UInt32.max, 7]476 }477 let read = try JSONDecoder().decode(WalletProfile.self, from: try JSONEncoder().encode(hostile))478 for network in BitcoinNetwork.allCases {479 #expect(read.usedReceiveIndices[network.rawValue] == [3, 4_000] && read.usedChangeIndices[network.rawValue] == [7], "\(network)")480 }481 #expect(WalletProfile.maximumUsedIndex >= WalletService.maximumScanIndex + UTXOAccount.gapLimit)482 // the account itself does not trap on such a set either483 for network in [BitcoinNetwork.signet, .litecoinTestnet, .dogecoinTestnet, .bitcoinCashTestnet] {484 let account = try UTXOAccount(master: try ExtendedKey.master(seed: try BIP39.seed(mnemonic: Harness.abandon)), network: network)485 #expect(account.nextUnusedIndex(used: [.max]) == .max && account.nextUnusedIndex(used: [.max - 1]) == .max && account.nextUnusedIndex(used: []) == 0)486 #expect(account.scanRange(used: [.max]).upperBound == .max && account.scanRange(used: [5]).upperBound == 6 + UTXOAccount.gapLimit)487 for used in [Set([UInt32.max]), [UInt32.max - 3], [0x7fff_ffff], [0x8000_0000]] {488 for skipping in [UInt32(0), 5, UTXOAccount.gapLimit - 1] {489 #expect(throws: BitcoinAccountError.self) { try account.nextUnusedAddress(chain: .change, used: used, skipping: skipping) }490 }491 }492 #expect(try account.nextUnusedAddress(chain: .change, used: [0x7fff_fffd]).index == 0x7fff_fffe)493 }494 }495496 /// Hostile figures from the endpoints never trap `feeQuote`: it answers an error or figures that hold together.497 @Test func feeQuoteSurvivesHostileFigures() async throws {498 let h = try await MultiHarness.wallet(chains: [.ethereum, .base, .solana, .tron])499 defer { h.cleanup() }500 let huge = [UInt256.max, UInt256.max - UInt256(1), UInt256(UInt64.max), UInt256(UInt64.max) + UInt256(1), .zero, UInt256(1)]501 var answered = 0, refused = 0502 for network in [EthereumNetwork.sepolia, .baseSepolia] {503 let chain = ChainRegistry.id(network)504 let node = h.backend.evm(network)505 for base in huge {506 for tip in [UInt256.max, UInt256(UInt64.max), .zero, UInt256(1_000_000_000)] {507 node.baseFee = base508 node.priorityFee = tip509 do {510 let quote = try await h.service.feeQuote(chain: chain)511 answered += 1512 #expect(quote.tiers.count == 3 && quote.tiers.allSatisfy { $0.expected <= $0.maximum })513 } catch {514 refused += 1515 }516 }517 }518 node.baseFee = UInt256(10_000_000_000)519 node.priorityFee = UInt256(1_000_000_000)520 // the L1 fee of an OP-Stack network and every gas estimate, as raw answers521 for answer in ["\"0x" + String(repeating: "f", count: 64) + "\"", "\"0x\"", "\"0x" + String(repeating: "f", count: 65) + "\"", "null", "\"-1\"", "12", "{}", "\"0xffffffffffffffff\""] {522 for method in ["eth_call", "eth_estimateGas", "eth_gasPrice", "eth_maxPriorityFeePerGas", "eth_feeHistory", "eth_getBlockByNumber"] {523 node.rpcResultOverride[method] = answer524 do {525 let quote = try await h.service.feeQuote(chain: chain)526 answered += 1527 #expect(quote.tiers.allSatisfy { $0.expected <= $0.maximum })528 } catch {529 refused += 1530 }531 node.rpcResultOverride[method] = nil532 }533 }534 }535 // Solana: the prices recent transactions paid536 for fees in [[UInt64.max], [UInt64.max, UInt64.max, 0], [UInt64.max / 2 + 1], [0], Array(repeating: UInt64.max - 1, count: 150)] {537 h.backend.solana.prioritizationFees = fees538 do {539 let quote = try await h.service.feeQuote(chain: .solanaDevnet)540 answered += 1541 // bounded by the highest unit price the wallet pays, on the compute budget of a plain transfer542 let bound = SolanaComputeBudget.priorityFee(unitLimit: SolanaSendPlanner.defaultUnitLimit(asset: .sol, program: nil, hasMemo: false),543 microLamportsPerUnit: SolanaFees.maximumUnitPrice) ?? 0544 #expect(quote.tiers.allSatisfy { $0.expected == $0.maximum && $0.maximum <= UInt256(SolanaComputeBudget.lamportsPerSignature + bound) })545 } catch {546 refused += 1547 }548 }549 // TRON: chain parameters and resources550 let parameters = h.backend.tron.parameters551 for value in ["9223372036854775807", "18446744073709551615", "18446744073709551616", "-1", "0", "1e999", "\"x\"", "null"] {552 for key in ["getTransactionFee", "getCreateAccountFee", "getCreateNewAccountFeeInSystemContract", "getEnergyFee"] {553 guard let range = parameters.range(of: "\"key\":\"\(key)\",\"value\":") else { continue }554 let tail = parameters[range.upperBound...]555 let end = tail.firstIndex(of: "}") ?? tail.endIndex556 h.backend.tron.parameters = String(parameters[..<range.upperBound]) + value + String(parameters[end...])557 for resources in [#"{"freeNetLimit":600,"freeNetUsed":0}"#, #"{"freeNetLimit":9223372036854775807,"freeNetUsed":0,"NetLimit":9223372036854775807,"EnergyLimit":9223372036854775807}"#,558 #"{"freeNetLimit":0,"freeNetUsed":9223372036854775807}"#, #"{"freeNetLimit":-1,"freeNetUsed":-1}"#, "{}"] {559 h.backend.tron.resources = resources560 do {561 let quote = try await h.service.feeQuote(chain: .tronNile)562 answered += 1563 let estimate = try #require(quote.tron)564 #expect(quote.tiers.isEmpty && estimate.transferBandwidthBytes > 0 && estimate.transferBandwidthBytes < 1_000 && estimate.lines.count == 2)565 } catch {566 refused += 1567 }568 }569 }570 }571 #expect(answered > 0 && refused > 0)572 }573574 /// Showing a hidden token again takes nothing from the value passed in: symbol and decimals of a payment stay575 /// those of the wallet's list, and a token hidden from the detected list does not enter the list.576 @Test func showingAHiddenTokenAgainChangesNoPaymentMetadata() async throws {577 let h = try await MultiHarness.wallet(chains: [.ethereum, .solana, .tron])578 defer { h.cleanup() }579 let owner = try #require(SolanaPublicKey(base58: MultiHarness.solanaAddress))580 let listedMint = solanaStranger(40).base58, foundMint = solanaStranger(41).base58581 h.backend.solana.lamports[MultiHarness.solanaAddress] = 1_000_000_000582 h.backend.solana.mints[listedMint] = .init(decimals: 6)583 h.backend.solana.mints[foundMint] = .init(decimals: 2)584 h.backend.solana.tokenAccounts = [585 .init(address: try SolanaAddress.associatedTokenAccount(owner: owner, mint: SolanaPublicKey(base58: listedMint)!, tokenProgram: .token).base58,586 mint: listedMint, owner: MultiHarness.solanaAddress, amount: 12_500_000),587 .init(address: solanaStranger(42).base58, mint: foundMint, owner: MultiHarness.solanaAddress, amount: 700),588 ]589 let contract = tronStranger(0x51)590 let me = try #require(TronAddress(MultiHarness.tronAddress))591 h.backend.tron.balances[me.hex] = 50_000_000592 h.backend.tron.tokens[contract.hex] = .init(decimals: 6, symbol: "TUSD", name: "Test Dollar", balances: [Hex.encode(me.hash): UInt256(3_210_000)])593 let added = try await h.service.addCustomToken(chain: .solanaDevnet, address: listedMint, label: "TEST")594 let tronToken = try await h.service.addCustomToken(chain: .tronNile, address: contract.base58)595 #expect(await h.service.synchronize().allSatisfy(\.succeeded))596 let detected = try #require(await h.service.chainSnapshot(.solanaDevnet)?.data.value?.detectedTokens.first)597 try await h.service.setTokenHidden(true, token: added)598 try await h.service.setTokenHidden(true, token: tronToken)599 try await h.service.setTokenHidden(true, token: detected.token)600 let before = await h.service.currentProfile()601602 // the caller describes the tokens as it likes: other decimals, another symbol, another standard603 let lyingSolana = ChainToken(chain: .solanaDevnet, address: listedMint, symbol: "LIE", name: "Lie", decimals: 0, standard: .splToken2022, isCustom: true)604 let lyingTron = ChainToken(chain: .tronNile, address: contract.base58, symbol: "LIE", name: "Lie", decimals: 0, standard: .trc20, isCustom: true)605 let lyingFound = ChainToken(chain: .solanaDevnet, address: foundMint, symbol: "LIE", name: "Lie", decimals: 9, standard: .spl, isCustom: true)606 try await h.service.showHiddenToken(HiddenToken(chain: .solanaDevnet, address: listedMint, token: lyingSolana))607 try await h.service.showHiddenToken(HiddenToken(chain: .tronNile, address: contract.base58, token: lyingTron))608 try await h.service.showHiddenToken(HiddenToken(chain: .solanaDevnet, address: foundMint, token: lyingFound))609 // an entry that names nothing hidden, or text that is no address, changes nothing and does not trap610 try await h.service.showHiddenToken(HiddenToken(chain: .solanaDevnet, address: "", token: lyingSolana))611 try await h.service.showHiddenToken(HiddenToken(chain: .tronNile, address: "solana-devnet:" + listedMint, token: nil))612 try await h.service.showHiddenToken(HiddenToken(chain: .ethereumSepolia, address: String(repeating: ":", count: 10_000), token: nil))613 #expect(await walletError { try await h.service.showHiddenToken(HiddenToken(chain: .bitcoinSignet, address: "x", token: nil)) } == .unknownChain("bitcoin-signet"))614615 let after = await h.service.currentProfile()616 #expect(after.hiddenTokens.isEmpty && after.customSolanaTokens == before.customSolanaTokens && after.customTronTokens == before.customTronTokens && after.customTokens == before.customTokens)617 let solana = try #require(await h.service.chainSnapshot(.solanaDevnet)?.data.value)618 #expect(solana.tokens.map(\.token) == [added] && solana.tokens.first?.token.decimals == 6)619 // the token that had only been detected stays out of the list: nothing of the caller's description was kept620 #expect(!solana.tokens.contains { $0.token.address == foundMint } && !solana.detectedTokens.contains { $0.token.symbol == "LIE" })621 #expect(await h.service.chainSnapshot(.tronNile)?.data.value?.tokens.map(\.token) == [tronToken])622 // a payment of the token is reviewed with the list's decimals and symbol, even when asked with the lie623 let tronReview = try await h.service.prepareSend(chain: .tronNile, asset: .token(lyingTron), to: tronStranger(0x44).base58, amount: UInt256(1_000_000))624 #expect(tronReview.amountDecimals == 6 && tronReview.amountSymbol == "TUSD")625 let solanaReview = try await h.service.prepareSend(chain: .solanaDevnet, asset: .token(lyingSolana), to: solanaStranger().base58, amount: UInt256(1_000_000))626 #expect(solanaReview.amountDecimals == 6 && solanaReview.amountSymbol == "TEST")627 }628629 /// QYV-SVC-102. A token of the detected list restored from the previous session's file could be moved into the630 /// wallet's list: symbol and decimals of the file then became those of every payment of the token (the quarantine631 /// of QYV-SVC-084 was lifted by one call). It is now refused until a synchronization of this session.632 @Test func aDetectedTokenOfARestoredSnapshotCannotEnterTheList() async throws {633 // EVM, through the 1.0 call634 let backend = FakeBackend()635 let e = try await Harness.abandonWallet(backend: backend)636 defer { e.cleanup() }637 let contract = "0x" + String(repeating: "c3", count: 20)638 var model = FakeBackend.TokenContract(symbol: "DET", name: "Detected", decimals: UInt256(6))639 model.balances[EthereumWalletTests.owner] = UInt256(1_000_000)640 backend.tokens[contract] = model641 backend.code[contract] = [0x60, 0x80]642 backend.balances[EthereumWalletTests.owner] = EthereumWalletTests.oneEther643 backend.indexerTokens = "{\"items\":[{\"token\":{\"address_hash\":\"\(contract)\",\"symbol\":\"LIE\",\"name\":\"LIE\",\"decimals\":\"0\",\"type\":\"ERC-20\"},\"token_id\":null,\"value\":\"1\"}],\"next_page_params\":null}"644 _ = try await e.service.syncEthereum()645 // the file of the next launch says other decimals and another symbol646 let store = try FileStore(root: e.directory)647 let name = EthereumSnapshotRecord.fileName(for: .sepolia)648 let text = String(decoding: try store.read(name), as: UTF8.self)649 #expect(text.contains("\"DET\""))650 var forged = text.replacingOccurrences(of: "\"DET\"", with: "\"USDC\"")651 #expect(forged.contains("\"decimals\":6"))652 forged = forged.replacingOccurrences(of: "\"decimals\":6", with: "\"decimals\":0")653 try store.write(Bytes(forged.utf8), to: name, keepPrevious: false)654 let again = try await Harness.make(backend: backend, clock: e.clock, directory: e.directory, configure: false)655 let restored = try #require(await again.service.ethereumSnapshot)656 let lie = try #require(restored.detectedTokens.first?.token)657 #expect(restored.isFromPreviousSession && lie.symbol == "USDC" && lie.decimals == 0)658 try await again.service.unlock(password: Harness.password)659 guard case .notSynchronized? = await walletError({ try await again.service.acceptDetectedToken(lie) }) else {660 Issue.record("a detected token of the previous session's file entered the list")661 return662 }663 #expect(await again.service.currentProfile().customTokens.isEmpty)664 // read again on chain, the token enters the list with the contract's own description665 _ = try await again.service.syncEthereum()666 let real = try #require(await again.service.ethereumSnapshot?.detectedTokens.first?.token)667 #expect(real.symbol == "DET" && real.decimals == 6)668 try await again.service.acceptDetectedToken(real)669 #expect(await again.service.currentProfile().customTokens.map(\.decimals) == [6])670671 // Solana and TRON, through the uniform call672 let h = try await MultiHarness.wallet(chains: [.solana, .tron])673 defer { h.cleanup() }674 let foundMint = solanaStranger(41).base58675 h.backend.solana.lamports[MultiHarness.solanaAddress] = 1_000_000_000676 h.backend.solana.mints[foundMint] = .init(decimals: 2)677 h.backend.solana.tokenAccounts = [.init(address: solanaStranger(42).base58, mint: foundMint, owner: MultiHarness.solanaAddress, amount: 700)]678 #expect(await h.service.synchronize().allSatisfy(\.succeeded))679 let detected = try #require(await h.service.chainSnapshot(.solanaDevnet)?.data.value?.detectedTokens.first?.token)680 let next = try await MultiHarness.make(backend: h.backend, clock: h.clock, directory: h.directory, configure: false)681 let shown = try #require(await next.service.chainSnapshot(.solanaDevnet)?.data.value)682 #expect(shown.isFromPreviousSession && shown.detectedTokens.first?.token == detected)683 try await next.service.unlock(password: Harness.password)684 guard case .notSynchronized? = await walletError({ try await next.service.acceptDetectedToken(detected) }) else {685 Issue.record("a detected SPL token of the previous session's file entered the list")686 return687 }688 #expect(await next.service.currentProfile().customSolanaTokens.isEmpty)689 #expect(await next.service.synchronize(chains: [.solanaDevnet]).allSatisfy(\.succeeded))690 try await next.service.acceptDetectedToken(detected)691 #expect(await next.service.currentProfile().customSolanaTokens.map(\.address) == [foundMint])692 }693}694