Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Tests/QyvoraWalletTests/UTXOCoinTests.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 QyvoraCore45import QyvoraBitcoin46import QyvoraNetworking47import QyvoraMigration48import QyvoraRecovery49@testable import QyvoraWallet5051/// Litecoin, Dogecoin and Bitcoin Cash in the wallet service, against the scripted Esplora-shaped backend (the52/// `UTXOIndexer` protocol makes the indexer dialect indifferent to the service). No network.53enum CoinFixture {54 /// Addresses of the "abandon … about" phrase, from Tests/QyvoraBitcoinTests/UTXOReferenceVectors.swift (bip_utils).55 static let litecoin0 = "ltc1qjmxnz78nmc8nq77wuxh25n2es7rzm5c2rkk4wh"56 static let litecoinTestnet0 = "tltc1q6rz28mcfaxtmd6v789l9rrlrusdprr9pesrjxk"57 static let dogecoin0 = "DBus3bamQjgJULBJtYXpEzDWQRwF5iwxgC"58 static let dogecoinTestnet0 = "nZVmfmUtKPmskB9Ds4P9GUJy9eYFqPKHqH"59 static let bitcoinCash0 = "bitcoincash:qqyx49mu0kkn9ftfj6hje6g2wfer34yfnq5tahq3q6"6061 /// The scripted backend also answers for `network` on the Esplora host.62 static func endpoints(_ networks: [BitcoinNetwork]) -> EndpointConfiguration {63 var e = FakeBackend.endpoints64 for n in networks { e.esplora[n.rawValue] = ["https://esplora.test/api"] }65 return e66 }6768 static func serve(_ backend: FakeBackend, _ network: BitcoinNetwork) {69 backend.network = network70 backend.genesis = network.genesisHash71 let identity = network.identityBlock72 if identity.height != 0 { backend.overrides.append(("block-height/\(identity.height)", 200, identity.hash)) }73 }7475 /// An address of `network` that belongs to nobody.76 static func external(_ network: BitcoinNetwork, _ n: UInt8 = 0x77) -> String {77 let hash = Bytes(repeating: n, count: 20)78 let script = network.supportsSegWit ? try! BitcoinScript.p2wpkh(publicKeyHash: hash) : try! BitcoinScript.p2pkh(publicKeyHash: hash)79 return try! BitcoinAddress(scriptPubKey: script, network: network).string80 }8182 /// A full wallet on the test phrase, test mode, with `chain` enabled and served by the backend.83 static func wallet(chain: ChainID, network: BitcoinNetwork) async throws -> Harness {84 let h = try await Harness.abandonWallet()85 try await h.service.setEndpoints(endpoints([network]))86 try await h.service.setChainEnabled(chain, enabled: true)87 serve(h.backend, network)88 return h89 }9091 static func plan(_ review: SendReview) throws -> BitcoinSendPlan {92 guard case .bitcoin(let plan) = review.body else { throw WalletError.invalidInput("not a UTXO review") }93 return plan94 }95}9697@Suite(.readsMainnetPolicy) struct UTXOCoinTests {98 @Test func accountsOfEveryCoinMatchThePublishedVectors() async throws {99 let h = try await Harness.abandonWallet()100 defer { h.cleanup() }101 let profile = await h.service.currentProfile()102 let expected: [(BitcoinNetwork, String, String)] = [103 (.litecoin, CoinFixture.litecoin0, "m/84'/2'/0'"), (.litecoinTestnet, CoinFixture.litecoinTestnet0, "m/84'/1'/0'"),104 (.dogecoin, CoinFixture.dogecoin0, "m/44'/3'/0'"), (.dogecoinTestnet, CoinFixture.dogecoinTestnet0, "m/44'/1'/0'"),105 (.bitcoinCash, CoinFixture.bitcoinCash0, "m/44'/145'/0'"),106 ]107 for (network, address, path) in expected {108 let data = try #require(profile.bitcoinAccounts[network.rawValue])109 let account = try UTXOAccount(extendedKey: data.extendedPublicKey, network: network)110 #expect(try account.address(chain: .receive, index: 0).string == address)111 #expect(account.accountPath.description == path)112 #expect(ChainRegistry.descriptor(ChainRegistry.id(network))?.derivationPath == path)113 }114 let cashTest = try UTXOAccount(extendedKey: try #require(profile.bitcoinAccounts["bitcoinCashTestnet"]).extendedPublicKey, network: .bitcoinCashTestnet)115 #expect(try cashTest.address(chain: .receive, index: 0).string.hasPrefix("bchtest:q") && cashTest.accountPath.description == "m/44'/1'/0'")116 // Bitcoin keeps its two keys of 1.0117 #expect(profile.bitcoinAccounts["test"] != nil && profile.bitcoinAccounts["main"] != nil && profile.bitcoinAccounts.count == 8)118119 // registry120 #expect(ChainRegistry.mainChains.filter { $0.family == .utxo }.map(\.id) == [.bitcoin, .litecoin, .dogecoin, .bitcoinCash])121 let doge = try #require(ChainRegistry.descriptor(.dogecoinTestnet))122 #expect(doge.nativeSymbol == "DOGE" && doge.mainCounterpart == .dogecoin && !doge.capabilities.historyAvailable && !doge.capabilities.coldSigning)123 #expect(ChainRegistry.descriptor(.litecoin)?.testCounterparts == [.litecoinTestnet] && ChainRegistry.descriptor(.bitcoinCash)?.priceID == "bitcoin-cash")124125 // the recovery sheet lists every coin with its path, key, descriptor and first address126 let sheet = try await h.service.recoverySheet()127 func entry(_ name: String) throws -> RecoverySheet.ChainAccount { try #require(sheet.otherChains.first { $0.chain == name }) }128 let ltc = try entry("Litecoin"), dogeEntry = try entry("Dogecoin"), bch = try entry("Bitcoin Cash")129 #expect(ltc.address == CoinFixture.litecoin0 && ltc.derivationPath == "m/84'/2'/0'" && ltc.descriptor?.hasPrefix("wpkh([73c5da0a/84h/2h/0h]xpub") == true)130 #expect(dogeEntry.address == CoinFixture.dogecoin0 && dogeEntry.descriptor?.hasPrefix("pkh([73c5da0a/44h/3h/0h]xpub") == true)131 #expect(bch.address == CoinFixture.bitcoinCash0 && bch.extendedPublicKey == profile.bitcoinAccounts["bitcoinCash"]?.extendedPublicKey)132 #expect(sheet.plainText().contains(CoinFixture.dogecoin0) && sheet.otherChains.contains { $0.chain == "Solana" })133 }134135 @Test func aWalletMadeBeforeTheCoinsGetsTheirAccountsAtUnlock() async throws {136 let h = try await Harness.abandonWallet()137 defer { h.cleanup() }138 let full = try #require(await h.service.currentProfile().publicData)139 // the state of a wallet written before the coins existed: Bitcoin's two keys only, in the profile and in the vault140 var old = full141 old.accounts = full.accounts.filter { $0.key == "test" || $0.key == "main" }142 try await h.service.storeAccountBinding(old)143 await h.service.replaceAccountDataForTesting(old)144 #expect(await h.service.currentProfile().bitcoinAccounts.count == 2)145 await h.service.lock()146 try await h.service.unlock(password: Harness.password)147 #expect(await h.service.currentProfile().publicData == full)148 #expect(await h.service.accountBindingRepairCount() == 0)149 #expect(try await h.service.accountBindingRecord()?.data == full)150151 // a coin key replaced in the profile file is a repair, as for Bitcoin152 var forged = full153 forged.accounts["litecoinTestnet"] = full.accounts["dogecoinTestnet"]154 await h.service.replaceAccountDataForTesting(forged)155 await h.service.lock()156 try await h.service.unlock(password: Harness.password)157 #expect(await h.service.currentProfile().publicData == full)158 #expect(await h.service.accountBindingRepairCount() == 1)159 }160161 @Test func litecoinTestnetSyncSendAndShield() async throws {162 let h = try await CoinFixture.wallet(chain: .litecoin, network: .litecoinTestnet)163 defer { h.cleanup() }164 #expect(await h.service.activeChains().map(\.id).contains(.litecoinTestnet))165 let funding = h.backend.fund(CoinFixture.litecoinTestnet0, 500_000)166167 let results = await h.service.synchronize(chains: [.litecoinTestnet])168 #expect(results == [ChainSyncResult(chain: .litecoinTestnet, error: nil)])169 let snapshot = try #require(await h.service.snapshot().chain(.litecoinTestnet))170 let data = try #require(snapshot.data.value)171 #expect(data.native.confirmed == UInt256(500_000) && data.native.symbol == "LTC" && data.native.decimals == 8 && !snapshot.isPrimary)172 #expect(data.history.value?.map(\.hash) == [funding] && data.history.value?.first?.direction == .received)173 #expect(snapshot.receive?.rule == .freshAddressPerPayment && snapshot.receive?.address.hasPrefix("tltc1q") == true && snapshot.receive?.address != CoinFixture.litecoinTestnet0)174 #expect(snapshot.receive?.derivationPath == "m/84'/1'/0'/0/1" && snapshot.limits == nil)175 guard case .utxo(let coins)? = snapshot.data.value?.extras else {176 Issue.record("no UTXO extras")177 return178 }179 #expect(coins.network == .litecoinTestnet && coins.utxos.count == 1)180 // Bitcoin's own state is untouched181 #expect(await h.service.latestBitcoinSnapshot() == nil)182 let valuation = await h.service.portfolioValuation()183 #expect(valuation.lines.contains { $0.chain == .litecoinTestnet && $0.amount == "0.005" && $0.isTestNetwork })184185 let fees = try await h.service.feeOptions(chain: .litecoinTestnet)186 #expect(fees.source == .estimates && fees.slow.rate <= fees.normal.rate && fees.normal.rate <= fees.fast.rate && fees.slow.rate >= .minimum(for: .litecoinTestnet))187188 let recipient = CoinFixture.external(.litecoinTestnet)189 let review = try await h.service.prepareSend(chain: .litecoinTestnet, asset: .native, to: recipient, amount: UInt256(100_000))190 let plan = try CoinFixture.plan(review)191 #expect(plan.network == .litecoinTestnet && review.amount == UInt256(100_000) && review.amountSymbol == "LTC" && !review.isMainnet)192 #expect(review.warnings.contains { $0.id == "first-payment" } && review.fee.expected == UInt256(plan.fee))193 let sent = try await h.service.signAndBroadcast(review)194 #expect(h.backend.broadcastBitcoin.count == 1 && sent.chain == .litecoinTestnet)195 let tx = try BitcoinTransaction(hex: h.backend.broadcastBitcoin[0])196 #expect(tx.txid == sent.id && tx.txid == plan.txid && tx.outputs.contains { $0.value == 100_000 })197 try BitcoinVerifier.verify(transaction: tx, spentOutputs: plan.plan.inputs.map(\.output))198 // the coin just spent is not offered again before the next synchronization199 guard case .bitcoinBuild? = await walletError({ try await h.service.prepareSend(chain: .litecoinTestnet, asset: .native, to: recipient, amount: UInt256(100_000)) }) else {200 Issue.record("a coin spent in this session was offered again")201 return202 }203 _ = await h.service.synchronize(chains: [.litecoinTestnet])204 #expect(try await h.service.track(chain: .litecoinTestnet, id: sent.id) == .pending)205 let again = try await h.service.prepareSend(chain: .litecoinTestnet, asset: .native, to: recipient, amount: UInt256(50_000),206 options: { var o = SendOptions(); o.coinControl = BitcoinCoinControl(includeUnconfirmed: true); return o }())207 #expect(again.warnings.contains { $0.id == "btc.destination-already-paid" })208209 // shield: the coin is analysed like Bitcoin, and section 3 names its network210 let shield = await h.service.shieldReport()211 #expect(shield.report.keyExposure.otherCoins.map(\.network) == [.litecoinTestnet])212 #expect(shield.report.keyExposure.otherCoins[0].findings.allSatisfy { $0.id.hasPrefix("ltc.") })213 #expect(shield.report.networkResistance.chains.contains { $0.networkName == "Litecoin Testnet" && !$0.offersQuantumResistance })214 #expect(shield.measuredAt[.litecoinTestnet] != nil)215 // cold signing is not offered for the coins216 guard case .featureUnavailable? = await walletError({ try await h.service.exportUnsigned(again) }) else {217 Issue.record("expected featureUnavailable")218 return219 }220 }221222 @Test func bitcoinCashTestnetIdentityAddressesAndForkIdSpend() async throws {223 let h = try await Harness.abandonWallet()224 defer { h.cleanup() }225 try await h.service.setEndpoints(CoinFixture.endpoints([.bitcoinCashTestnet]))226 try await h.service.setChainEnabled(.bitcoinCash, enabled: true)227 // an endpoint on another chain with the same genesis block (chipnet, Bitcoin testnet…) is refused228 h.backend.network = .bitcoinCashTestnet229 h.backend.overrides.append(("block-height/200000", 200, String(repeating: "0", count: 63) + "1"))230 guard case .wrongChain? = await walletError({ try await h.service.synchronize(chain: .bitcoinCashTestnet) }) else {231 Issue.record("expected wrongChain")232 return233 }234 h.backend.overrides.removeAll()235 CoinFixture.serve(h.backend, .bitcoinCashTestnet)236237 let receive = try #require(await h.service.snapshot().chain(.bitcoinCashTestnet)?.receive)238 #expect(receive.address.hasPrefix("bchtest:q") && receive.derivationPath == "m/44'/1'/0'/0/0")239 h.backend.fund(receive.address, 400_000)240 try await h.service.synchronize(chain: .bitcoinCashTestnet)241 #expect(await h.service.snapshot().chain(.bitcoinCashTestnet)?.data.value?.native.confirmed == UInt256(400_000))242243 // address rules244 let recipient = CoinFixture.external(.bitcoinCashTestnet)245 #expect(recipient.hasPrefix("bchtest:"))246 let bare = String(recipient.dropFirst("bchtest:".count))247 #expect(await walletError { try await h.service.checkAddress(bare, chain: .bitcoinCashTestnet) }248 == .address(.missingPrefix(chain: "Bitcoin Cash", prefix: "bchtest")))249 #expect(await walletError { try await h.service.prepareSend(chain: .bitcoinCashTestnet, asset: .native, to: bare, amount: UInt256(1_000)) }250 == .address(.missingPrefix(chain: "Bitcoin Cash", prefix: "bchtest")))251 guard case .address(.wrongFamily(let chain, let found))? = await walletError({ try await h.service.checkAddress("tb1q6rz28mcfaxtmd6v789l9rrlrusdprr9pqcpvkl", chain: .bitcoinCashTestnet) }) else {252 Issue.record("expected wrongFamily")253 return254 }255 #expect(chain == "Bitcoin Cash" && found == "a Bitcoin")256 #expect(try await h.service.checkAddress(receive.address, chain: .bitcoinCashTestnet).isOwnAddress)257258 let review = try await h.service.prepareSend(chain: .bitcoinCashTestnet, asset: .native, to: recipient, amount: UInt256(120_000))259 let plan = try CoinFixture.plan(review)260 let sent = try await h.service.signAndBroadcast(review)261 let tx = try BitcoinTransaction(hex: h.backend.broadcastBitcoin[0], allowWitness: false)262 #expect(tx.txid == sent.id && tx.outputs.contains { $0.value == 120_000 })263 // no replace-by-fee signal on Bitcoin Cash, and the fork-id signature verifies264 #expect(tx.inputs.allSatisfy { $0.sequence >= 0xffff_fffe })265 try BitcoinVerifier.verify(transaction: tx, spentOutputs: plan.plan.inputs.map(\.output), scheme: .bip143ForkID)266 #expect(review.notes.isEmpty)267 }268269 @Test func addressesOfOtherChainsAreRefusedWithThePreciseReason() async throws {270 let h = try await Harness.abandonWallet()271 defer { h.cleanup() }272 func refusal(_ text: String, _ chain: ChainID) async -> AddressRefusal? {273 if case .address(let r)? = await walletError({ try await h.service.checkAddress(text, chain: chain) }) { return r }274 return nil275 }276 // a Bitcoin address on Litecoin, a Litecoin address on Bitcoin, an EVM address on Dogecoin277 #expect(await refusal("tb1q6rz28mcfaxtmd6v789l9rrlrusdprr9pqcpvkl", .litecoinTestnet) == .wrongFamily(chain: "Litecoin", found: "a Bitcoin"))278 #expect(await refusal(MainnetPolicyTests.mainnetAddress, .litecoin) == .wrongFamily(chain: "Litecoin", found: "a Bitcoin"))279 #expect(await refusal(CoinFixture.litecoinTestnet0, .bitcoinSignet) == .wrongFamily(chain: "Bitcoin", found: "a Litecoin"))280 #expect(await refusal(Harness.abandonEthereumAddress, .dogecoin) == .wrongFamily(chain: "Dogecoin", found: "an Ethereum (EVM)"))281 // a test address on the main network of the same coin282 #expect(await refusal(CoinFixture.litecoinTestnet0, .litecoin) == .wrongNetwork(chain: "Litecoin", found: "Litecoin Testnet"))283 // the former Litecoin script form ("3…") cannot be told from a Bitcoin address284 guard case .unsupported(let text)? = await refusal("3J98t1WpEZ73CNmQviecrnyiWrnqRhWNLy", .litecoin) else {285 Issue.record("expected the ambiguous-format refusal")286 return287 }288 #expect(text.contains("former Litecoin script address format"))289 #expect(try await h.service.checkAddress(CoinFixture.dogecoin0, chain: .dogecoin).isOwnAddress)290 #expect(WalletError.address(.missingPrefix(chain: "Bitcoin Cash", prefix: "bitcoincash")).userMessage.contains("bitcoincash:"))291 }292293 @Test func dogecoinTestnetIsShownAsUnavailable() async throws {294 let h = try await Harness.abandonWallet()295 defer { h.cleanup() }296 try await h.service.setChainEnabled(.dogecoin, enabled: true)297 let before = h.backend.requests.count298 guard case .featureUnavailable(let text)? = await walletError({ try await h.service.synchronize(chain: .dogecoinTestnet) }) else {299 Issue.record("expected featureUnavailable")300 return301 }302 #expect(text.contains("no keyless public indexer") && h.backend.requests.count == before)303 let snapshot = try #require(await h.service.snapshot().chain(.dogecoinTestnet))304 #expect(snapshot.data == .unavailable(reason: text) && snapshot.syncError == text)305 #expect(snapshot.receive?.address == CoinFixture.dogecoinTestnet0 && snapshot.receive?.notes.contains(text) == true)306 #expect(!snapshot.chain.capabilities.historyAvailable)307 // the other chains are not held back by it308 let results = await h.service.synchronize(chains: [.dogecoinTestnet, .bitcoinSignet])309 #expect(results.map(\.succeeded) == [false, true])310 }311312 @Test func hostileIndexerAnswersNeverCrashAndNeverCount() async throws {313 let h = try await CoinFixture.wallet(chain: .litecoin, network: .litecoinTestnet)314 defer { h.cleanup() }315 let txid = h.backend.fund(CoinFixture.litecoinTestnet0, 500_000)316 let path = "address/\(CoinFixture.litecoinTestnet0)"317 func failure(_ match: String, _ body: String) async -> WalletError? {318 h.backend.overrides = [(match, 200, body)]319 defer { h.backend.overrides = [] }320 return await walletError { try await h.service.synchronize(chain: .litecoinTestnet) }321 }322 // not JSON, a coin above the monetary range, a coin that disagrees with its transaction, a duplicate coin323 for body in ["<html>", "{\"chain_stats\":7}", "[]"] {324 // whatever the answer, the synchronization fails with a typed error and nothing else happens325 #expect(await failure("GET esplora.test/api/\(path)", body) != nil)326 }327 let status = "{\"confirmed\":true,\"block_height\":100,\"block_hash\":\"\(String(repeating: "0", count: 64))\",\"block_time\":1700060000}"328 guard case .untrustedResponse? = await failure("\(path)/utxo", "[{\"txid\":\"\(txid)\",\"vout\":0,\"value\":18446744073709551615,\"status\":\(status)}]") else {329 Issue.record("a coin above the monetary range was accepted")330 return331 }332 guard case .untrustedResponse? = await failure("\(path)/utxo", "[{\"txid\":\"\(txid)\",\"vout\":0,\"value\":499999,\"status\":\(status)}]") else {333 Issue.record("a coin that disagrees with its transaction was accepted")334 return335 }336 let coin = "{\"txid\":\"\(txid)\",\"vout\":0,\"value\":500000,\"status\":\(status)}"337 guard case .untrustedResponse? = await failure("\(path)/utxo", "[\(coin),\(coin)]") else {338 Issue.record("a duplicate coin was accepted")339 return340 }341 // a history that does not involve the address342 let foreign = Hex.encode(try BitcoinAddress(CoinFixture.external(.litecoinTestnet), network: .litecoinTestnet).scriptPubKey)343 let out = "{\"scriptpubkey\":\"\(foreign)\",\"scriptpubkey_type\":\"v0_p2wpkh\",\"value\":5}"344 let unrelated = "[{\"txid\":\"\(String(repeating: "ab", count: 32))\",\"version\":2,\"locktime\":0,\"vin\":[{\"txid\":\"\(String(repeating: "cd", count: 32))\",\"vout\":0,\"prevout\":\(out),\"sequence\":1}],\"vout\":[\(out)],\"size\":100,\"weight\":400,\"fee\":0,\"status\":\(status)}]"345 guard case .untrustedResponse? = await failure("\(path)/txs", unrelated) else {346 Issue.record("a transaction that does not involve the address was accepted")347 return348 }349 // nothing of all that reached the snapshot; an honest answer then does350 #expect(await h.service.snapshot().chain(.litecoinTestnet)?.data.value == nil)351 try await h.service.synchronize(chain: .litecoinTestnet)352 #expect(await h.service.snapshot().chain(.litecoinTestnet)?.data.value?.native.confirmed == UInt256(500_000))353 }354355 @Test func coldModeMakesNoRequestForTheCoins() async throws {356 let backend = FakeBackend()357 backend.forbidAllRequests = true358 let h = try await Harness.make(backend: backend)359 defer { h.cleanup() }360 try await h.service.setColdMode(true)361 try await h.service.importWallet(words: Harness.abandon, password: Harness.password)362 try await h.service.setEnabledChains([.bitcoin, .litecoin, .dogecoin, .bitcoinCash])363 let snapshot = await h.service.snapshot()364 #expect(snapshot.chain(.litecoinTestnet)?.receive?.address == CoinFixture.litecoinTestnet0)365 #expect(snapshot.chain(.dogecoinTestnet)?.receive?.address == CoinFixture.dogecoinTestnet0)366 #expect(snapshot.chain(.bitcoinCashTestnet)?.receive?.address.hasPrefix("bchtest:") == true)367 let results = await h.service.synchronize()368 #expect(results.count == 4 && results.allSatisfy { !$0.succeeded })369 #expect(await walletError { try await h.service.synchronize(chain: .litecoinTestnet) } == .offline)370 #expect(await walletError { try await h.service.feeOptions(chain: .litecoinTestnet) } == .offline)371 #expect(await walletError { try await h.service.prepareSend(chain: .litecoinTestnet, asset: .native, to: CoinFixture.external(.litecoinTestnet), amount: UInt256(1)) } == .offline)372 #expect(backend.requests.isEmpty)373 #expect(await h.service.networkRequestCount() == 0)374 }375376 @Test func theMigrationRegistryListsTheCoinsWithNothingQuantumResistantAvailable() {377 for chain in [MigrationEngine.Chain.litecoin, .dogecoin, .bitcoinCash] {378 let entries = MigrationEngine.capabilities(for: chain)379 #expect(entries.count == 4 && !MigrationEngine.chainOffersQuantumResistance(chain))380 #expect(entries.filter(\.quantumResistant).allSatisfy { $0.status == .awaitingProtocol })381 }382 #expect(MigrationEngine.isEnabled("ltc.p2wpkh") && MigrationEngine.isEnabled("doge.p2pkh") && MigrationEngine.isEnabled("bch.p2pkh"))383 // the guided sweep of exposed coins exists for every UTXO coin; nothing post-quantum is available on any384 #expect(MigrationEngine.isEnabled("doge.rotation") && MigrationEngine.isEnabled("ltc.rotation") && MigrationEngine.isEnabled("bch.rotation"))385 #expect(!MigrationEngine.isEnabled("bch.utxo-migration") && !MigrationEngine.isEnabled("doge.pq-output"))386 #expect(Set(MigrationEngine.capabilities.map(\.id)).count == MigrationEngine.capabilities.count)387 }388}389390/// Main networks of the coins: the gate, the limits at prepare and at sign, Dogecoin's previous transactions.391/// In the serialized suite: `MainnetPolicy` is process-wide.392extension MainnetPolicyTests {393 static func coinMainnetWallet(_ chain: ChainID, _ network: BitcoinNetwork) async throws -> Harness {394 let h = try await mainnetWallet()395 try await h.service.setEndpoints(CoinFixture.endpoints([network]))396 try await h.service.setNetworkMode(.main)397 try await h.service.setChainEnabled(chain, enabled: true)398 CoinFixture.serve(h.backend, network)399 return h400 }401402 /// Here because what a package imports depends on the mainnet gate, which is process-wide.403 @Test func watchOnlyWalletsAndPackagesCarryTheCoinAccounts() async throws {404 Self.reset()405 defer { Self.reset() }406 let full = try await Harness.abandonWallet()407 defer { full.cleanup() }408 // the package names the chains the device shows: the companion shows the same ones409 try await full.service.setEnabledChains([.bitcoin, .litecoin, .dogecoin, .bitcoinCash, .ethereum, .solana, .tron])410 let package = try await full.service.exportWatchOnlyPackage()411 let decoded = try JSONDecoder().decode(WatchOnlyPackage.self, from: Data(package.text.utf8))412 #expect(decoded.version == 2 && decoded.accounts?.count == 6 && decoded.accounts?["dogecoin"] != nil)413 let key = try #require(decoded.accounts?["litecoinTestnet"]?.extendedPublicKey)414415 // from a package: the test-network accounts only, while mainnet is not enabled416 let fromPackage = try await Harness.make()417 defer { fromPackage.cleanup() }418 try await fromPackage.service.importWatchOnly(package: package.frames)419 let profile = await fromPackage.service.currentProfile()420 #expect(profile.kind == .watchOnly && Set(profile.bitcoinAccounts.keys) == ["test", "litecoinTestnet", "dogecoinTestnet", "bitcoinCashTestnet"])421 #expect(profile.enabledChains == [.bitcoin, .litecoin, .dogecoin, .bitcoinCash, .ethereum, .solana, .tron])422 #expect(await fromPackage.service.snapshot().chain(.litecoinTestnet)?.receive?.address == CoinFixture.litecoinTestnet0)423424 // from a key typed by the user425 let typed = try await Harness.make()426 defer { typed.cleanup() }427 try await typed.service.importWatchOnly(bitcoinExtendedPublicKey: nil, ethereumAddress: nil, accounts: ["litecoinTestnet": key])428 #expect(await typed.service.currentProfile().enabledChains == [.litecoin])429 #expect(await typed.service.snapshot().chain(.litecoinTestnet)?.receive?.address == CoinFixture.litecoinTestnet0)430 // it can prepare, never sign431 try await typed.service.setEndpoints(CoinFixture.endpoints([.litecoinTestnet]))432 CoinFixture.serve(typed.backend, .litecoinTestnet)433 typed.backend.fund(CoinFixture.litecoinTestnet0, 300_000)434 try await typed.service.synchronize(chain: .litecoinTestnet)435 let review = try await typed.service.prepareSend(chain: .litecoinTestnet, asset: .native, to: CoinFixture.external(.litecoinTestnet), amount: UInt256(10_000))436 #expect(await walletError { try await typed.service.signAndBroadcast(review) } == .watchOnly)437438 // refusals: a main-network key without mainnet, a private key, a Bitcoin network name, a key of the wrong side439 let other = try await Harness.make()440 defer { other.cleanup() }441 let main = try #require(decoded.accounts?["litecoin"]?.extendedPublicKey)442 guard case .mainnetDisabled? = await walletError({ try await other.service.importWatchOnly(bitcoinExtendedPublicKey: nil, ethereumAddress: nil, accounts: ["litecoin": main]) }) else {443 Issue.record("expected mainnetDisabled")444 return445 }446 for (name, text) in [("signet", key), ("litecoinTestnet", main), ("nowhere", key), ("litecoinTestnet", "tprv8ZgxMBicQKsPd")] {447 guard case .invalidInput? = await walletError({ try await other.service.importWatchOnly(bitcoinExtendedPublicKey: nil, ethereumAddress: nil, accounts: [name: text]) }) else {448 Issue.record("\(name) was accepted")449 continue450 }451 }452 }453454 @Test func theCoinsAreBehindTheMainnetGate() async throws {455 Self.reset()456 defer { Self.reset() }457 let h = try await Harness.abandonWallet()458 defer { h.cleanup() }459 try await h.service.setEnabledChains([.bitcoin, .litecoin, .dogecoin, .bitcoinCash])460 #expect(await h.service.activeChains().map(\.id) == [.bitcoinSignet, .litecoinTestnet, .dogecoinTestnet, .bitcoinCashTestnet])461 for chain in [ChainID.litecoin, .dogecoin, .bitcoinCash] {462 guard case .mainnetDisabled? = await walletError({ try await h.service.synchronize(chain: chain) }) else {463 Issue.record("\(chain) is not behind the gate")464 continue465 }466 guard case .mainnetDisabled? = await walletError({ try await h.service.prepareSend(chain: chain, asset: .native, to: "x", amount: UInt256(1)) }) else {467 Issue.record("\(chain) can be paid without the gate")468 continue469 }470 #expect(await h.service.snapshot().chain(chain) == nil)471 }472 guard case .mainnetDisabled? = await walletError({ try await h.service.setNetworkMode(.main) }) else {473 Issue.record("main mode without the gate")474 return475 }476 #expect(h.backend.requests.isEmpty)477 }478479 @Test func dogecoinMainnetLimitsAtPrepareAndAtSignAndPreviousTransactions() async throws {480 Self.reset()481 defer { Self.reset() }482 let h = try await Self.coinMainnetWallet(.dogecoin, .dogecoin)483 defer { h.cleanup() }484 try await h.service.setChainEnabled(.litecoin, enabled: true)485 try await h.service.setChainEnabled(.bitcoinCash, enabled: true)486 let dashboard = await h.service.snapshot()487 #expect(dashboard.chain(.dogecoin)?.limits?.native == "At most 150 USD of DOGE per transaction, checked with fresh prices from two sources that agree; refused otherwise.")488 #expect(dashboard.chain(.dogecoin)?.limits?.fee == "Fee of a transaction: at most 5 DOGE and 100000 koinus per virtual byte.")489 #expect(dashboard.chain(.litecoin)?.limits?.fee == "Fee of a transaction: at most 0.001 LTC and 200 litoshis per virtual byte.")490 #expect(dashboard.chain(.bitcoinCash)?.limits?.fee == "Fee of a transaction: at most 0.0005 BCH and 20 satoshis per virtual byte.")491 #expect(dashboard.chain(.bitcoin)?.limits?.native == "At most 0.002 BTC per transaction.")492493 let funding = h.backend.fundReal(CoinFixture.dogecoin0, 100_000_000_000) // 1000 DOGE, with its raw transaction494 try await h.service.synchronize(chain: .dogecoin)495 #expect(await h.service.snapshot().chain(.dogecoin)?.data.value?.native.confirmed == UInt256(100_000_000_000))496 let recipient = CoinFixture.external(.dogecoin)497 let ten = UInt256(1_000_000_000)498499 // no price: nothing can be checked, nothing is prepared500 h.backend.priceStatus = 500501 guard case .unauditedLimitUnverifiable? = await walletError({ try await h.service.prepareSend(chain: .dogecoin, asset: .native, to: recipient, amount: ten) }) else {502 Issue.record("prepared without a price")503 return504 }505 // 0.5 USD per DOGE: 300 DOGE at most506 h.backend.priceStatus = 200507 h.backend.markets = ServiceTests.market([("dogecoin", "0.5")])508 let review = try await h.service.prepareSend(chain: .dogecoin, asset: .native, to: recipient, amount: ten)509 let plan = try CoinFixture.plan(review)510 #expect(review.isMainnet && review.unauditedMainnet && review.warnings.contains { $0.id == "unaudited-mainnet" && $0.isCritical })511 #expect(plan.fee >= 200_000 && plan.fee <= 500_000_000 && review.limits != nil)512 _ = try await h.service.prepareSend(chain: .dogecoin, asset: .native, to: recipient, amount: UInt256(30_000_000_000))513 #expect(await walletError { try await h.service.prepareSend(chain: .dogecoin, asset: .native, to: recipient, amount: UInt256(30_000_000_001)) }514 == .exceedsUnauditedLimit(limit: "150 USD of DOGE per transaction (300 DOGE at the current price)"))515 #expect(await walletError { try await h.service.prepareSend(chain: .dogecoin, asset: .native, to: recipient, amount: .zero, options: { var o = SendOptions(); o.sendMax = true; return o }()) }516 == .exceedsUnauditedLimit(limit: "150 USD of DOGE per transaction (300 DOGE at the current price)"))517 // a fee rate above the ceiling of the build (1 DOGE per kB)518 #expect(await walletError { try await h.service.prepareSend(chain: .dogecoin, asset: .native, to: recipient, amount: ten, options: { var o = SendOptions(); o.bitcoinFeeRate = FeeRate(satPerVByte: 100_001); return o }()) }519 == .bitcoinBuild(.feeRateOutOfRange))520521 // at sign: the price moved to 100 USD, the same plan is now above the limit522 h.clock.advance(WalletService.quoteFreshness + 60)523 h.backend.markets = ServiceTests.market([("dogecoin", "100")])524 try await h.service.unlock(password: Harness.password)525 #expect(await walletError { try await h.service.signAndBroadcast(review) }526 == .exceedsUnauditedLimit(limit: "150 USD of DOGE per transaction (1.5 DOGE at the current price)"))527 h.clock.advance(WalletService.quoteFreshness + 60)528 h.backend.markets = ServiceTests.market([("dogecoin", "0.5")])529 try await h.service.unlock(password: Harness.password)530531 // Dogecoin signatures do not commit to the amounts: the previous transaction must be served and must hash to its identifier532 let honest = try #require(h.backend.rawTransactions[funding])533 h.backend.rawTransactions[funding] = nil534 guard case .network? = await walletError({ try await h.service.signAndBroadcast(review) }) else {535 Issue.record("signed without the previous transaction")536 return537 }538 let other = BitcoinTransaction(inputs: [.init(previousOutput: BitcoinOutPoint(txid: String(repeating: "11", count: 32), vout: 0)!, scriptSig: [0x51])],539 outputs: [.init(value: 100_000_000_000, scriptPubKey: plan.plan.inputs[0].scriptPubKey)])540 h.backend.rawTransactions[funding] = other.hex541 guard case .untrustedResponse? = await walletError({ try await h.service.signAndBroadcast(review) }) else {542 Issue.record("signed with a previous transaction that does not hash to the outpoint")543 return544 }545 #expect(h.backend.broadcastBitcoin.isEmpty)546 h.backend.rawTransactions[funding] = honest547548 let sent = try await h.service.signAndBroadcast(review)549 let tx = try BitcoinTransaction(hex: h.backend.broadcastBitcoin[0], allowWitness: false)550 #expect(tx.txid == sent.id && tx.outputs.contains { $0.value == 1_000_000_000 } && tx.inputs.allSatisfy { !$0.scriptSig.isEmpty })551 try BitcoinVerifier.verify(transaction: tx, spentOutputs: plan.plan.inputs.map(\.output), scheme: .legacy)552 #expect(sent.explorerURL?.absoluteString.contains(sent.id) == true)553 }554}555