Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Tests/QyvoraWalletTests/TestSupport.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 QyvoraSymmetric45import QyvoraCore46import QyvoraBitcoin47import QyvoraEthereum48import QyvoraNetworking49import QyvoraStorage50import QyvoraVault51@testable import QyvoraWallet5253/// A settable clock.54final class TestClock: @unchecked Sendable {55 private let lock = NSLock()56 private var current = Date(timeIntervalSince1970: 1_800_000_000)57 var now: Date { lock.withLock { current } }58 /// Time passes: the wall clock and the monotonic clock move together.59 func advance(_ seconds: TimeInterval) {60 lock.withLock {61 current = current.addingTimeInterval(seconds)62 uptime += seconds63 }64 }6566 // The clock the user cannot set (QYV-SVC-010), and the two ways it can part from the wall clock.67 private var uptime: TimeInterval = 5_00068 private var boot = Bytes(repeating: 0xb0, count: 16)69 var monotonic: MonotonicInstant { lock.withLock { MonotonicInstant(bootSession: boot, seconds: UInt64(max(0, uptime))) } }70 /// The date is changed in the settings: only the wall clock moves.71 func setDate(by seconds: TimeInterval) { lock.withLock { current = current.addingTimeInterval(seconds) } }72 /// The device restarts: a new boot session, the monotonic clock starts again; `downtime` passes on the wall clock.73 func reboot(downtime: TimeInterval = 30, uptimeAfter: TimeInterval = 20) {74 lock.withLock {75 current = current.addingTimeInterval(downtime)76 uptime = uptimeAfter77 boot = boot.map { $0 &+ 1 }78 }79 }80}8182/// An in-memory stand-in for the four services the wallet talks to. It answers in the shapes of the real APIs83/// (Esplora REST, Ethereum JSON-RPC, Blockscout v2, CoinGecko v3) from a small model the tests edit.84final class FakeBackend: HTTPTransport, @unchecked Sendable {85 // MARK: Bitcoin model8687 struct Tx {88 var txid: String89 var inputs: [(txid: String, vout: Int)]90 var outputs: [(script: Bytes, value: UInt64)]91 var height: Int?92 }9394 struct TokenContract {95 var symbol = "TKN"96 var name = "Token"97 var decimals = UInt256(6)98 var balances: [String: UInt256] = [:]99 /// "owner|spender" (lower case) → allowance100 var allowances: [String: UInt256] = [:]101 /// Return data of `transfer`; default is the ABI word 1.102 var transferReturn: Bytes = UInt256(1).bytes32103 }104105 private let lock = NSLock()106 var network = BitcoinNetwork.signet107 var genesis = BitcoinNetwork.signet.genesisHash108 var tip = 200109 var txs: [Tx] = []110 var feeEstimates = "{\"1\":25.3,\"2\":20.0,\"6\":10.1,\"144\":1.0}"111 var broadcastBitcoin: [String] = []112 /// When set, POST /tx answers this instead of the real txid.113 var bitcoinBroadcastAnswer: String?114 /// Add broadcast transactions to the model as unconfirmed.115 var acceptBroadcastIntoMempool = true116117 // MARK: Ethereum model118119 var chainID: UInt64 = 11_155_111120 var blockNumber: UInt64 = 5_000_000121 var balances: [String: UInt256] = [:]122 var latestNonce: [String: UInt64] = [:]123 var pendingNonce: [String: UInt64] = [:]124 var code: [String: Bytes] = [:]125 var tokens: [String: TokenContract] = [:]126 var baseFee = UInt256(10_000_000_000)127 var priorityFee = UInt256(1_000_000_000)128 var gasEstimate: UInt64 = 50_000129 /// JSON-RPC error message returned by eth_estimateGas when set.130 var gasEstimateError: String?131 var broadcastEthereum: [Bytes] = []132 var ethereumBroadcastAnswer: String?133 var receipts: [String: String] = [:]134 var transactionsByHash: [String: String] = [:]135 /// A second JSON-RPC endpoint ("rpc2.test") serving the same model, whose transaction counts are ahead of the136 /// first one by this much (two honest endpoints that are not at the same block).137 var secondEndpointNonceLead: UInt64 = 0138 /// Leads used by the next answers of the second endpoint, one per `eth_getTransactionCount` call, before139 /// `secondEndpointNonceLead` applies again (a difference that disappears on retry).140 var secondEndpointNonceLeadQueue: [UInt64] = []141 /// method → raw JSON of the `result` member (hostile or special answers).142 var rpcResultOverride: [String: String] = [:]143144 // MARK: Indexer and prices145146 var indexerTransactions = "{\"items\":[],\"next_page_params\":null}"147 var indexerTokenTransfers = "{\"items\":[],\"next_page_params\":null}"148 var indexerTokens = "{\"items\":[],\"next_page_params\":null}"149 var indexerStatus = 200150 var markets = "[]"151 var marketChart = "{\"prices\":[],\"market_caps\":[],\"total_volumes\":[]}"152 var priceStatus = 200153 /// The second price source ("pricecheck.test", Kraken's ticker form). nil: an honest second source, which answers154 /// the price `markets` gives for the asset behind the pair asked (the two sources agree). Otherwise pair → price155 /// text; a pair that is absent is unknown to the source.156 var checkPrices: [String: String]?157 var checkStatus = 200158 /// Raw body of the second source's answer, when set (hostile or malformed answers).159 var checkBody: String?160161 // MARK: Control162163 /// Substring of "METHOD path" → (status, body): replaces the normal answer.164 var overrides: [(match: String, status: Int, body: String)] = []165 /// The next N requests answer HTTP 429.166 var rateLimitNext = 0167 /// Hosts that answer HTTP 429 to everything (a public endpoint that rate-limits this client).168 var rateLimitedHosts: Set<String> = []169 /// Hosts that do not answer at all (the request times out).170 var silentHosts: Set<String> = []171 /// Any request is a test failure (cold mode).172 var forbidAllRequests = false173 private(set) var requests: [String] = []174 private(set) var statisticsRequests = 0175 private var counter: UInt64 = 0176177 static let endpoints = EndpointConfiguration(178 esplora: ["signet": ["https://esplora.test/api"], "testnet": ["https://esplora.test/api"], "mainnet": ["https://esplora.test/api"]],179 ethereumRPC: ["sepolia": ["https://rpc.test"], "mainnet": ["https://rpc.test"]],180 ethereumIndexer: ["sepolia": ["https://indexer.test"], "mainnet": ["https://indexer.test"]],181 priceAPI: "https://prices.test/api/v3", priceCheckAPI: "https://pricecheck.test/0/public")182183 /// One ticker of the second source, in Kraken's form: ask, bid and last trade all at `price`.184 static func ticker(_ pair: String, _ price: String) -> String {185 "{\"error\":[],\"result\":{\"\(pair)\":{\"a\":[\"\(price)\",\"1\",\"1.000\"],\"b\":[\"\(price)\",\"1\",\"1.000\"],\"c\":[\"\(price)\",\"0.5\"]}}}"186 }187188 private func checkAnswer(_ url: URL) -> String {189 if let checkBody { return checkBody }190 let pair = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems?.first { $0.name == "pair" }?.value ?? ""191 let unknown = "{\"error\":[\"EQuery:Unknown asset pair\"]}"192 if let checkPrices { return checkPrices[pair].map { Self.ticker(pair, $0) } ?? unknown }193 // honest mirror of the first source194 guard let rows = (try? JSONDecoder().decode(JSONValue.self, from: Data(markets.utf8)))?.array else { return unknown }195 for row in rows {196 guard let id = row["id"]?.string, PriceClient.checkPairs[id] == pair, case .number(let price)? = row["current_price"], price > 0 else { continue }197 return Self.ticker(pair, String(format: "%.12f", price))198 }199 return unknown200 }201202 // MARK: Model helpers203204 func nextTxid() -> String {205 counter += 1206 return Hex.encode(SHA256.hash(Bytes("fake-tx-\(counter)".utf8)))207 }208209 static let foreignScript = try! BitcoinScript.p2wpkh(publicKeyHash: Bytes(repeating: 0xee, count: 20))210211 /// A confirmed (or unconfirmed, height nil) payment from outside to `address`.212 @discardableResult213 func fund(_ address: String, _ value: UInt64, height: Int? = 100) -> String {214 let script = try! BitcoinAddress(address, network: network).scriptPubKey215 let id = nextTxid()216 txs.append(Tx(txid: id, inputs: [(nextTxid(), 0)], outputs: [(script, value)], height: height))217 return id218 }219220 /// A transaction spending model outputs.221 @discardableResult222 func spend(_ inputs: [(String, Int)], to outputs: [(String, UInt64)], height: Int? = 120) -> String {223 let id = nextTxid()224 txs.append(Tx(txid: id, inputs: inputs.map { ($0.0, $0.1) },225 outputs: outputs.map { (try! BitcoinAddress($0.0, network: network).scriptPubKey, $0.1) }, height: height))226 return id227 }228229 /// Raw transactions served by GET /tx/<txid>/hex, by txid.230 var rawTransactions: [String: String] = [:]231232 /// Like `fund`, with a real transaction behind the output: its identifier is the hash of its bytes, and the233 /// endpoint serves those bytes (what a PSBT carries as PSBT_IN_NON_WITNESS_UTXO).234 @discardableResult235 func fundReal(_ address: String, _ value: UInt64, height: Int? = 100) -> String {236 let script = try! BitcoinAddress(address, network: network).scriptPubKey237 let source = nextTxid()238 let tx = BitcoinTransaction(inputs: [.init(previousOutput: BitcoinOutPoint(txid: source, vout: 0)!, scriptSig: [0x51])],239 outputs: [.init(value: value, scriptPubKey: script)])240 txs.append(Tx(txid: tx.txid, inputs: [(source, 0)], outputs: [(script, value)], height: height))241 rawTransactions[tx.txid] = tx.hex242 return tx.txid243 }244245 func prevout(_ txid: String, _ vout: Int) -> (script: Bytes, value: UInt64)? {246 guard let t = txs.first(where: { $0.txid == txid }), vout < t.outputs.count else { return nil }247 return t.outputs[vout]248 }249250 func confirmAll(at height: Int) {251 for i in txs.indices where txs[i].height == nil { txs[i].height = height }252 }253254 private func outputJSON(_ script: Bytes, _ value: UInt64) -> [String: Any] {255 var o: [String: Any] = ["scriptpubkey": Hex.encode(script), "scriptpubkey_asm": "", "scriptpubkey_type": "v0_p2wpkh", "value": value]256 if let a = try? BitcoinAddress(scriptPubKey: script, network: network) { o["scriptpubkey_address"] = a.string }257 return o258 }259260 private func txJSON(_ t: Tx) -> [String: Any] {261 var inTotal: UInt64 = 0262 let vin: [[String: Any]] = t.inputs.map { i in263 let p = prevout(i.txid, i.vout) ?? (Self.foreignScript, t.outputs.reduce(0) { $0 + $1.value } / UInt64(max(1, t.inputs.count)) + 500)264 inTotal += p.value265 return ["txid": i.txid, "vout": i.vout, "prevout": outputJSON(p.script, p.value), "scriptsig": "", "scriptsig_asm": "",266 "witness": ["00", "00"], "is_coinbase": false, "sequence": 4_294_967_293 as UInt32]267 }268 let outTotal = t.outputs.reduce(0) { $0 + $1.value }269 var status: [String: Any] = ["confirmed": t.height != nil]270 if let h = t.height {271 status["block_height"] = h272 status["block_hash"] = String(repeating: "0", count: 64)273 status["block_time"] = 1_700_000_000 + h * 600274 }275 return ["txid": t.txid, "version": 2, "locktime": 0, "vin": vin, "vout": t.outputs.map { outputJSON($0.script, $0.value) },276 "size": 222, "weight": 561, "fee": inTotal >= outTotal ? inTotal - outTotal : 0, "status": status]277 }278279 private func history(of script: Bytes) -> [Tx] {280 txs.filter { t in t.outputs.contains { $0.script == script } || t.inputs.contains { prevout($0.txid, $0.vout)?.script == script } }281 .sorted { a, b in282 switch (a.height, b.height) {283 case (nil, nil): return a.txid < b.txid284 case (nil, _): return true285 case (_, nil): return false286 case (let x?, let y?): return x != y ? x > y : a.txid < b.txid287 }288 }289 }290291 // MARK: Transport292293 private func json(_ value: Any) -> String {294 String(decoding: try! JSONSerialization.data(withJSONObject: value, options: [.fragmentsAllowed, .sortedKeys]), as: UTF8.self)295 }296297 func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) {298 try lock.withLock {299 let url = request.url!300 let method = request.httpMethod ?? "GET"301 let line = "\(method) \(url.host ?? "")\(url.path)" + (url.query.map { "?\($0)" } ?? "")302 requests.append(line)303 if forbidAllRequests { Issue.record("network request in cold mode: \(line)") }304 func reply(_ status: Int, _ body: String) -> (Data, HTTPURLResponse) {305 (Data(body.utf8), HTTPURLResponse(url: url, statusCode: status, httpVersion: "HTTP/1.1", headerFields: nil)!)306 }307 if rateLimitNext > 0 {308 rateLimitNext -= 1309 return reply(429, "Too Many Requests")310 }311 if let host = url.host, rateLimitedHosts.contains(host) { return reply(429, "Too Many Requests") }312 if let host = url.host, silentHosts.contains(host) { throw URLError(.timedOut) }313 if let o = overrides.first(where: { line.contains($0.match) }) { return reply(o.status, o.body) }314 switch url.host {315 case "esplora.test", "esplora2.test": return try esplora(method, url.path, request.httpBody, reply)316 case "rpc.test": return reply(200, rpc(request.httpBody ?? Data()))317 case "rpc2.test": return reply(200, rpc(request.httpBody ?? Data(), second: true))318 case "indexer.test":319 if url.path.hasSuffix("/transactions") { return reply(indexerStatus, indexerTransactions) }320 if url.path.hasSuffix("/token-transfers") { return reply(indexerStatus, indexerTokenTransfers) }321 if url.path.hasSuffix("/tokens") { return reply(indexerStatus, indexerTokens) }322 return reply(404, "{}")323 case "pricecheck.test":324 return url.path.hasSuffix("/Ticker") ? reply(checkStatus, checkAnswer(url)) : reply(404, "{}")325 case "prices.test":326 if url.path.hasSuffix("/coins/markets") { return reply(priceStatus, markets) }327 if url.path.hasSuffix("/market_chart") { return reply(priceStatus, marketChart) }328 return reply(404, "{}")329 default:330 throw URLError(.cannotFindHost)331 }332 }333 }334335 private func esplora(_ method: String, _ path: String, _ body: Data?, _ reply: (Int, String) -> (Data, HTTPURLResponse)) throws -> (Data, HTTPURLResponse) {336 let parts = path.split(separator: "/").map(String.init).dropFirst() // drop "api"337 let p = Array(parts)338 if method == "GET", p.count == 3, p[0] == "tx", p[2] == "hex" {339 return rawTransactions[p[1]].map { reply(200, $0) } ?? reply(404, "Transaction not found")340 }341 if method == "POST", p == ["tx"] {342 let hex = String(decoding: body ?? Data(), as: UTF8.self)343 guard let tx = try? BitcoinTransaction(hex: hex) else { return reply(400, "sendrawtransaction RPC error: TX decode failed") }344 broadcastBitcoin.append(hex)345 if acceptBroadcastIntoMempool, !txs.contains(where: { $0.txid == tx.txid }) {346 txs.append(Tx(txid: tx.txid, inputs: tx.inputs.map { ($0.previousOutput.txid, Int($0.previousOutput.index)) },347 outputs: tx.outputs.map { ($0.scriptPubKey, $0.value) }, height: nil))348 }349 return reply(200, bitcoinBroadcastAnswer ?? tx.txid)350 }351 if p == ["block-height", "0"] { return reply(200, genesis) }352 if p == ["blocks", "tip", "height"] { return reply(200, String(tip)) }353 if p == ["fee-estimates"] { return reply(200, feeEstimates) }354 if p.count >= 2, p[0] == "address" {355 guard let script = try? BitcoinAddress(p[1], network: network).scriptPubKey else { return reply(400, "Invalid Bitcoin address") }356 let all = history(of: script)357 if p.count == 3, p[2] == "txs" {358 let mempool = all.filter { $0.height == nil }, chain = all.filter { $0.height != nil }359 return reply(200, json((mempool + chain.prefix(25)).map(txJSON)))360 }361 if p.count == 5, p[2] == "txs", p[3] == "chain" {362 let chain = all.filter { $0.height != nil }363 guard let i = chain.firstIndex(where: { $0.txid == p[4] }) else { return reply(200, "[]") }364 return reply(200, json(chain.dropFirst(i + 1).prefix(25).map(txJSON)))365 }366 if p.count == 2 {367 // as Esplora counts them: an output is funded where its transaction is (chain or mempool), spent where368 // the spending transaction is369 func counters(confirmed: Bool) -> [String: Any] {370 var funded = 0, fundedSum: UInt64 = 0, spent = 0, spentSum: UInt64 = 0371 for t in txs {372 for (n, o) in t.outputs.enumerated() where o.script == script {373 if (t.height != nil) == confirmed {374 funded += 1375 fundedSum += o.value376 }377 if let spender = txs.first(where: { s in s.inputs.contains { $0.txid == t.txid && $0.vout == n } }), (spender.height != nil) == confirmed {378 spent += 1379 spentSum += o.value380 }381 }382 }383 return ["funded_txo_count": funded, "funded_txo_sum": fundedSum, "spent_txo_count": spent, "spent_txo_sum": spentSum,384 "tx_count": all.filter { ($0.height != nil) == confirmed }.count]385 }386 statisticsRequests += 1387 return reply(200, json(["address": p[1], "chain_stats": counters(confirmed: true), "mempool_stats": counters(confirmed: false)]))388 }389 if p.count == 3, p[2] == "utxo" {390 var list = [[String: Any]]()391 for t in txs {392 for (n, o) in t.outputs.enumerated() where o.script == script {393 let spent = txs.contains { s in s.inputs.contains { $0.txid == t.txid && $0.vout == n } }394 if spent { continue }395 var status: [String: Any] = ["confirmed": t.height != nil]396 if let h = t.height {397 status["block_height"] = h398 status["block_hash"] = String(repeating: "0", count: 64)399 status["block_time"] = 1_700_000_000 + h * 600400 }401 list.append(["txid": t.txid, "vout": n, "value": o.value, "status": status])402 }403 }404 return reply(200, json(list))405 }406 }407 return reply(404, "Not found")408 }409410 private func word(_ v: UInt256) -> String { "0x" + Hex.encode(v.bytes32) }411412 private func abiString(_ s: String) -> String {413 let b = Bytes(s.utf8)414 let padded = b + Bytes(repeating: 0, count: (32 - b.count % 32) % 32)415 return "0x" + Hex.encode(UInt256(32).bytes32 + UInt256(UInt64(b.count)).bytes32 + padded)416 }417418 private func rpc(_ body: Data, second: Bool = false) -> String {419 guard let request = try? JSONSerialization.jsonObject(with: body) as? [String: Any], let method = request["method"] as? String else {420 return "{\"jsonrpc\":\"2.0\",\"id\":1,\"error\":{\"code\":-32700,\"message\":\"parse error\"}}"421 }422 let params = request["params"] as? [Any] ?? []423 func result(_ raw: String) -> String { "{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":\(raw)}" }424 func error(_ code: Int, _ message: String) -> String { "{\"jsonrpc\":\"2.0\",\"id\":1,\"error\":{\"code\":\(code),\"message\":\"\(message)\"}}" }425 func quoted(_ s: String) -> String { "\"\(s)\"" }426 if let o = rpcResultOverride[method] { return result(o) }427 func address(_ i: Int) -> String { ((params.count > i ? params[i] : "") as? String ?? "").lowercased() }428 switch method {429 case "eth_chainId": return result(quoted(UInt256(chainID).hexQuantity))430 case "eth_blockNumber": return result(quoted(UInt256(blockNumber).hexQuantity))431 case "eth_getBalance": return result(quoted((balances[address(0)] ?? .zero).hexQuantity))432 case "eth_getTransactionCount":433 let a = address(0)434 let latest = latestNonce[a] ?? 0435 var lead: UInt64 = 0436 if second { lead = secondEndpointNonceLeadQueue.isEmpty ? secondEndpointNonceLead : secondEndpointNonceLeadQueue.removeFirst() }437 return result(quoted(UInt256(((params[1] as? String) == "pending" ? (pendingNonce[a] ?? latest) : latest) + lead).hexQuantity))438 case "eth_getCode":439 let a = address(0)440 if tokens[a] != nil { return result(quoted("0x6080604052")) }441 return result(quoted("0x" + Hex.encode(code[a] ?? [])))442 case "eth_getBlockByNumber":443 return result("{\"number\":\"\(UInt256(blockNumber).hexQuantity)\",\"baseFeePerGas\":\"\(baseFee.hexQuantity)\",\"hash\":\"0x\(String(repeating: "ab", count: 32))\"}")444 case "eth_maxPriorityFeePerGas": return result(quoted(priorityFee.hexQuantity))445 case "eth_estimateGas":446 if let e = gasEstimateError { return error(3, e) }447 return result(quoted(UInt256(gasEstimate).hexQuantity))448 case "eth_call":449 guard let call = params.first as? [String: Any], let to = (call["to"] as? String)?.lowercased(), let dataHex = call["data"] as? String,450 let data = Hex.decode(String(dataHex.dropFirst(2))) else { return error(-32602, "invalid params") }451 guard let token = tokens[to], data.count >= 4 else { return result(quoted("0x")) }452 let selector = Bytes(data[0..<4])453 func arg(_ n: Int) -> String { "0x" + Hex.encode(data[(4 + n * 32 + 12)..<(4 + n * 32 + 32)]) }454 if selector == ERC20.decimalsSelector { return result(quoted(word(token.decimals))) }455 if selector == ERC20.symbolSelector { return result(quoted(abiString(token.symbol))) }456 if selector == ERC20.nameSelector { return result(quoted(abiString(token.name))) }457 if selector == ERC20.balanceOfSelector, data.count == 36 { return result(quoted(word(token.balances[arg(0)] ?? .zero))) }458 if selector == ERC20.allowanceSelector, data.count == 68 { return result(quoted(word(token.allowances["\(arg(0))|\(arg(1))"] ?? .zero))) }459 if selector == ERC20.transferSelector { return result(quoted("0x" + Hex.encode(token.transferReturn))) }460 if selector == ERC20.approveSelector { return result(quoted(word(UInt256(1)))) }461 return error(3, "execution reverted")462 case "eth_sendRawTransaction":463 guard let hex = params.first as? String, let raw = Hex.decode(String(hex.dropFirst(2))) else { return error(-32602, "invalid params") }464 guard let signed = try? SignedEIP1559Transaction.decode(raw) else { return error(-32000, "invalid transaction") }465 broadcastEthereum.append(raw)466 return result(quoted(ethereumBroadcastAnswer ?? signed.hashHex))467 case "eth_getTransactionReceipt": return result(receipts[address(0)] ?? "null")468 case "eth_getTransactionByHash": return result(transactionsByHash[address(0)] ?? "null")469 default: return error(-32601, "method not found")470 }471 }472}473474/// One wallet service on its own temporary directory, vault and fake backend.475struct Harness {476 let service: WalletService477 let vault: Vault478 let backend: FakeBackend479 let clock: TestClock480 let directory: URL481482 static let password = "correct horse battery staple 42"483 static let abandon = ["abandon", "abandon", "abandon", "abandon", "abandon", "abandon", "abandon", "abandon", "abandon", "abandon", "abandon", "about"]484 /// m/84'/1'/0'/0/0 of the BIP-84 test mnemonic.485 static let abandonFirstTestAddress = "tb1q6rz28mcfaxtmd6v789l9rrlrusdprr9pqcpvkl"486 /// m/44'/60'/0'/0/0 of the same mnemonic.487 static let abandonEthereumAddress = "0x9858EfFD232B4033E47d90003D41EC34EcaEda94"488489 static func make(backend: FakeBackend = FakeBackend(), clock: TestClock = TestClock(), directory: URL? = nil, configure: Bool = true,490 internalBuildAllowsMainnet: Bool = false, historyPages: Int = 20) async throws -> Harness {491 let dir = directory ?? FileManager.default.temporaryDirectory.appendingPathComponent("qy-wallet-\(UUID().uuidString)")492 let store = try FileStore(root: dir)493 let vault = Vault(fileStore: store, keychain: InMemoryKeychainStore(), configuration: .init(kdf: .insecureForTesting, now: { clock.now }, monotonic: { clock.monotonic }))494 let service = try WalletService(vault: vault, fileStore: store, transport: backend, now: { clock.now }, monotonic: { clock.monotonic }, sleep: { _ in },495 transactionSeed: 7, backupKDF: .insecureForTesting, internalBuildAllowsMainnet: internalBuildAllowsMainnet,496 historyPagesPerAddress: historyPages)497 if configure { try await service.setEndpoints(FakeBackend.endpoints) }498 return Harness(service: service, vault: vault, backend: backend, clock: clock, directory: dir)499 }500501 /// A full wallet on the BIP-84 test mnemonic.502 static func abandonWallet(backend: FakeBackend = FakeBackend()) async throws -> Harness {503 let h = try await make(backend: backend)504 try await h.service.importWallet(words: abandon, password: password)505 return h506 }507508 func receive(_ index: UInt32) async throws -> String {509 try await service.bitcoinAddresses(chain: .receive, range: index..<(index + 1))[0]510 }511512 func change(_ index: UInt32) async throws -> String {513 try await service.bitcoinAddresses(chain: .change, range: index..<(index + 1))[0]514 }515516 var ethereumAddress: String { get async { await service.currentProfile().ethereumAddress!.checksummed.lowercased() } }517518 func cleanup() { try? FileManager.default.removeItem(at: directory) }519}520521/// An address that belongs to nobody in the tests.522func externalAddress(_ n: UInt8 = 0x77) -> String {523 try! BitcoinAddress(scriptPubKey: try! BitcoinScript.p2wpkh(publicKeyHash: Bytes(repeating: n, count: 20)), network: .signet).string524}525526/// Runs `body` and returns the `WalletError` it throws; records an issue when it does not throw.527func walletError<T>(_ body: () async throws -> T, sourceLocation: SourceLocation = #_sourceLocation) async -> WalletError? {528 do {529 _ = try await body()530 Issue.record("expected a WalletError", sourceLocation: sourceLocation)531 return nil532 } catch let e as WalletError {533 return e534 } catch {535 Issue.record("unexpected error type: \(error)", sourceLocation: sourceLocation)536 return nil537 }538}539540// MARK: - The process-wide mainnet policy and parallel tests541542/// `MainnetPolicy` is one value for the whole process: a wallet service of an internal build configures it when it543/// is created, and every service reads it. Swift Testing runs suites in parallel in one process, so a test that544/// expects the default policy (mainnet off) could run while a test of `MainnetPolicyTests` had mainnet on, and fail545/// for no reason of its own (seen on 2026-12-05: `chainsAreEnabledAndDisabled` and `coldSigningRoundTripWithPSBT`,546/// roughly one run in five once more mainnet tests existed). This lock gives the tests that change the policy the547/// process to themselves, one test at a time, and lets all the others run together between them.548actor MainnetPolicyGate {549 static let shared = MainnetPolicyGate()550 private var readers = 0551 private var writing = false552 private var writersWaiting = 0553 private var waiting: [CheckedContinuation<Void, Never>] = []554555 private func wake() {556 let all = waiting557 waiting = []558 for continuation in all { continuation.resume() }559 }560561 private func pause() async {562 await withCheckedContinuation { waiting.append($0) }563 }564565 func acquire(exclusive: Bool) async {566 if exclusive {567 writersWaiting += 1568 while writing || readers > 0 { await pause() }569 writersWaiting -= 1570 writing = true571 } else {572 // a waiting writer goes first: readers keep arriving and would otherwise never let it in573 while writing || writersWaiting > 0 { await pause() }574 readers += 1575 }576 }577578 func release(exclusive: Bool) {579 if exclusive { writing = false } else { readers -= 1 }580 wake()581 }582}583584/// Scope of one test with respect to the process-wide mainnet policy: `exclusive` for the tests that switch it,585/// shared for every other test of this target.586struct MainnetPolicyScope: SuiteTrait, TestTrait, TestScoping {587 let exclusive: Bool588 var isRecursive: Bool { true }589590 func scopeProvider(for test: Test, testCase: Test.Case?) -> MainnetPolicyScope? {591 test.isSuite || testCase == nil ? nil : self592 }593594 func provideScope(for test: Test, testCase: Test.Case?, performing function: @Sendable () async throws -> Void) async throws {595 await MainnetPolicyGate.shared.acquire(exclusive: exclusive)596 do {597 try await function()598 } catch {599 await MainnetPolicyGate.shared.release(exclusive: exclusive)600 throw error601 }602 await MainnetPolicyGate.shared.release(exclusive: exclusive)603 }604}605606extension Trait where Self == MainnetPolicyScope {607 /// The test changes the process-wide mainnet policy: nothing else of this target runs meanwhile.608 static var changesMainnetPolicy: Self { MainnetPolicyScope(exclusive: true) }609 /// The test reads the policy and expects it untouched (mainnet off).610 static var readsMainnetPolicy: Self { MainnetPolicyScope(exclusive: false) }611}612