SPB Git

Repository Public

ServiceTests.swift 53.7 KB 838 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Tests/QyvoraWalletTests/ServiceTests.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 QyvoraCore45import QyvoraBitcoin46import QyvoraEthereum47import QyvoraNetworking48import QyvoraStorage49import QyvoraVault50import QyvoraQuantumShield51import QyvoraMigration52import QyvoraRecovery53@testable import QyvoraWallet5455@Suite(.readsMainnetPolicy) struct ServiceTests {56    static func market(_ rows: [(String, String)]) -> String {57        "[" + rows.map { "{\"id\":\"\($0.0)\",\"symbol\":\"x\",\"name\":\"X\",\"current_price\":\($0.1),\"price_change_percentage_24h_in_currency\":1.5,\"price_change_percentage_7d_in_currency\":-2.25,\"sparkline_in_7d\":{\"price\":[1.0,2.0,3.0]},\"last_updated\":\"2026-12-04T00:00:00.000Z\"}" }.joined(separator: ",") + "]"58    }5960    @Test func coldModeMakesNoNetworkCallAtAll() async throws {61        let backend = FakeBackend()62        backend.forbidAllRequests = true63        let h = try await Harness.make(backend: backend)64        defer { h.cleanup() }65        try await h.service.setColdMode(true)6667        // everything that needs no network keeps working68        let words = try await h.service.createWallet(password: Harness.password)69        #expect(try await h.service.verifyPhraseBackup(words: words))70        #expect(try await h.service.bitcoinAddresses(chain: .receive, range: 0..<3).count == 3)71        #expect(try await h.service.nextReceiveAddress().index == 0)72        let package = try await h.service.exportWatchOnlyPackage()73        #expect(package.text.contains("qyvora-watch-only"))74        _ = try await h.service.recoverySheet()75        _ = await h.service.shieldReport()76        _ = await h.service.snapshot()77        _ = await h.service.portfolioValuation()78        try await h.service.setBitcoinNetwork(.testnet)79        try await h.service.setEndpoints(.default)8081        // everything that needs the network says so, with a typed error82        #expect(await walletError { try await h.service.syncBitcoin() } == .offline)83        #expect(await walletError { try await h.service.syncEthereum() } == .offline)84        #expect(await walletError { try await h.service.bitcoinFeeOptions() } == .offline)85        #expect(await walletError { try await h.service.refreshMarket() } == .offline)86        #expect(await walletError { try await h.service.priceChart(assetID: "bitcoin", range: .week) } == .offline)87        #expect(await walletError { try await h.service.prepareEthereumSend(asset: .ether, to: EthereumWalletTests.recipient, amount: UInt256(1)) } == .offline)88        #expect(await walletError { try await h.service.addCustomToken(address: EthereumWalletTests.usdc) } == .offline)89        #expect(await walletError { try await h.service.trackEthereumTransaction(hash: EthereumWalletTests.hash(1)) } == .offline)90        #expect(await walletError { try await h.service.broadcastSignedEthereum(["0x02c0"]) } != nil)9192        let dashboard = await h.service.snapshot()93        #expect(dashboard.profile.coldMode)94        #expect(dashboard.bitcoin == .unavailable(reason: "Cold mode is on: this device makes no network request."))95        #expect(dashboard.market.quotes.isEmpty && dashboard.market.unavailableReason?.contains("Cold mode") == true)96        #expect(dashboard.valuation.realValue == nil && dashboard.valuation.referenceValue == nil)9798        // not one request left the device; the flag survives a restart99        #expect(backend.requests.isEmpty)100        #expect(await h.service.networkRequestCount() == 0)101        let reopened = try await Harness.make(backend: backend, directory: h.directory, configure: false)102        #expect(await walletError { try await reopened.service.syncBitcoin() } == .offline)103        #expect(backend.requests.isEmpty)104105        // leaving cold mode restores the network106        backend.forbidAllRequests = false107        try await h.service.setColdMode(false)108        try await h.service.setEndpoints(FakeBackend.endpoints)109        try await h.service.setBitcoinNetwork(.signet)110        #expect(try await h.service.syncBitcoin().balance.total == 0)111        #expect(!backend.requests.isEmpty)112    }113114    @Test func pricesAreDatedStaleLabelledAndNeverInvented() async throws {115        let h = try await EthereumWalletTests.funded()116        defer { h.cleanup() }117        h.backend.fund(try await h.receive(0), 150_000_000)118        _ = try await h.service.syncBitcoin()119        _ = try await h.service.syncEthereum()120121        // before any fetch: no price, no value, and the reason122        var valuation = await h.service.portfolioValuation()123        #expect(valuation.realValue == nil && valuation.referenceValue == nil && valuation.pricedAt == nil)124        #expect(valuation.unpricedAssets == ["BTC", "ETH"])125        #expect(valuation.lines.map(\.amount) == ["1.5", "2"])126        #expect(await h.service.marketSnapshot().unavailableReason == "Prices have not been fetched yet.")127128        // hostile rows are dropped: negative, absurd, text, unknown identifier129        h.backend.markets = Self.market([("bitcoin", "60000.5"), ("ethereum", "3000"), ("dogecoin", "1"), ("usd-coin", "-1"), ("tether", "1e300"), ("dai", "\"1.0\"")])130        let fetchedAt = h.clock.now131        let market = try await h.service.refreshMarket()132        #expect(Set(market.quotes.keys) == ["bitcoin", "ethereum"])133        let btc = try #require(market.quotes["bitcoin"])134        #expect(btc.price == 60_000.5 && btc.currency == .usd && btc.fetchedAt == fetchedAt && !btc.isStale)135        #expect(btc.change24h == 1.5 && btc.change7d == -2.25 && btc.sparkline7d == [1, 2, 3])136        #expect(market.unavailableReason == nil)137        #expect(h.backend.requests.last?.contains("vs_currency=usd") == true)138        #expect(h.backend.requests.last?.contains("ids=bitcoin,ethereum") == true)139140        // test-network coins have no monetary value: only a flagged reference value141        valuation = await h.service.portfolioValuation()142        #expect(valuation.isTestNetwork && valuation.realValue == nil)143        #expect(valuation.referenceValue == 1.5 * 60_000.5 + 2 * 3_000)144        #expect(valuation.lines.allSatisfy { $0.isTestNetwork && $0.value == nil && $0.referenceValue != nil })145        #expect(!valuation.isStale && valuation.pricedAt == fetchedAt && valuation.unpricedAssets.isEmpty)146        #expect(await h.service.snapshot().valuation == valuation)147148        // ten minutes later the same quote is labelled stale, with its original date149        h.clock.advance(601)150        var later = await h.service.marketSnapshot()151        #expect(later.quotes["bitcoin"]?.isStale == true && later.quotes["bitcoin"]?.fetchedAt == fetchedAt)152        #expect(await h.service.portfolioValuation().isStale)153        // a failed refresh keeps the last known value, stale, and reports the failure154        h.backend.priceStatus = 500155        guard case .network? = await walletError({ try await h.service.refreshMarket() }) else {156            Issue.record("expected a network error")157            return158        }159        later = await h.service.marketSnapshot()160        #expect(later.quotes["bitcoin"]?.price == 60_000.5 && later.quotes["bitcoin"]?.isStale == true)161        #expect(later.unavailableReason?.contains("unavailable") == true)162163        // a new session starts from the persisted last-known quotes: always stale until refreshed164        h.backend.priceStatus = 200165        let reopened = try await Harness.make(backend: h.backend, clock: h.clock, directory: h.directory, configure: false)166        let persisted = await reopened.service.marketSnapshot()167        #expect(persisted.quotes["ethereum"]?.price == 3_000 && persisted.quotes["ethereum"]?.isStale == true)168        #expect(persisted.quotes["ethereum"]?.fetchedAt == fetchedAt)169        #expect(persisted.unavailableReason != nil)170        let refreshed = try await reopened.service.refreshMarket()171        #expect(refreshed.quotes["ethereum"]?.isStale == false && refreshed.quotes["ethereum"]?.fetchedAt == h.clock.now)172173        // another currency has its own quotes: nothing is converted or carried over174        try await h.service.setDisplayCurrency(.cad)175        #expect(await h.service.marketSnapshot().quotes.isEmpty)176        #expect(await h.service.portfolioValuation().referenceValue == nil)177        // a price source that returns nothing usable is an error, not a zero178        h.backend.markets = "[{\"id\":\"bitcoin\",\"current_price\":null},{\"id\":\"ethereum\"}]"179        guard case .untrustedResponse? = await walletError({ try await h.service.refreshMarket() }) else {180            Issue.record("expected untrustedResponse")181            return182        }183        h.backend.markets = "{\"status\":{\"error_code\":429}}"184        #expect(await walletError { try await h.service.refreshMarket() } != nil)185        #expect(await h.service.marketSnapshot().quotes.isEmpty)186187        // charts188        h.backend.marketChart = "{\"prices\":[[1764806400000,61000.0],[1764720000000,60000.0],[1764892800000,\"x\"],[1764892800000,-4]],\"market_caps\":[],\"total_volumes\":[]}"189        let chart = try await h.service.priceChart(assetID: "bitcoin", range: .week)190        #expect(chart.points.map(\.price) == [60_000, 61_000] && !chart.isStale && chart.range == .week && chart.currency == .cad)191        #expect(h.backend.requests.last?.contains("days=7") == true)192        h.clock.advance(700)193        h.backend.priceStatus = 503194        let stale = try await h.service.priceChart(assetID: "bitcoin", range: .week)195        #expect(stale.isStale && stale.points == chart.points && stale.fetchedAt == chart.fetchedAt)196        #expect(await walletError { try await h.service.priceChart(assetID: "ethereum", range: .year) } != nil)197        #expect(ChartRange.allCases.map(\.days) == [1, 7, 30, 365])198    }199200    @Test func shieldReportFromWalletState() async throws {201        // fresh wallet, nothing synchronized: sections say what was not measured202        let fresh = try await Harness.make()203        defer { fresh.cleanup() }204        _ = try await fresh.service.createWallet(password: "tr0ub4dor&3 horse staple battery")205        var shield = await fresh.service.shieldReport()206        #expect(shield.report.keyExposure.bitcoin == nil)207        #expect(shield.report.keyExposure.ethereum?.publicKeyRecoverable == nil)208        #expect(shield.report.keyExposure.ethereum?.openApprovals == nil)209        // nothing was measured on either chain: the section is not assessed, never "in good order"210        #expect(shield.report.keyExposure.level == .unknown && shield.report.keyExposure.isPartlyUnmeasured)211        #expect(shield.report.vaultSecurity.level == .critical)   // the phrase has not been verified yet212        #expect(shield.report.vaultSecurity.findings.contains { $0.id == "vault.phrase.unverified" })213        #expect(shield.report.vaultSecurity.findings.contains { $0.id == "vault.backup.none" })214        #expect(shield.disclaimer == QuantumShield.localCryptographyDisclaimer)215        #expect(shield.report.networkResistance.chains.map(\.chain) == [.bitcoin, .ethereum])216        #expect(shield.report.networkResistance.chains.allSatisfy { !$0.offersQuantumResistance && !$0.awaitingProtocol.isEmpty })217        #expect(shield.report.networkResistance.chains[0].networkName == "Bitcoin Signet")218        // only the protocol-dependent steps, all blocked219        #expect(shield.migrationPlan.steps.map(\.id) == ["btc-pq", "eth-pq"])220        #expect(shield.migrationPlan.actionable.isEmpty && shield.migrationPlan.blocked.count == 2)221        #expect(await fresh.service.migrationPlan() == shield.migrationPlan)222223        // a wallet with reuse, a spent-from address, outgoing transactions and an open approval224        let s = try await BitcoinWalletTests.scenario()225        defer { s.h.cleanup() }226        let h = s.h227        h.backend.balances[EthereumWalletTests.owner] = EthereumWalletTests.oneEther228        h.backend.latestNonce[EthereumWalletTests.owner] = 4229        var token = FakeBackend.TokenContract(symbol: "USDC", name: "USD Coin", decimals: UInt256(6))230        token.allowances["\(EthereumWalletTests.owner)|\(EthereumWalletTests.spender)"] = UInt256(25_000_000)231        h.backend.tokens[EthereumWalletTests.usdc.lowercased()] = token232        let spender = try #require(EthereumAddress(EthereumWalletTests.spender))233        h.backend.indexerTransactions = "{\"items\":[\(EthereumWalletTests.nativeItem(hash: EthereumWalletTests.hash(3), from: Harness.abandonEthereumAddress, to: EthereumWalletTests.usdc, value: "0", method: "approve"))]}"234        h.backend.transactionsByHash[EthereumWalletTests.hash(3)] =235            "{\"from\":\"\(EthereumWalletTests.owner)\",\"to\":\"\(EthereumWalletTests.usdc)\",\"input\":\"0x\(Hex.encode(ERC20.approve(spender: spender, amount: UInt256(25_000_000))))\"}"236        _ = try await h.service.syncBitcoin()237        let eth = try await h.service.syncEthereum()238        #expect(eth.approvals.value?.count == 1 && eth.approvals.value?.first?.isUnlimited == false)239        // the approval's token was not in the list: it is described from the chain240        #expect(eth.approvals.value?.first?.token.symbol == "USDC")241242        shield = await h.service.shieldReport()243        let btc = try #require(shield.report.keyExposure.bitcoin)244        #expect(btc.totals.revealedBySpend == 50_000 && btc.totals.hashedUnrevealed == 69_000)245        #expect(btc.exposedUTXOCount == 1 && btc.reusedAddresses.map(\.address) == [s.a0])246        #expect(btc.hashedUnrevealedShareBasisPoints == 5_798)247        let e = try #require(shield.report.keyExposure.ethereum)248        #expect(e.outgoingTransactionCount == 4 && e.publicKeyRecoverable == true && e.openApprovals?.count == 1)249        #expect(e.compatibilityNotes.contains { $0.id == "eth.pq-validation" && $0.status == .awaitingProtocol })250        #expect(shield.report.keyExposure.level == .attention && !shield.report.keyExposure.isPartlyUnmeasured)251        #expect(shield.report.vaultSecurity.findings.contains { $0.id == "vault.phrase.verified" })252        #expect(shield.migrationPlan.steps.map(\.id) == ["sweep-btc", "rotate-eth", "revoke-approvals", "btc-pq", "eth-pq"])253        #expect(shield.migrationPlan.actionable.map(\.id) == ["sweep-btc", "revoke-approvals"])254        #expect(MigrationEngine.isEnabled("btc.rotation") && !MigrationEngine.isEnabled("btc.utxo-migration"))255256        // acting on the plan changes the next report257        _ = try await h.service.signAndBroadcastBitcoin(try await h.service.prepareSweepOfExposedBitcoin(feeRate: FeeRate(satPerVByte: 1)))258        _ = try await h.service.syncBitcoin()259        #expect(await h.service.shieldReport().report.keyExposure.bitcoin?.exposedUTXOCount == 0)260    }261262    @Test func identityBackupRestoreAndTransfer() async throws {263        let h = try await Harness.abandonWallet()264        defer { h.cleanup() }265        let directory = FileManager.default.temporaryDirectory.appendingPathComponent("qy-backup-\(UUID().uuidString)")266        try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)267        defer { try? FileManager.default.removeItem(at: directory) }268269        // identity270        #expect(try await h.service.identity() == nil)271        guard case .featureUnavailable? = await walletError({ try await h.service.signMessage([1, 2, 3]) }) else {272            Issue.record("expected featureUnavailable")273            return274        }275        let created = try await h.service.createIdentity()276        #expect(created.text.hasPrefix("qyvora-id:") && created.fingerprintText.split(separator: " ").count == 16 && created.rotationCount == 0)277        #expect(try await h.service.identity() == created)278        guard case .invalidInput? = await walletError({ try await h.service.createIdentity() }) else {279            Issue.record("a second identity must be refused")280            return281        }282        let exported = try await h.service.exportPublicIdentity()283        #expect(exported.text == created.text && exported.frames.count > 1)284        let message = Bytes("hello".utf8)285        let signature = try await h.service.signMessage(message)286        #expect(h.service.verifyMessage(message, signature: signature, signer: created.text))287        #expect(!h.service.verifyMessage(Bytes("hellO".utf8), signature: signature, signer: created.text))288        #expect(!h.service.verifyMessage(message, signature: signature, signer: "qyvora-id:AAAA"))289        await h.service.lock()290        #expect(await walletError { try await h.service.signMessage(message) } == .vaultLocked)291        #expect(await walletError { try await h.service.identity() } == .vaultLocked)292        try await h.service.unlock(password: Harness.password)293294        // rotation: new keys, certificate, old signature still verifies against the old public identity only295        let rotated = try await h.service.rotateIdentity(dual: false)296        #expect(rotated.identity.text != created.text && rotated.identity.rotationCount == 1 && !rotated.certificate.isEmpty)297        #expect(try await h.service.identity() == rotated.identity)298        #expect(try await h.service.identityRotationChain() != nil)299        #expect(!h.service.verifyMessage(message, signature: signature, signer: rotated.identity.text))300        #expect(try await h.vault.report().recordCounts == ["recoveryPhrase": 1, "identityKeys": 1, "custom": 1, "watchOnlyAccount": 1])301302        // recovery sheet303        let sheet = try await h.service.recoverySheet()304        #expect(sheet.privateMaterial == nil && sheet.masterFingerprint == "73c5da0a")305        #expect(sheet.ethereum.first?.address == Harness.abandonEthereumAddress)306        #expect(sheet.bitcoin.contains { $0.firstReceiveAddress == Harness.abandonFirstTestAddress })307        #expect(try await h.service.recoverySheet(includePrivateMaterial: true).privateMaterial?.mnemonic == Harness.abandon.joined(separator: " "))308309        // signed backup file310        let url = directory.appendingPathComponent("wallet.qyvora")311        guard case .weakPassword? = await walletError({ try await h.service.createBackup(to: url, password: "") }) else {312            Issue.record("an empty backup password must be refused")313            return314        }315        #expect(await h.service.currentProfile().lastBackupDate == nil)316        let header = try await h.service.createBackup(to: url, password: "backup river stone 71", sign: true)317        #expect(header.isSigned && header.recordCount == 4 && header.createdAt == h.clock.now)318        // creating the file records nothing: the user has not saved it anywhere yet319        #expect(await h.service.currentProfile().lastBackupDate == nil)320        #expect(await h.service.currentProfile().lastBackupSigned == nil)321        #expect(await h.service.shieldReport().report.vaultSecurity.findings.contains { $0.id == "vault.backup.none" })322        h.clock.advance(90)323        try await h.service.recordBackupSaved(signed: header.isSigned)324        #expect(await h.service.currentProfile().lastBackupDate == h.clock.now)325        #expect(await h.service.currentProfile().lastBackupSigned == true)326        #expect(try await h.service.inspectBackup(at: url) == header)327        #expect(await h.service.shieldReport().report.vaultSecurity.findings.contains { $0.id == "vault.backup.recent" })328        // the file holds no plain secret329        let fileText = String(decoding: try Data(contentsOf: url), as: UTF8.self)330        #expect(!fileText.contains("abandon"))331332        // restore on a device without wallet333        let target = try await Harness.make()334        defer { target.cleanup() }335        #expect(await walletError { try await target.service.restoreBackup(from: url, backupPassword: "wrong", newPassword: "new device granite lamp 5") } == .wrongPassword)336        #expect(await target.vault.exists == false)337        guard case .storage? = await walletError({ try await target.service.restoreBackup(from: directory.appendingPathComponent("missing"), backupPassword: "x", newPassword: "y") }) else {338            Issue.record("expected storage error")339            return340        }341        guard case .invalidPayload? = await walletError({342            try await target.service.restoreBackup(from: url, backupPassword: "backup river stone 71", newPassword: "new device granite lamp 5",343                                                   expectedSignerFingerprint: Bytes(repeating: 9, count: 32))344        }) else {345            Issue.record("an unexpected signer must be refused")346            return347        }348        try await target.service.restoreBackup(from: url, backupPassword: "backup river stone 71", newPassword: "new device granite lamp 5")349        #expect(try await target.receive(0) == Harness.abandonFirstTestAddress)350        #expect(await target.service.currentProfile().ethereumAddress?.checksummed == Harness.abandonEthereumAddress)351        #expect(await target.service.currentProfile().kind == .full)352        #expect(await target.service.currentProfile().lastBackupSigned == true)353        #expect(try await target.service.identity() == rotated.identity)354        #expect(try await target.service.revealRecoveryPhrase() == Harness.abandon)355        await target.service.lock()356        try await target.service.unlock(password: "new device granite lamp 5")357        #expect(await walletError { try await h.service.restoreBackup(from: url, backupPassword: "backup river stone 71", newPassword: "x") } == .walletAlreadyExists)358        // a damaged file is refused before anything is created359        var damaged = Bytes(try Data(contentsOf: url))360        damaged[damaged.count / 2] ^= 0x01361        let bad = directory.appendingPathComponent("damaged.qyvora")362        try Data(damaged).write(to: bad)363        let third = try await Harness.make()364        defer { third.cleanup() }365        guard case .invalidPayload? = await walletError({ try await third.service.restoreBackup(from: bad, backupPassword: "backup river stone 71", newPassword: "new device granite lamp 5") }) else {366            Issue.record("a damaged backup must be refused")367            return368        }369        #expect(await third.vault.exists == false)370        #expect(await third.service.currentProfile().kind == nil)371372        // device-to-device transfer: the new device shows its identity, the old one wraps a backup for it373        let reception = try await third.service.beginTransferReception()374        let transfer = try await h.service.createTransferPackage(to: reception.export.frames, backupPassword: "transfer copper owl 38")375        #expect(!transfer.package.isEmpty)376        let package = transfer.frames.isEmpty ? transfer.package : try third.service.assembleTransferPackage(frames: transfer.frames.shuffled())377        #expect(package == transfer.package)378        // a package made for another device cannot be opened379        let stranger = try await Harness.make()380        defer { stranger.cleanup() }381        _ = try await stranger.service.beginTransferReception()382        #expect(await walletError { try await stranger.service.inspectTransferPackage(package: package) } != nil)383        #expect(await walletError {384            try await stranger.service.completeTransferReception(package: package, backupPassword: "transfer copper owl 38", newPassword: "p",385                                                                 expectedSender: rotated.identity.text)386        } != nil)387        #expect(await stranger.vault.exists == false)388389        // step 2 on the right device: the sender is known BEFORE anything is restored390        let inspection = try await third.service.inspectTransferPackage(package: package)391        #expect(inspection.sender.text == rotated.identity.text && inspection.sender.fingerprintText == rotated.identity.fingerprintText)392        #expect(inspection.backup.isSigned && inspection.backup.recordCount == 4)393        #expect(await third.vault.exists == false)394        #expect(await third.service.currentProfile().kind == nil)395        #expect(await third.service.snapshot().hasWallet == false)396        // inspecting is repeatable and consumes nothing397        #expect(try await third.service.inspectTransferPackage(package: package) == inspection)398        // a package altered in transit fails at inspection: its signature no longer verifies399        var altered = package400        altered[altered.count - 20] ^= 0x01401        #expect(await walletError { try await third.service.inspectTransferPackage(package: altered) } != nil)402        #expect(await walletError { try await third.service.inspectTransferPackage(package: Array(package.prefix(100))) } != nil)403        #expect(await third.vault.exists == false)404405        // step 3: the identity the user confirmed is pinned; another one restores nothing406        #expect(await walletError {407            try await third.service.completeTransferReception(package: package, backupPassword: "transfer copper owl 38", newPassword: "p", expectedSender: created.text)408        } != nil)409        #expect(await walletError {410            try await third.service.completeTransferReception(package: package, backupPassword: "transfer copper owl 38", newPassword: "p", expectedSender: "not an identity")411        } != nil)412        #expect(await third.vault.exists == false)413        let sender = try await third.service.completeTransferReception(package: package, backupPassword: "transfer copper owl 38", newPassword: "third device amber kiln 4",414                                                                       expectedSender: inspection.sender.text)415        #expect(sender == rotated.identity.fingerprintText)416        // the temporary identity is gone: the package cannot be inspected or opened again417        #expect(await walletError { try await third.service.inspectTransferPackage(package: package) } != nil)418        #expect(try await third.receive(0) == Harness.abandonFirstTestAddress)419        #expect(try await third.service.revealRecoveryPhrase() == Harness.abandon)420        #expect(h.backend.requests.isEmpty && target.backend.requests.isEmpty && third.backend.requests.isEmpty)421    }422423    /// Opt-in, read-only: `QYVORA_LIVE=1 swift test --filter liveReadOnlySync`. Uses the default public endpoints.424    @Test(.enabled(if: ProcessInfo.processInfo.environment["QYVORA_LIVE"] == "1"))425    func liveReadOnlySync() async throws {426        let directory = FileManager.default.temporaryDirectory.appendingPathComponent("qy-live-\(UUID().uuidString)")427        defer { try? FileManager.default.removeItem(at: directory) }428        let store = try FileStore(root: directory)429        let vault = Vault(fileStore: store, keychain: InMemoryKeychainStore(), configuration: .init(kdf: .insecureForTesting))430        let service = try WalletService(vault: vault, fileStore: store, transport: LiveTransport(), historyPagesPerAddress: 1)431        let master = try ExtendedKey.master(seed: try BIP39.seed(mnemonic: Harness.abandon))432        let tpub = try master.derive(StandardPaths.bip84Account(.signet)).neutered.serialized(.tpub)433        try await service.importWatchOnly(bitcoinExtendedPublicKey: tpub, ethereumAddress: "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266",434                                          masterFingerprint: Hex.encode(master.fingerprint))435        print("LIVE account \(tpub)")436        func bitcoin(_ label: String) async throws {437            let b = try await service.syncBitcoin()438            print("LIVE \(label) tip=\(b.tipHeight) confirmed=\(b.balance.confirmed) sat pending=\(b.balance.pending) sat utxos=\(b.utxos.count) "439                + "transactions=\(b.transactions.count) usedAddresses=\(b.addresses.filter(\.isUsed).count) reused=\(b.reusedAddresses.count) "440                + "truncated=\(b.historyTruncated) nextReceive=\(b.receiveAddress.address) (index \(b.receiveAddress.index))")441            let exposure = await service.shieldReport().report.keyExposure.bitcoin442            print("LIVE \(label) exposure hashedUnrevealed=\(exposure?.totals.hashedUnrevealed ?? 0) revealedBySpend=\(exposure?.totals.revealedBySpend ?? 0) exposedUTXOs=\(exposure?.exposedUTXOCount ?? 0)")443            let fees = try await service.bitcoinFeeOptions()444            print("LIVE \(label) fees source=\(fees.source.rawValue) slow=\(fees.slow.rate) normal=\(fees.normal.rate) fast=\(fees.fast.rate)")445            #expect(b.network == .signet && b.tipHeight > 200_000)446            #expect(!b.receiveAddress.isUsed)447        }448        do {449            try await bitcoin("signet")450        } catch {451            print("LIVE signet FAILED on the default endpoint: \(error)")452            // second attempt on another public Esplora instance, so that the run still exercises a real signet backend453            do {454                try await service.setEndpoints(EndpointConfiguration.default.with { $0.esplora["signet"] = ["https://blockstream.info/signet/api"] })455                try await bitcoin("signet (blockstream.info)")456                try await service.resetEndpoints()457            } catch {458                print("LIVE signet (blockstream.info) FAILED: \(error)")459                Issue.record("signet: \(error)")460            }461        }462        do {463            let e = try await service.syncEthereum()464            print("LIVE sepolia block=\(e.blockNumber) balance=\(BaseUnits.format(e.balance, decimals: 18)) ETH nonce=\(e.latestNonce)/\(e.pendingNonce) "465                + "tokens=\(e.tokens.count) detected=\(e.detectedTokens.count) history=\(e.history.value.map { String($0.count) } ?? "unavailable") "466                + "approvals=\(e.approvals.value.map { String($0.count) } ?? "unavailable") notes=\(e.notes)")467            for t in e.detectedTokens.prefix(5) { print("LIVE sepolia detected \(t.token.symbol) decimals=\(t.token.decimals) \(t.token.address)") }468            #expect(e.network == .sepolia && e.blockNumber > 5_000_000)469        } catch {470            print("LIVE sepolia FAILED: \(error)")471            Issue.record("sepolia: \(error)")472        }473        do {474            let m = try await service.refreshMarket()475            print("LIVE prices " + m.quotes.values.sorted { $0.id < $1.id }.map { "\($0.id)=\($0.price) usd" }.joined(separator: " "))476        } catch {477            print("LIVE prices FAILED: \(error)")478        }479        let valuation = await service.portfolioValuation()480        print("LIVE valuation isTestNetwork=\(valuation.isTestNetwork) realValue=\(String(describing: valuation.realValue)) referenceValue=\(String(describing: valuation.referenceValue))")481        print("LIVE requests=\(await service.networkRequestCount())")482    }483484    /// Opt-in timing of the first synchronization of a freshly created wallet on the default public endpoints485    /// (Signet + Sepolia), then of a second one: `QYVORA_LIVE_FRESH=1 swift test --filter liveFreshWalletFirstSync`.486    @Test(.enabled(if: ProcessInfo.processInfo.environment["QYVORA_LIVE_FRESH"] == "1"))487    func liveFreshWalletFirstSync() async throws {488        let directory = FileManager.default.temporaryDirectory.appendingPathComponent("qy-fresh-\(UUID().uuidString)")489        defer { try? FileManager.default.removeItem(at: directory) }490        let store = try FileStore(root: directory)491        let vault = Vault(fileStore: store, keychain: InMemoryKeychainStore(), configuration: .init(kdf: .insecureForTesting))492        let service = try WalletService(vault: vault, fileStore: store, transport: LiveTransport())493        _ = try await service.createWallet(password: Harness.password)494        func timed(_ label: String, _ work: () async throws -> Void) async {495            let start = Date(), before = await service.networkRequestCount()496            do {497                try await work()498                print("FRESH \(label): \(String(format: "%.1f", Date().timeIntervalSince(start))) s, \(await service.networkRequestCount() - before) requests")499            } catch {500                print("FRESH \(label) FAILED after \(String(format: "%.1f", Date().timeIntervalSince(start))) s, \(await service.networkRequestCount() - before) requests: \(error)")501                Issue.record("\(label): \(error)")502            }503        }504        await timed("first Bitcoin sync (Signet)") { _ = try await service.syncBitcoin() }505        await timed("first Ethereum sync (Sepolia)") { _ = try await service.syncEthereum() }506        await timed("second Bitcoin sync (Signet)") { _ = try await service.syncBitcoin() }507        await timed("second Ethereum sync (Sepolia)") { _ = try await service.syncEthereum() }508    }509}510511/// `MainnetPolicy` is process-wide: these tests run one after the other and restore (false, false).512@Suite(.serialized, .changesMainnetPolicy) struct MainnetPolicyTests {513    static let mainnetAddress = "bc1qcr8te4kr609gcawutmrza0j4xv80jy8z306fyu"514    static let usdcMainnet = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"515516    static func reset() { MainnetPolicy.configure(internalBuildAllowsMainnet: false, userOptedIn: false) }517518    static func external(_ n: UInt8 = 0x77) -> String {519        try! BitcoinAddress(scriptPubKey: try! BitcoinScript.p2wpkh(publicKeyHash: Bytes(repeating: n, count: 20)), network: .mainnet).string520    }521522    /// An internal build with mainnet switched on and both networks on mainnet.523    static func mainnetWallet() async throws -> Harness {524        let backend = FakeBackend()525        backend.network = .mainnet526        backend.genesis = BitcoinNetwork.mainnet.genesisHash527        backend.chainID = 1528        let h = try await Harness.make(backend: backend, internalBuildAllowsMainnet: true)529        try await h.service.importWallet(words: Harness.abandon, password: Harness.password)530        #expect(try await h.service.setMainnetOptIn(true))531        try await h.service.setActiveNetworks(bitcoin: .mainnet, ethereum: .mainnet)532        return h533    }534535    @Test func refusedByDefaultAndEachConditionAloneEnablesNothing() async throws {536        Self.reset()537        defer { Self.reset() }538        #expect(!MainnetPolicy.mainnetEnabled && !MainnetPolicy.mainnetAvailable)539540        // default build541        let h = try await Harness.abandonWallet()542        defer { h.cleanup() }543        guard case .mainnetDisabled(let text)? = await walletError({ try await h.service.setBitcoinNetwork(.mainnet) }) else {544            Issue.record("expected mainnetDisabled")545            return546        }547        #expect(text.contains("watch-only") && text.contains("audited"))548        guard case .mainnetDisabled? = await walletError({ try await h.service.setEthereumNetwork(.mainnet) }) else {549            Issue.record("expected mainnetDisabled")550            return551        }552        guard case .mainnetDisabled? = await walletError({ try await h.service.setActiveNetworks(bitcoin: .mainnet, ethereum: .sepolia) }) else {553            Issue.record("expected mainnetDisabled")554            return555        }556        var dashboard = await h.service.snapshot()557        #expect(!dashboard.mainnetEnabled && !dashboard.mainnetAvailable && !dashboard.isMainnet && !dashboard.unauditedMainnet)558        #expect(dashboard.profile.bitcoinNetwork == .signet)559        try await h.service.setActiveNetworks(bitcoin: .testnet, ethereum: .sepolia)560        #expect(await h.service.currentProfile().bitcoinNetwork == .testnet)561562        // watch-only viewing of mainnet is refused too563        let master = try ExtendedKey.master(seed: try BIP39.seed(mnemonic: Harness.abandon))564        let mainKey = try master.derive(StandardPaths.bip84Account(.mainnet)).neutered565        for version in [ExtendedKey.Version.xpub, .zpub] {566            let w = try await Harness.make()567            defer { w.cleanup() }568            guard case .mainnetDisabled? = await walletError({569                try await w.service.importWatchOnly(bitcoinExtendedPublicKey: try mainKey.serialized(version), ethereumAddress: nil)570            }) else {571                Issue.record("expected mainnetDisabled")572                return573            }574            #expect(await w.service.currentProfile().kind == nil)575        }576577        // condition 1 alone: the user opts in on a build that does not allow mainnet578        #expect(try await h.service.setMainnetOptIn(true) == false)579        #expect(await h.service.currentProfile().mainnetOptIn)580        #expect(!MainnetPolicy.mainnetEnabled && !MainnetPolicy.mainnetAvailable)581        guard case .mainnetDisabled? = await walletError({ try await h.service.setActiveNetworks(bitcoin: .mainnet, ethereum: .mainnet) }) else {582            Issue.record("the opt-in alone must not enable mainnet")583            return584        }585        // a profile edited on disk cannot switch mainnet on either586        let path = h.directory.appendingPathComponent("wallet-profile.json")587        var edited = String(decoding: try Data(contentsOf: path), as: UTF8.self)588        edited = edited.replacingOccurrences(of: "\"bitcoinNetwork\" : \"testnet\"", with: "\"bitcoinNetwork\" : \"mainnet\"")589            .replacingOccurrences(of: "\"ethereumNetwork\" : \"sepolia\"", with: "\"ethereumNetwork\" : \"mainnet\"")590        #expect(edited.contains("\"bitcoinNetwork\" : \"mainnet\"") && edited.contains("\"mainnetOptIn\" : true"))591        try Data(edited.utf8).write(to: path)592        let reopened = try await Harness.make(backend: h.backend, directory: h.directory, configure: false)593        #expect(await reopened.service.currentProfile().bitcoinNetwork == .signet)594        #expect(await reopened.service.currentProfile().ethereumNetwork == .sepolia)595        #expect(h.backend.requests.isEmpty)596597        // condition 2 alone: an internal build whose user has not opted in598        Self.reset()599        let internalBuild = try await Harness.make(internalBuildAllowsMainnet: true)600        defer { internalBuild.cleanup() }601        try await internalBuild.service.importWallet(words: Harness.abandon, password: Harness.password)602        #expect(MainnetPolicy.mainnetAvailable && !MainnetPolicy.mainnetEnabled)603        guard case .mainnetDisabled? = await walletError({ try await internalBuild.service.setActiveNetworks(bitcoin: .mainnet, ethereum: .mainnet) }) else {604            Issue.record("the build flag alone must not enable mainnet")605            return606        }607        dashboard = await internalBuild.service.snapshot()608        #expect(dashboard.mainnetAvailable && !dashboard.mainnetEnabled && !dashboard.unauditedMainnet)609610        // both conditions611        #expect(try await internalBuild.service.setMainnetOptIn(true))612        try await internalBuild.service.setActiveNetworks(bitcoin: .mainnet, ethereum: .mainnet)613        dashboard = await internalBuild.service.snapshot()614        #expect(dashboard.mainnetEnabled && dashboard.isMainnet && dashboard.unauditedMainnet)615        #expect(dashboard.unauditedLimits == MainnetPolicy.limits)616        #expect(dashboard.unauditedLimits.bitcoinSatoshisPerTransaction == 200_000)617        #expect(dashboard.bitcoinReceiveAddress == Self.mainnetAddress)618        // the choice is stored: a new session of the internal build is on mainnet again, a public build is not619        Self.reset()620        let again = try await Harness.make(directory: internalBuild.directory, configure: false, internalBuildAllowsMainnet: true)621        #expect(MainnetPolicy.mainnetEnabled)622        #expect(await again.service.currentProfile().bitcoinNetwork == .mainnet)623        Self.reset()624        let publicBuild = try await Harness.make(directory: internalBuild.directory, configure: false)625        #expect(!MainnetPolicy.mainnetEnabled)626        #expect(await publicBuild.service.currentProfile().bitcoinNetwork == .signet)627628        // switching the opt-in off returns to the test networks629        MainnetPolicy.configure(internalBuildAllowsMainnet: true, userOptedIn: true)630        #expect(await internalBuild.service.currentProfile().ethereumNetwork == .mainnet)631        #expect(try await internalBuild.service.setMainnetOptIn(false) == false)632        let after = await internalBuild.service.snapshot()633        #expect(after.profile.bitcoinNetwork == .signet && after.profile.ethereumNetwork == .sepolia && !after.profile.mainnetOptIn)634        #expect(!after.isMainnet && !after.unauditedMainnet && !after.mainnetEnabled && after.mainnetAvailable)635        #expect(after.bitcoinReceiveAddress == Harness.abandonFirstTestAddress)636        guard case .mainnetDisabled? = await walletError({ try await internalBuild.service.setBitcoinNetwork(.mainnet) }) else {637            Issue.record("expected mainnetDisabled after opting out")638            return639        }640    }641642    @Test func bitcoinLimitIsEnforcedAtPrepareAndAtSign() async throws {643        Self.reset()644        defer { Self.reset() }645        let h = try await Self.mainnetWallet()646        defer { h.cleanup() }647        #expect(try await h.receive(0) == Self.mainnetAddress)648        h.backend.fund(Self.mainnetAddress, 500_000, height: 100)649        let snapshot = try await h.service.syncBitcoin()650        #expect(snapshot.network == .mainnet && snapshot.balance.confirmed == 500_000)651        let rate = FeeRate(satPerVByte: 2)652653        // at the limit: allowed, with the unaudited warning654        let plan = try await h.service.prepareBitcoinSend(to: Self.external(), amount: 200_000, feeRate: rate)655        #expect(plan.network == .mainnet && plan.warnings.first == .unauditedMainnet)656        #expect(BitcoinSendWarning.unauditedMainnet.message.contains("not been independently audited"))657        // above it: refused at prepare, send-max included, with the limit in the error658        #expect(await walletError { try await h.service.prepareBitcoinSend(to: Self.external(), amount: 200_001, feeRate: rate) }659            == .exceedsUnauditedLimit(limit: "0.002 BTC per transaction"))660        guard case .exceedsUnauditedLimit(let limit)? = await walletError({ try await h.service.prepareBitcoinSend(to: Self.external(), amount: 0, feeRate: rate, sendMax: true) }) else {661            Issue.record("send-max above the limit must be refused")662            return663        }664        #expect(limit.contains("0.002 BTC") && limit.contains("everything"))665666        // at sign: a plan above the limit (built here with the check bypassed) is refused before any key is read667        let account = try await h.service.bitcoinAccount()668        let over = try await h.service.buildBitcoinPlan(account: account, snapshot: snapshot, purpose: .payment,669                                                        destination: try BitcoinAddress(Self.external(), network: .mainnet), amount: 300_000,670                                                        feeRate: rate, sendMax: false, coinControl: BitcoinCoinControl(), enforceLimits: false)671        #expect(await walletError { try await h.service.signAndBroadcastBitcoin(over) } == .exceedsUnauditedLimit(limit: "0.002 BTC per transaction"))672        #expect(await walletError { try await h.service.exportPSBT(over) } == .exceedsUnauditedLimit(limit: "0.002 BTC per transaction"))673        // and through the PSBT path, on the signing side and on the broadcasting side674        let psbt = try account.psbt(for: over.plan).base64675        let review = try await h.service.reviewPSBT([psbt])676        #expect(review.sentToOthers == 300_000 && review.warnings.contains { $0.contains("not been independently audited") })677        #expect(await walletError { try await h.service.signPSBT([psbt]) } == .exceedsUnauditedLimit(limit: "0.002 BTC per transaction"))678        #expect(await walletError { try await h.service.finalizeAndBroadcastPSBT([psbt]) } == .exceedsUnauditedLimit(limit: "0.002 BTC per transaction"))679        #expect(h.backend.broadcastBitcoin.isEmpty)680681        // the allowed plan goes through and is a real mainnet transaction682        let result = try await h.service.signAndBroadcastBitcoin(plan)683        let tx = try BitcoinTransaction(hex: try #require(h.backend.broadcastBitcoin.first))684        #expect(tx.txid == result.txid && tx.outputs.contains { $0.value == 200_000 })685        try BitcoinVerifier.verify(transaction: tx, spentOutputs: [snapshot.utxos[0].utxo.output])686687        // on mainnet the valuation is real value688        h.backend.markets = ServiceTests.market([("bitcoin", "60000"), ("ethereum", "3000")])689        _ = try await h.service.refreshMarket()690        let valuation = await h.service.portfolioValuation()691        #expect(!valuation.isTestNetwork && valuation.referenceValue == nil)692        #expect(valuation.realValue == 0.005 * 60_000)693        #expect(valuation.lines.first?.value == 300 && valuation.lines.first?.referenceValue == nil)694695        // with the policy off again the same service refuses to touch mainnet at all696        Self.reset()697        guard case .mainnetDisabled? = await walletError({ try await h.service.syncBitcoin() }) else {698            Issue.record("expected mainnetDisabled")699            return700        }701        guard case .mainnetDisabled? = await walletError({ try await h.service.prepareBitcoinSend(to: Self.external(), amount: 10_000, feeRate: rate) }) else {702            Issue.record("expected mainnetDisabled")703            return704        }705    }706707    @Test func ethereumLimitsAreEnforcedAtPrepareAndAtSign() async throws {708        Self.reset()709        defer { Self.reset() }710        let h = try await Self.mainnetWallet()711        defer { h.cleanup() }712        let owner = EthereumWalletTests.owner713        h.backend.balances[owner] = EthereumWalletTests.oneEther714        let limit = UInt256(50_000_000_000_000_000)715        let recipient = EthereumWalletTests.recipient716717        // ether718        let review = try await h.service.prepareEthereumSend(asset: .ether, to: recipient, amount: limit)719        #expect(review.network == .mainnet && review.transaction.chainID == 1 && review.warnings.contains(.unauditedMainnet))720        #expect(await walletError { try await h.service.prepareEthereumSend(asset: .ether, to: recipient, amount: limit + UInt256(1)) }721            == .exceedsUnauditedLimit(limit: "0.05 ETH per transaction"))722        #expect(await walletError { try await h.service.prepareEthereumSend(asset: .ether, to: recipient, amount: .zero, sendMax: true) }723            == .exceedsUnauditedLimit(limit: "0.05 ETH per transaction"))724        // at sign: the same review with a larger value725        var bigger = review.transaction726        bigger.value = limit + limit727        let forged = EthereumSendReview(id: UUID(), network: review.network, createdAt: review.createdAt, from: review.from, asset: .ether,728                                        recipient: review.recipient, amount: bigger.value, transaction: bigger, call: .etherTransfer, feeTier: .normal,729                                        baseFee: review.baseFee, maximumFee: review.maximumFee, maximumTotalCost: review.maximumTotalCost, isSendMax: false,730                                        warnings: [])731        #expect(await walletError { try await h.service.signAndBroadcastEthereum(forged) } == .exceedsUnauditedLimit(limit: "0.05 ETH per transaction"))732        #expect(await walletError { try await h.service.signColdEthereumPayload(["0x" + Hex.encode(bigger.unsignedPayload)]) }733            == .exceedsUnauditedLimit(limit: "0.05 ETH per transaction"))734        #expect(h.backend.broadcastEthereum.isEmpty)735        _ = try await h.service.signAndBroadcastEthereum(review)736        #expect(h.backend.broadcastEthereum.count == 1)737738        // ERC-20: built-in mainnet USDC, valued at a fresh USD price739        let usdc = try #require(BuiltInTokens.mainnet.first { $0.symbol == "USDC" })740        #expect(usdc.address.checksummed == Self.usdcMainnet)741        var contract = FakeBackend.TokenContract(symbol: "USDC", name: "USD Coin", decimals: UInt256(6))742        contract.balances[owner] = UInt256(1_000_000_000)743        h.backend.tokens[Self.usdcMainnet.lowercased()] = contract744        // no price yet and the price source is down: the value cannot be checked, so nothing is prepared745        h.backend.priceStatus = 500746        guard case .unauditedLimitUnverifiable? = await walletError({ try await h.service.prepareEthereumSend(asset: .token(usdc), to: recipient, amount: UInt256(1_000_000)) }) else {747            Issue.record("a token without a fresh price must be refused")748            return749        }750        h.backend.priceStatus = 200751        h.backend.markets = ServiceTests.market([("usd-coin", "1.0")])752        let tokenReview = try await h.service.prepareEthereumSend(asset: .token(usdc), to: recipient, amount: UInt256(150_000_000))753        #expect(tokenReview.warnings.contains(.unauditedMainnet))754        #expect(await walletError { try await h.service.prepareEthereumSend(asset: .token(usdc), to: recipient, amount: UInt256(150_000_001)) }755            == .exceedsUnauditedLimit(limit: "150 USD per token transfer"))756        // the limit follows the price757        h.clock.advance(700)758        h.backend.markets = ServiceTests.market([("usd-coin", "2.0")])759        #expect(await walletError { try await h.service.prepareEthereumSend(asset: .token(usdc), to: recipient, amount: UInt256(100_000_000)) }760            == .exceedsUnauditedLimit(limit: "150 USD per token transfer"))761        // at sign: the review prepared at 1 USD is now worth 300 USD762        #expect(await walletError { try await h.service.signAndBroadcastEthereum(tokenReview) } == .exceedsUnauditedLimit(limit: "150 USD per token transfer"))763        // a stale price is not used: when the source is down, signing is refused764        h.clock.advance(700)765        // signing needs a credential verified recently (QYV-APP-002): time has passed since the wallet was opened766        try await h.service.unlock(password: Harness.password)767        h.backend.priceStatus = 503768        guard case .unauditedLimitUnverifiable? = await walletError({ try await h.service.signAndBroadcastEthereum(tokenReview) }) else {769            Issue.record("a stale price must not be used for the limit")770            return771        }772        h.backend.priceStatus = 200773        h.backend.markets = ServiceTests.market([("usd-coin", "1.0")])774        _ = try await h.service.signAndBroadcastEthereum(tokenReview)775        #expect(h.backend.broadcastEthereum.count == 2)776777        // a token without price identifier cannot be sent on mainnet778        let other = "0x" + String(repeating: "9a", count: 20)779        var unknown = FakeBackend.TokenContract(symbol: "NOPRICE", name: "No price", decimals: UInt256(18))780        unknown.balances[owner] = UInt256(10)781        h.backend.tokens[other] = unknown782        let custom = try await h.service.addCustomToken(address: other)783        guard case .unauditedLimitUnverifiable(let why)? = await walletError({ try await h.service.prepareEthereumSend(asset: .token(custom), to: recipient, amount: UInt256(1)) }) else {784            Issue.record("a token without price must be refused")785            return786        }787        #expect(why.contains("no known price"))788789        // approvals: only revocations; no blind signing790        let spender = try #require(EthereumAddress(EthereumWalletTests.spender))791        let revoke = try await h.service.revokeApproval(token: usdc, spender: spender)792        #expect(revoke.warnings.contains(.revokesApproval) && revoke.warnings.contains(.unauditedMainnet))793        func payload(_ data: Bytes) -> String {794            var tx = revoke.transaction795            tx.data = data796            return "0x" + Hex.encode(tx.unsignedPayload)797        }798        let approve = payload(ERC20.approve(spender: spender, amount: UInt256(5)))799        #expect(try await h.service.reviewColdEthereumPayload([approve]).warnings.contains(.unauditedMainnet))800        guard case .unauditedLimitUnverifiable? = await walletError({ try await h.service.signColdEthereumPayload([approve]) }) else {801            Issue.record("a non-zero approval must not be signed on unaudited mainnet")802            return803        }804        guard case .unauditedLimitUnverifiable? = await walletError({ try await h.service.signColdEthereumPayload([payload([0xde, 0xad, 0xbe, 0xef])], allowBlindSigning: true) }) else {805            Issue.record("undecodable call data must not be signed on unaudited mainnet")806            return807        }808        #expect(try await h.service.signColdEthereumPayload([payload(ERC20.approve(spender: spender, amount: .zero))]).hash.count == 66)809        #expect(h.backend.broadcastEthereum.count == 2)810811        // the same amounts are not limited on a test network812        try await h.service.setActiveNetworks(bitcoin: .signet, ethereum: .sepolia)813        h.backend.chainID = 11_155_111814        let free = try await h.service.prepareEthereumSend(asset: .ether, to: recipient, amount: limit + limit)815        #expect(!free.warnings.contains(.unauditedMainnet))816    }817}818819/// Live transport that reports slow or failed requests (diagnostics of the opt-in live test).820struct LiveTransport: HTTPTransport {821    let inner = URLSessionTransport(timeout: 30)822823    func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) {824        let start = Date()825        do {826            let result = try await inner.send(request)827            let elapsed = Date().timeIntervalSince(start)828            if elapsed > 5 || result.1.statusCode != 200 {829                print("LIVE slow or refused: \(result.1.statusCode) \(String(format: "%.1f", elapsed))s \(result.0.count)B \(request.url?.absoluteString ?? "")")830            }831            return result832        } catch {833            print("LIVE request failed after \(String(format: "%.1f", Date().timeIntervalSince(start)))s: \(request.url?.absoluteString ?? "") — \((error as NSError).code)")834            throw error835        }836    }837}838
Files main
Menu

Theme