Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Tests/QyvoraWalletTests/EVMChainsAuditRegressionTests.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 QyvoraEthereum47import QyvoraNetworking48import QyvoraStorage49import QyvoraSolana50import QyvoraTron51@testable import QyvoraWallet5253// Regression tests of the multi-chain security audit, area "EVM networks and shared wallet machinery"54// (findings QYV-SVC-080 to QYV-SVC-086), and the cross-family tests of the mainnet gate and of the limits: what is55// signed is bounded by the bytes that are signed, whatever a review object, a stored profile or the network mode56// says. They read and change the process-wide mainnet policy, so they belong to the serialized suite.5758extension MainnetPolicyTests {59 /// The private key of the EVM account of the test phrase (m/44'/60'/0'/0/0), for transactions signed outside the wallet.60 static func abandonEthereumKey() throws -> Bytes {61 let master = try ExtendedKey.master(seed: try BIP39.seed(mnemonic: Harness.abandon))62 return try #require(try master.derive(StandardPaths.ethereum()).privateKey)63 }6465 // MARK: QYV-SVC-0806667 /// QYV-SVC-080. `setNetworkMode(.main)` asks for a fresh authentication; the 1.0 setters moved the primary Bitcoin68 /// and EVM networks to a main network without one, and so did `setNetworkMode(.main)` itself when the stored mode69 /// already said "main" while a primary network was on a test network.70 @Test func leavingTheTestNetworksAlwaysNeedsAFreshAuthentication() async throws {71 Self.reset()72 defer { Self.reset() }73 let h = try await Harness.make(internalBuildAllowsMainnet: true)74 defer { h.cleanup() }75 try await h.service.importWallet(words: Harness.abandon, password: Harness.password)76 #expect(try await h.service.setMainnetOptIn(true))77 h.clock.advance(WalletService.authenticationWindow + 1)7879 #expect(await walletError { try await h.service.setEthereumNetwork(.mainnet) } == .authenticationRequired)80 #expect(await walletError { try await h.service.setEthereumNetwork(.base) } == .authenticationRequired)81 #expect(await walletError { try await h.service.setBitcoinNetwork(.mainnet) } == .authenticationRequired)82 #expect(await walletError { try await h.service.setActiveNetworks(bitcoin: .mainnet, ethereum: .mainnet) } == .authenticationRequired)83 #expect(await walletError { try await h.service.setNetworkMode(.main) } == .authenticationRequired)84 var profile = await h.service.currentProfile()85 #expect(profile.bitcoinNetwork == .signet && profile.ethereumNetwork == .sepolia && profile.networkMode == .test)8687 // between test networks nothing is asked88 try await h.service.setEthereumNetwork(.baseSepolia)89 try await h.service.setBitcoinNetwork(.testnet)9091 // with a fresh authentication the switch works, and moving between two main networks asks nothing more92 try await h.service.unlock(password: Harness.password)93 try await h.service.setActiveNetworks(bitcoin: .mainnet, ethereum: .mainnet)94 try await h.service.setNetworkMode(.main)95 h.clock.advance(WalletService.authenticationWindow + 1)96 try await h.service.setEthereumNetwork(.base)97 profile = await h.service.currentProfile()98 #expect(profile.bitcoinNetwork == .mainnet && profile.ethereumNetwork == .base && profile.networkMode == .main)99100 // the stored mode says "main" while a primary network went back to a test network: going forward is a switch101 try await h.service.setBitcoinNetwork(.signet)102 #expect(await h.service.currentProfile().networkMode == .main)103 #expect(await walletError { try await h.service.setNetworkMode(.main) } == .authenticationRequired)104 #expect(await walletError { try await h.service.setBitcoinNetwork(.mainnet) } == .authenticationRequired)105 #expect(await h.service.currentProfile().bitcoinNetwork == .signet)106 }107108 // MARK: QYV-SVC-081109110 /// QYV-SVC-081. A transaction signed outside this build for this wallet's account (another device, an earlier111 /// build) above the ceilings was broadcast by `broadcastSignedEthereum`: the limits were applied when signing112 /// only, although the documentation of `broadcastSigned` says they are applied again.113 @Test func aColdSignedEVMTransactionAboveTheCeilingIsNotBroadcast() async throws {114 Self.reset()115 defer { Self.reset() }116 let h = try await Self.mainnetWallet()117 defer { h.cleanup() }118 let key = try Self.abandonEthereumKey()119 let recipient = try #require(EthereumAddress(EthereumWalletTests.recipient))120 func signed(value: UInt256, maxFee: UInt256 = UInt256(20_000_000_000), data: Bytes = [], to: EthereumAddress? = nil) throws -> String {121 let tx = EIP1559Transaction(chainID: 1, nonce: 0, maxPriorityFeePerGas: UInt256(1_000_000_000), maxFeePerGas: maxFee, gasLimit: data.isEmpty ? 21_000 : 60_000,122 to: to ?? recipient, value: value, data: data)123 return "0x" + Hex.encode(try tx.sign(privateKey: key).raw)124 }125 // 1 ETH: twenty times the ceiling126 #expect(await walletError { try await h.service.broadcastSignedEthereum([try signed(value: EthereumWalletTests.oneEther)]) }127 == .exceedsUnauditedLimit(limit: "0.05 ETH per transaction"))128 // a fee of 21 000 × 600 gwei = 0.0126 ETH: above 0.01 ETH129 #expect(await walletError { try await h.service.broadcastSignedEthereum([try signed(value: UInt256(1), maxFee: UInt256(600_000_000_000))]) }130 == .exceedsUnauditedLimit(limit: "a maximum fee of 0.01 ETH per transaction"))131 // a token transfer to a contract without a known price132 let unknown = try #require(EthereumAddress("0x" + String(repeating: "c7", count: 20)))133 guard case .unauditedLimitUnverifiable? = await walletError({134 try await h.service.broadcastSigned([try signed(value: .zero, data: ERC20.transfer(to: recipient, amount: UInt256(5)), to: unknown)])135 }) else {136 Issue.record("a token transfer that cannot be valued must not be broadcast")137 return138 }139 #expect(h.backend.broadcastEthereum.isEmpty)140 // under the ceilings the transaction goes out, through both entry points141 _ = try await h.service.broadcastSignedEthereum([try signed(value: UInt256(10_000_000_000_000_000))])142 #expect(h.backend.broadcastEthereum.count == 1)143 }144145 // MARK: QYV-SVC-082146147 /// QYV-SVC-082. The dollar ceilings are converted with the price of one source. A source answering a price close to148 /// zero turned "150 USD of POL" into any amount: a price under the floor of the coin is now no price at all.149 @Test func aPriceCloseToZeroDoesNotLiftTheDollarCeilings() async throws {150 Self.reset()151 defer { Self.reset() }152 let recipient = EthereumWalletTests.recipient, coin = EthereumWalletTests.oneEther153 let implausible = WalletError.unauditedLimitUnverifiable("The price sources gave a price for this asset that is not plausible, so its value cannot be checked against the limit.")154 for network in [EthereumNetwork.polygon, .bsc, .avalanche] {155 let h = try await Self.evmMainnetWallet(network)156 defer { h.cleanup() }157 h.backend.balances[EthereumWalletTests.owner] = coin.multipliedReportingOverflow(by: 10_000_000).0158 h.backend.baseFee = network.hasZeroBaseFee ? .zero : UInt256(100_000_000_000)159 h.backend.priorityFee = UInt256(30_000_000_000)160 h.backend.rpcResultOverride["eth_gasPrice"] = EVMNetworkWalletTests.quantity(30_000_000_000)161 let floor = try #require(MainnetPolicy.minimumPlausibleUSDPrice[network.priceID])162 let million = coin.multipliedReportingOverflow(by: 1_000_000).0163164 // fetched for the check: one millionth of a cent per coin would allow 15 billion coins165 h.backend.markets = ServiceTests.market([(network.priceID, "0.00000001")])166 #expect(await walletError { try await h.service.prepareEthereumSend(asset: .ether, to: recipient, amount: million) } == implausible, "\(network)")167 // the same price already in the cache (the dashboard refreshed it)168 try await h.service.refreshMarket()169 #expect(await walletError { try await h.service.prepareEthereumSend(asset: .ether, to: recipient, amount: million) } == implausible, "\(network)")170 #expect(await walletError { try await h.service.prepareEthereumSend(asset: .ether, to: recipient, amount: UInt256(1)) } == implausible, "\(network)")171172 // just under the floor: refused; at the floor: the ceiling is 150 USD / floor coins, the absolute bound173 h.backend.markets = ServiceTests.market([(network.priceID, String(floor * 0.999))])174 try await h.service.refreshMarket()175 #expect(await walletError { try await h.service.prepareEthereumSend(asset: .ether, to: recipient, amount: coin) } == implausible, "\(network)")176 h.backend.markets = ServiceTests.market([(network.priceID, String(floor))])177 try await h.service.refreshMarket()178 let bound = try #require(MainnetPolicy.absoluteNativeCeiling(usd: MainnetPolicy.evmLimits.nativeUSDPerTransaction, priceID: network.priceID))179 let above = UInt256(UInt64(bound * 1.01 * 1_000)).multipliedReportingOverflow(by: UInt256(1_000_000_000_000_000)).0180 #expect(await walletError { try await h.service.prepareEthereumSend(asset: .ether, to: recipient, amount: above) }181 == .exceedsUnauditedLimit(limit: "150 USD of \(network.nativeSymbol) per transaction"), "\(network)")182 Self.reset()183 }184 }185186 /// Every chain whose ceiling is a dollar figure has a price floor: no family converts dollars with an unbounded price.187 @Test func everyDollarCeilingHasAPriceFloor() {188 for chain in ChainRegistry.mainChains {189 switch chain.kind {190 case .utxo(let network):191 guard case .usd? = MainnetPolicy.utxoLimits(network)?.value else {192 #expect(network == .mainnet, "\(chain.id): only Bitcoin has a ceiling in its own unit")193 continue194 }195 #expect(MainnetPolicy.minimumPlausibleUSDPrice[chain.priceID] != nil, "\(chain.id)")196 case .evm(let network):197 if MainnetPolicy.nativeValueCeiling(for: network).needsPrice || MainnetPolicy.feeCeiling(for: network).needsPrice {198 #expect(MainnetPolicy.minimumPlausibleUSDPrice[chain.priceID] != nil, "\(chain.id)")199 }200 case .solana:201 #expect(MainnetPolicy.minimumPlausibleUSDPrice[WalletService.solanaPriceID] != nil && chain.priceID == WalletService.solanaPriceID)202 case .tron:203 #expect(MainnetPolicy.minimumPlausibleUSDPrice[WalletService.tronPriceID] != nil && chain.priceID == WalletService.tronPriceID)204 }205 }206 }207208 // MARK: QYV-SVC-084209210 /// QYV-SVC-084. A token found by the indexer is described by the chain at synchronization. After a restart the211 /// snapshot comes from a file: its symbol and decimals reached the review of a payment (what is shown next to212 /// the amount that is signed). A payment in such a token now needs a synchronization of this session.213 @Test func aDetectedTokenOfARestoredSnapshotIsNotUsedForAPayment() async throws {214 let backend = FakeBackend()215 let h = try await Harness.abandonWallet(backend: backend)216 defer { h.cleanup() }217 let contract = "0x" + String(repeating: "c3", count: 20)218 var token = FakeBackend.TokenContract(symbol: "DET", name: "Detected", decimals: UInt256(6))219 token.balances[EthereumWalletTests.owner] = UInt256(1_000_000)220 backend.tokens[contract] = token221 backend.code[contract] = [0x60, 0x80]222 backend.balances[EthereumWalletTests.owner] = EthereumWalletTests.oneEther223 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}"224 _ = try await h.service.syncEthereum()225 let data = try #require(await h.service.chainSnapshot(.ethereumSepolia)?.data.value)226 let detected = try #require(data.detectedTokens.first?.token)227 #expect(detected.symbol == "DET" && detected.decimals == 6 && !data.isFromPreviousSession)228 // read in this session: the payment can be prepared229 let review = try await h.service.prepareSend(chain: .ethereumSepolia, asset: .token(detected), to: EthereumWalletTests.recipient, amount: UInt256(1_000))230 #expect(review.amountDecimals == 6 && review.amountSymbol == "DET")231232 // next launch: the same token, now known from the file only233 let again = try await Harness.make(backend: backend, clock: h.clock, directory: h.directory, configure: false)234 let restored = try #require(await again.service.chainSnapshot(.ethereumSepolia)?.data.value)235 #expect(restored.isFromPreviousSession && restored.detectedTokens.first?.token == detected)236 #expect(await walletError { try await again.service.prepareSend(chain: .ethereumSepolia, asset: .token(detected), to: EthereumWalletTests.recipient, amount: UInt256(1_000)) }237 == .invalidInput("This token is not in the wallet's list. Add it first."))238 // once read again on chain it can be sent239 _ = try await again.service.syncEthereum()240 _ = try await again.service.prepareSend(chain: .ethereumSepolia, asset: .token(detected), to: EthereumWalletTests.recipient, amount: UInt256(1_000))241 }242243 // MARK: QYV-SVC-086244245 /// QYV-SVC-086. A watch-only package whose Bitcoin account names a network that is not Bitcoin's was refused after246 /// the wallet had been created from it: the caller got an error and a wallet.247 @Test func aWatchOnlyPackageIsValidatedBeforeAnythingIsCreated() async throws {248 Self.reset()249 defer { Self.reset() }250 let cold = try await MultiHarness.wallet(chains: [.bitcoin, .ethereum, .solana, .tron])251 defer { cold.cleanup() }252 let text = try await cold.service.exportWatchOnlyPackage().text253 var package = try JSONDecoder().decode(WatchOnlyPackage.self, from: Data(text.utf8))254 func encoded(_ p: WatchOnlyPackage) throws -> String { String(decoding: try JSONEncoder().encode(p), as: UTF8.self) }255 for network in [BitcoinNetwork.litecoinTestnet, .dogecoinTestnet, .bitcoinCashTestnet, .litecoin] {256 package.bitcoin?.network = network257 let online = try await MultiHarness.make()258 defer { online.cleanup() }259 guard case .invalidPayload? = await walletError({ try await online.service.importWatchOnly(package: [try encoded(package)]) }) else {260 Issue.record("\(network): a package naming it as the Bitcoin network must be refused")261 continue262 }263 #expect(await online.service.currentProfile().kind == nil, "\(network): nothing may be created from a refused package")264 }265 // a main network while mainnet is not enabled: refused by the gate, and nothing is created either266 package.bitcoin?.network = .mainnet267 let online = try await MultiHarness.make()268 defer { online.cleanup() }269 guard case .mainnetDisabled? = await walletError({ try await online.service.importWatchOnly(package: [try encoded(package)]) }) else {270 Issue.record("a mainnet package must be refused while mainnet is disabled")271 return272 }273 #expect(await online.service.currentProfile().kind == nil)274 }275276 // MARK: Cross-family: the mainnet gate277278 /// Every entry point that reads, prepares, signs or broadcasts on a main network of any family is refused while279 /// the gate is closed, before any request leaves the device.280 @Test func everyFamilyIsBehindTheGateAtEveryEntryPoint() async throws {281 Self.reset()282 defer { Self.reset() }283 let h = try await MultiHarness.wallet(chains: ChainRegistry.mainChains.map(\.id))284 defer { h.cleanup() }285 let before = h.backend.requests.count286 let refused = WalletError.mainnetDisabled(WalletError.mainnetText)287 #expect(ChainRegistry.mainChains.count == 13 && Set(ChainRegistry.mainChains.map(\.family)) == Set(ChainFamily.allCases))288 for chain in ChainRegistry.mainChains {289 let id = chain.id290 #expect(await walletError { try await h.service.synchronize(chain: id) } == refused, "synchronize \(id)")291 #expect(await walletError { try await h.service.prepareSend(chain: id, asset: .native, to: "x", amount: UInt256(1)) } == refused, "prepareSend \(id)")292 #expect(await walletError { try await h.service.track(chain: id, id: String(repeating: "0", count: 64)) } == refused, "track \(id)")293 #expect(await walletError { try await h.service.addCustomToken(chain: id, address: "x") } == refused, "addCustomToken \(id)")294 #expect(await h.service.chainSnapshot(id) == nil, "snapshot \(id)")295 // the cold envelope names its chain: a main-network label is refused whatever the payload296 for marker in ["u", "s"] {297 let envelope = "qyvtx1|\(marker)|\(id.rawValue)|AAAA"298 #expect(await walletError { try await h.service.reviewColdTransaction([envelope]) } == refused, "cold review \(id)")299 #expect(await walletError { try await h.service.signColdTransaction([envelope]) } == refused, "cold sign \(id)")300 #expect(await walletError { try await h.service.broadcastSigned([envelope]) } == refused, "cold broadcast \(id)")301 }302 }303 // the per-chain results of a synchronization of everything: main networks are simply not in it304 let results = await h.service.synchronize(chains: ChainRegistry.mainChains.map(\.id))305 #expect(results.count == 13 && results.allSatisfy { $0.error == WalletMessages.text(for: refused) })306 #expect(await h.service.activeChains().allSatisfy(\.isTest))307 #expect(await walletError { try await h.service.setNetworkMode(.main) } == refused)308 #expect(await walletError { try await h.service.setEthereumNetwork(.polygon) } == refused)309 #expect(await walletError { try await h.service.setBitcoinNetwork(.mainnet) } == refused)310 // EVM: a signed or unsigned payload of a main network, by its chain identifier311 let key = try Self.abandonEthereumKey()312 for network in EthereumNetwork.mainNetworks {313 let tx = EIP1559Transaction(chainID: network.chainID, nonce: 0, maxPriorityFeePerGas: UInt256(1), maxFeePerGas: UInt256(2), gasLimit: 21_000,314 to: EthereumAddress(EthereumWalletTests.recipient), value: UInt256(1))315 let unsigned = "0x" + Hex.encode(tx.unsignedPayload), signed = "0x" + Hex.encode(try tx.sign(privateKey: key).raw)316 for attempt in [unsigned, signed] {317 let error = await walletError { try await h.service.signColdTransaction([attempt]) }318 #expect(error == .ethereum(.chainMismatch(expected: 11_155_111, found: network.chainID)) || error == .invalidPayload("Not an unsigned EIP-1559 transaction."), "\(network)")319 }320 #expect(await walletError { try await h.service.broadcastSigned([signed]) } == .ethereum(.chainMismatch(expected: 11_155_111, found: network.chainID)), "\(network)")321 }322 #expect(h.backend.requests.count == before, "a refused call must not reach the network")323 }324325 /// A profile file edited outside the wallet cannot open the gate: with every "main" field set and the user switch326 /// on, a build that does not declare mainnet testing still works on test networks only.327 @Test func aHostileStoredProfileDoesNotOpenTheGate() async throws {328 Self.reset()329 defer { Self.reset() }330 let h = try await MultiHarness.wallet(chains: ChainRegistry.mainChains.map(\.id))331 defer { h.cleanup() }332 var hostile = await h.service.currentProfile()333 hostile.mainnetOptIn = true334 hostile.networkMode = .main335 hostile.bitcoinNetwork = .mainnet336 hostile.ethereumNetwork = .base337 try SettingsStore(fileStore: try h.store, name: WalletService.profileFile).save(hostile)338 let reopened = try await MultiHarness.make(backend: h.backend, clock: h.clock, directory: h.directory, configure: false)339 let profile = await reopened.service.currentProfile()340 #expect(profile.networkMode == .test && profile.bitcoinNetwork == .signet && profile.ethereumNetwork == .baseSepolia)341 #expect(!MainnetPolicy.mainnetEnabled && !MainnetPolicy.mainnetAvailable)342 #expect(await reopened.service.activeChains().allSatisfy(\.isTest))343 #expect(await walletError { try await reopened.service.synchronize(chain: .solana) } == .mainnetDisabled(WalletError.mainnetText))344 #expect(await walletError { try await reopened.service.setNetworkMode(.main) } == .mainnetDisabled(WalletError.mainnetText))345 }346347 // MARK: Cross-family: limits and review objects348349 /// The limits table has an entry for every main network of every family, and none for a test network.350 @Test func everyMainNetworkHasCeilingsAndNoTestNetworkHasAny() async throws {351 Self.reset()352 defer { Self.reset() }353 MainnetPolicy.configure(internalBuildAllowsMainnet: true, userOptedIn: true)354 #expect(MainnetPolicy.unauditedMainnet)355 for chain in ChainRegistry.all {356 let limits = WalletService.limits(chain.kind)357 if chain.isTest {358 #expect(limits == nil, "\(chain.id)")359 continue360 }361 let l = try #require(limits, "\(chain.id) has no ceiling")362 #expect(!l.native.isEmpty && !l.fee.isEmpty && l.native.contains("At most") && (l.tokens != nil) == chain.capabilities.tokens, "\(chain.id)")363 switch chain.kind {364 case .utxo(let network):365 let table = try #require(MainnetPolicy.utxoLimits(network))366 #expect(table.feePerTransaction > 0 && table.feeRatePerVByte > 0)367 switch table.value {368 case .baseUnits(let v): #expect(v == 200_000 && network == .mainnet)369 case .usd(let usd): #expect(usd == 150)370 }371 case .evm(let network):372 #expect(MainnetPolicy.isMainnet(network))373 #expect(MainnetPolicy.nativeValueCeiling(for: network) == (network.nativeIsEther ? .native(UInt256(50_000_000_000_000_000)) : .usd(150)))374 #expect(MainnetPolicy.feeCeiling(for: network) == (network.nativeIsEther ? .native(UInt256(10_000_000_000_000_000)) : .usd(5)))375 case .solana: #expect(MainnetPolicy.solanaLimits.nativeUSDPerTransaction == 150 && MainnetPolicy.solanaLimits.feePerTransaction == 10_000_000)376 case .tron: #expect(MainnetPolicy.tronLimits.nativeUSDPerTransaction == 150 && MainnetPolicy.tronLimits.feePerTransaction == 100_000_000)377 }378 }379 for network in BitcoinNetwork.allCases where network.isTest { #expect(MainnetPolicy.utxoLimits(network) == nil) }380 }381382 /// EVM: a review object altered after the review (a larger value, a larger fee, another network, another account)383 /// is not signed. Review types have no public initializer and no mutable property; the test builds the altered384 /// values with the internal initializer, as code inside the module could, and the signature path refuses each of385 /// them from the bytes it is about to sign.386 @Test func anAlteredEVMReviewIsNotSigned() async throws {387 Self.reset()388 defer { Self.reset() }389 let h = try await Self.evmMainnetWallet(.polygon)390 defer { h.cleanup() }391 let coin = EthereumWalletTests.oneEther392 h.backend.balances[EthereumWalletTests.owner] = coin.multipliedReportingOverflow(by: 1_000).0393 h.backend.baseFee = UInt256(100_000_000_000)394 h.backend.priorityFee = UInt256(30_000_000_000)395 h.backend.markets = ServiceTests.market([("polygon-ecosystem-token", "100.0")])396 let review = try await h.service.prepareEthereumSend(asset: .ether, to: EthereumWalletTests.recipient, amount: coin)397 func altered(_ change: (inout EIP1559Transaction) -> Void, network: EthereumNetwork = .polygon, from: EthereumAddress? = nil) -> EthereumSendReview {398 var tx = review.transaction399 change(&tx)400 // the descriptive fields still say "1 POL": only the transaction differs401 return EthereumSendReview(id: UUID(), network: network, createdAt: review.createdAt, from: from ?? review.from, asset: review.asset, recipient: review.recipient,402 amount: review.amount, transaction: tx, call: review.call, feeTier: review.feeTier, baseFee: review.baseFee,403 maximumFee: review.maximumFee, maximumTotalCost: review.maximumTotalCost, isSendMax: false, warnings: [], l1DataFee: .zero)404 }405 let valueLimit = WalletError.exceedsUnauditedLimit(limit: "150 USD of POL per transaction")406 let feeLimit = WalletError.exceedsUnauditedLimit(limit: "a maximum fee of 5 USD of POL per transaction")407 // 2 POL at 100 USD: above 150 USD — through the EVM entry point and through the uniform one408 let larger = altered { $0.value = coin + coin }409 #expect(await walletError { try await h.service.signAndBroadcastEthereum(larger) } == valueLimit)410 let uniform = await h.service.review(for: larger)411 #expect(uniform.amount == coin && uniform.isMainnet)412 #expect(await walletError { try await h.service.signAndBroadcast(uniform) } == valueLimit)413 // a fee of 21 000 × 5 000 gwei = 0.105 POL = 10.5 USD414 #expect(await walletError { try await h.service.signAndBroadcastEthereum(altered { $0.maxFeePerGas = UInt256(5_000_000_000_000) }) } == feeLimit)415 // a gas limit that multiplies the fee416 guard case .ethereum(.gasLimitTooHigh)? = await walletError({ try await h.service.signAndBroadcastEthereum(altered { $0.gasLimit = 30_000_000 }) }) else {417 Issue.record("a gas limit above the ceiling must be refused")418 return419 }420 // another chain identifier than the network of the review; a network of another chain; another account421 #expect(await walletError { try await h.service.signAndBroadcastEthereum(altered { $0.chainID = 1 }) } == .ethereum(.chainMismatch(expected: 137, found: 1)))422 guard case .stalePlan? = await walletError({ try await h.service.signAndBroadcastEthereum(altered({ _ in }, network: .polygonAmoy)) }),423 case .stalePlan? = await walletError({ try await h.service.signAndBroadcastEthereum(altered({ _ in }, from: EthereumAddress(EthereumWalletTests.recipient))) }) else {424 Issue.record("a review of another network or account must be refused")425 return426 }427 // call data the wallet cannot decode, an approval that is not a revocation, an access list, a contract creation428 guard case .unauditedLimitUnverifiable? = await walletError({ try await h.service.signAndBroadcastEthereum(altered { $0.data = [1, 2, 3, 4]; $0.gasLimit = 60_000 }) }),429 case .unauditedLimitUnverifiable? = await walletError({430 try await h.service.signAndBroadcastEthereum(altered { $0.data = ERC20.approve(spender: review.recipient, amount: UInt256(1)); $0.value = .zero; $0.gasLimit = 60_000 })431 }),432 case .ethereum(.unsupportedTransaction)? = await walletError({433 try await h.service.signAndBroadcastEthereum(altered { $0.accessList = [.init(address: review.recipient, storageKeys: [])] })434 }),435 case .ethereum(.unsupportedTransaction)? = await walletError({ try await h.service.signAndBroadcastEthereum(altered { $0.to = nil }) }) else {436 Issue.record("a transaction outside the supported forms must be refused")437 return438 }439 #expect(h.backend.broadcastEthereum.isEmpty)440441 // the limit context changed after the review (the price doubled): the untouched review is not signed either442 h.backend.markets = ServiceTests.market([("polygon-ecosystem-token", "200.0")])443 try await h.service.refreshMarket()444 let untouched = await h.service.review(for: review)445 #expect(await walletError { try await h.service.signAndBroadcast(untouched) } == valueLimit)446 // and when the price source disappears and the quote is no longer fresh, nothing can be verified447 h.backend.priceStatus = 500448 h.clock.advance(WalletService.quoteFreshness + 1)449 try await h.service.unlock(password: Harness.password)450 guard case .unauditedLimitUnverifiable? = await walletError({ try await h.service.signAndBroadcastEthereum(review) }) else {451 Issue.record("without a fresh price nothing is signed")452 return453 }454 #expect(h.backend.broadcastEthereum.isEmpty)455 }456457 /// A review prepared on a test network is not signed after the wallet moved to the main networks, a review458 /// prepared on a main network is not signed once the gate is closed, and the uniform entry point follows.459 @Test func aReviewDoesNotSurviveAChangeOfNetworkMode() async throws {460 Self.reset()461 defer { Self.reset() }462 let backend = MultiBackend()463 let h = try await MultiHarness.make(backend: backend, internalBuildAllowsMainnet: true)464 defer { h.cleanup() }465 try await h.service.importWallet(words: Harness.abandon, password: Harness.password)466 try await h.service.setEnabledChains([.ethereum, .polygon])467 // prepared on Polygon Amoy: 500 test POL, far above any ceiling of the main network468 let coin = EthereumWalletTests.oneEther469 backend.evm(.polygonAmoy).balances[EthereumWalletTests.owner] = coin.multipliedReportingOverflow(by: 1_000).0470 backend.evm(.polygonAmoy).priorityFee = UInt256(30_000_000_000)471 let test = try await h.service.prepareSend(chain: .polygonAmoy, asset: .native, to: EthereumWalletTests.recipient, amount: coin.multipliedReportingOverflow(by: 500).0)472 #expect(!test.isMainnet && test.limits == nil)473474 #expect(try await h.service.setMainnetOptIn(true))475 try await h.service.setNetworkMode(.main)476 guard case .stalePlan? = await walletError({ try await h.service.signAndBroadcast(test) }) else {477 Issue.record("a test-network review must not be signed in main mode")478 return479 }480 #expect(backend.evm(.polygonAmoy).broadcastEthereum.isEmpty && backend.evm(.polygon).broadcastEthereum.isEmpty)481482 // prepared on Polygon PoS, then the user switch goes off483 backend.base.markets = ServiceTests.market([("polygon-ecosystem-token", "100.0")])484 backend.evm(.polygon).balances[EthereumWalletTests.owner] = coin.multipliedReportingOverflow(by: 10).0485 backend.evm(.polygon).priorityFee = UInt256(30_000_000_000)486 let main = try await h.service.prepareSend(chain: .polygon, asset: .native, to: EthereumWalletTests.recipient, amount: coin)487 #expect(main.isMainnet && main.unauditedMainnet && main.limits != nil && main.hasCriticalWarning)488 #expect(try await h.service.setMainnetOptIn(false) == false)489 #expect(await walletError { try await h.service.signAndBroadcast(main) } == .mainnetDisabled(WalletError.mainnetText))490 #expect(backend.evm(.polygon).broadcastEthereum.isEmpty)491 // back on: the same review is still for the active network and under the ceiling, it can be signed492 #expect(try await h.service.setMainnetOptIn(true))493 try await h.service.setNetworkMode(.main)494 _ = try await h.service.signAndBroadcast(main)495 #expect(backend.evm(.polygon).broadcastEthereum.count == 1)496 }497}498499/// Regressions found by fuzzing in the shared chain model (no mainnet policy involved).500@Suite(.readsMainnetPolicy) struct MultichainExplorerLinkRegressionTests {501 /// QYV-FUZ-080 (fuzz target `network-table`, reproducer security/fuzzing/crashes/network-table/8deb7b19….bin).502 /// The descriptor of a UTXO network built its explorer links from "<base>/tx/" and "<base>/address/" with any503 /// alphanumeric text: on a network without an explorer (Dogecoin Testnet) the result was a URL without a host504 /// ("/address/0xabab…"), a transaction hash of another family was linked as an address, and Dogecoin's explorer505 /// uses another path for transactions.506 @Test func utxoExplorerLinksNeedAnExplorerAndAnAddressOfTheNetwork() throws {507 let hash = String(repeating: "ab", count: 32), evmHash = "0x" + hash508 let key = Bytes(repeating: 0x5a, count: 20)509 for chain in ChainRegistry.all {510 guard case .utxo(let network) = chain.kind else { continue }511 // the reproducer: an EVM transaction hash is not an address of a UTXO network512 #expect(chain.explorerAddressURL(evmHash) == nil, "\(chain.id)")513 #expect(chain.explorerTransactionURL(evmHash) == nil && chain.explorerTransactionURL(hash.uppercased()) == nil, "\(chain.id)")514 let own = try BitcoinAddress(scriptPubKey: try BitcoinScript.p2pkh(publicKeyHash: key), network: network).string515 let transaction = chain.explorerTransactionURL(hash), address = chain.explorerAddressURL(own)516 if let base = network.explorerBaseURL {517 let host = try #require(URL(string: base)?.host)518 #expect(transaction?.host == host && transaction?.scheme == "https" && transaction?.absoluteString == network.explorerTransactionURL(txid: hash), "\(chain.id)")519 #expect(address?.host == host && address?.absoluteString == base + "/address/" + own, "\(chain.id)")520 } else {521 // no explorer is known for the network: no link, rather than a link to nowhere522 #expect(transaction == nil && address == nil, "\(chain.id)")523 #expect(network == .dogecoinTestnet)524 }525 // an address of another coin, an address of another family, text with URL syntax526 for foreign in [MultiHarness.ethereumAddress, MultiHarness.solanaAddress, MultiHarness.tronAddress, own + "/../x", own + "?a=b", own + "#x", "", String(repeating: "a", count: 40)] {527 #expect(chain.explorerAddressURL(foreign) == nil, "\(chain.id): \(foreign)")528 }529 }530 #expect(ChainRegistry.descriptor(.dogecoin)?.explorerTransactionURL(hash)?.absoluteString == "https://blockchair.com/dogecoin/transaction/" + hash)531 // every link of every chain has a host and is https532 for chain in ChainRegistry.all {533 for text in [hash, evmHash, MultiHarness.ethereumAddress, MultiHarness.solanaAddress, MultiHarness.tronAddress] {534 for url in [chain.explorerTransactionURL(text), chain.explorerAddressURL(text)].compactMap({ $0 }) {535 #expect(url.scheme == "https" && !(url.host ?? "").isEmpty, "\(chain.id): \(url)")536 }537 }538 }539 }540}541542/// QYV-APP-080: the code the two devices show for a watch-only package, so that a substituted package is noticed.543/// In the serialized suite: an import reads the process-wide mainnet policy twice.544extension MainnetPolicyTests {545 @Test func theWatchOnlyFingerprintFollowsEveryAccountOfThePackage() async throws {546 Self.reset()547 defer { Self.reset() }548 let cold = try await MultiHarness.wallet(chains: [.bitcoin, .litecoin, .ethereum, .solana, .tron])549 defer { cold.cleanup() }550 let export = try await cold.service.exportWatchOnlyPackage()551 let code = try WalletService.watchOnlyFingerprint(package: [export.text])552 // five groups of four hexadecimal digits, the same from the text and from the QR frames, in any order553 let groups = code.split(separator: "-")554 #expect(groups.count == 5 && groups.allSatisfy { $0.count == 4 && $0.allSatisfy { $0.isHexDigit && !$0.isLowercase } })555 #expect(try WalletService.watchOnlyFingerprint(package: export.frames) == code)556 #expect(try WalletService.watchOnlyFingerprint(package: export.frames.reversed()) == code)557558 var package = try JSONDecoder().decode(WatchOnlyPackage.self, from: Data(export.text.utf8))559 func fingerprint(_ p: WatchOnlyPackage) throws -> String {560 try WalletService.watchOnlyFingerprint(package: [String(decoding: try JSONEncoder().encode(p), as: UTF8.self)])561 }562 // another encoding of the same package (key order, spacing) is the same package563 #expect(try fingerprint(package) == code)564 // the list of enabled chains names no account565 package.enabledChains = ["solana"]566 #expect(try fingerprint(package) == code)567 package.enabledChains = nil568 #expect(try fingerprint(package) == code)569570 // any account replaced by another one changes the code571 var seen = Set([code])572 var other = package573 other.ethereumAddress = EthereumWalletTests.recipient574 #expect(seen.insert(try fingerprint(other)).inserted)575 other = package576 other.solanaAddress = solanaStranger().base58577 #expect(seen.insert(try fingerprint(other)).inserted)578 other = package579 other.tronAddress = tronStranger().base58580 #expect(seen.insert(try fingerprint(other)).inserted)581 other = package582 other.tronAddress = nil583 #expect(seen.insert(try fingerprint(other)).inserted)584 let stranger = try ExtendedKey.master(seed: Bytes(repeating: 0x5a, count: 64))585 other = package586 other.accounts?["litecoinTestnet"]?.extendedPublicKey = try stranger.derive(WalletService.utxoAccountPath(.litecoinTestnet)).neutered.serialized(.tpub)587 #expect(seen.insert(try fingerprint(other)).inserted)588 other = package589 other.accounts?["litecoinTestnet"] = nil590 #expect(seen.insert(try fingerprint(other)).inserted)591 other = package592 other.bitcoin?.extendedPublicKey = try stranger.derive(StandardPaths.bip84Account(.signet)).neutered.serialized(.tpub)593 #expect(seen.insert(try fingerprint(other)).inserted)594 other = package595 other.bitcoin?.masterFingerprint = "00000000"596 #expect(seen.insert(try fingerprint(other)).inserted)597 other = package598 other.bitcoin = nil599 #expect(seen.insert(try fingerprint(other)).inserted)600 #expect(seen.count == 10)601602 // the EVM address is the same account in any letter case603 other = package604 other.ethereumAddress = package.ethereumAddress?.lowercased()605 #expect(try fingerprint(other) == code)606607 // not a package: no code608 for text in ["", "{}", "null", "[]", "{\"format\":\"qyvora-watch-only\",\"version\":3}", "{\"format\":\"x\",\"version\":2}", String(repeating: "a", count: 70_000)] {609 #expect(throws: WalletError.self) { try WalletService.watchOnlyFingerprint(package: [text]) }610 }611 // the companion that imports the untouched package watches the accounts the code stands for612 let online = try await MultiHarness.make()613 defer { online.cleanup() }614 #expect(try WalletService.watchOnlyFingerprint(package: export.frames) == code)615 try await online.service.importWatchOnly(package: export.frames)616 let watched = await online.service.currentProfile(), mine = await cold.service.currentProfile()617 #expect(watched.ethereumAddress == mine.ethereumAddress && watched.solanaAddress == mine.solanaAddress && watched.tronAddress == mine.tronAddress)618 }619}620