SPB Git

Repository Public

IntegrationGapTests.swift 51.6 KB 752 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Tests/QyvoraWalletTests/IntegrationGapTests.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 QyvoraSymmetric45import QyvoraMigration46import QyvoraCore47import QyvoraBitcoin48import QyvoraEthereum49import QyvoraNetworking50import QyvoraStorage51import QyvoraVault52import QyvoraRecovery53import QyvoraQuantumShield54import QyvoraSolana55import QyvoraTron56@testable import QyvoraWallet5758/// Regression tests of the integration gaps closed after the multi-chain upgrade: what the screens needed from the59/// service and could not get (hidden tokens, limits before the opt-in, registry keys, a sync result they can build).60@Suite(.readsMainnetPolicy) struct IntegrationGapTests {61    @Test func aSyncResultCanBeBuiltByWhoeverListensToEvents() {62        let ok = ChainSyncResult(chain: .solanaDevnet), failed = ChainSyncResult(chain: .tronNile, error: "no answer")63        #expect(ok.succeeded && ok.error == nil && ok.id == .solanaDevnet)64        #expect(!failed.succeeded && failed.error == "no answer")65    }6667    @Test func theRegistryGivesTheModuleNetworkAndTheEndpointKeyOfEveryChain() {68        for d in ChainRegistry.all {69            switch d.family {70            case .utxo:71                let network = try! #require(d.utxoNetwork)72                #expect(d.endpointKey == network.rawValue && ChainRegistry.descriptor(of: network) == d && network.displayName == d.displayName)73                #expect(d.evmNetwork == nil && d.solanaNetwork == nil && d.tronNetwork == nil)74            case .evm:75                let network = try! #require(d.evmNetwork)76                #expect(d.endpointKey == network.rawValue && ChainRegistry.descriptor(of: network) == d && network.chainID == d.evmChainID)77                #expect(d.utxoNetwork == nil)78            case .solana:79                let network = try! #require(d.solanaNetwork)80                #expect(d.endpointKey == network.rawValue && ChainRegistry.descriptor(of: network) == d)81            case .tron:82                let network = try! #require(d.tronNetwork)83                #expect(d.endpointKey == network.rawValue && ChainRegistry.descriptor(of: network) == d)84            }85        }86        // the keys are those of the endpoint tables87        #expect(ChainRegistry.descriptor(.bitcoinSignet)?.endpointKey == "signet" && ChainRegistry.descriptor(.solanaDevnet)?.endpointKey == "devnet")88        #expect(ChainRegistry.descriptor(.tronNile)?.endpointKey == "nile")89        let endpoints = MultiBackend.endpoints()90        for d in ChainRegistry.all where d.family == .solana { #expect(endpoints.solana.rpc[d.endpointKey] != nil, "\(d.id)") }91        for d in ChainRegistry.all where d.family == .tron { #expect(endpoints.tron.fullNodes[d.endpointKey] != nil, "\(d.id)") }92        for d in ChainRegistry.all where d.family == .evm { #expect(endpoints.core.ethereumRPC[d.endpointKey] != nil, "\(d.id)") }93    }9495    @Test func networkNamesOfTheRegistryAreConsistent() {96        let all = ChainRegistry.all97        #expect(Set(all.map(\.displayName)).count == all.count)98        for d in all {99            #expect(!d.shortName.isEmpty && !d.displayName.isEmpty)100            let main = try! #require(ChainRegistry.descriptor(d.mainCounterpart))101            // a main network is called by its chain in short; a test network of a UTXO coin by the network alone102            if !d.isTest { #expect(d.id == main.id) }103            if d.family == .utxo, d.isTest {104                #expect(!d.shortName.contains(main.displayName), "\(d.shortName)")105                #expect(d.displayName == main.displayName + " " + d.shortName)106            }107            // no word twice in a name108            let words = d.displayName.lowercased().split(separator: " ").map(String.init)109            #expect(Set(words).count == words.count, "\(d.displayName)")110        }111        #expect(ChainRegistry.descriptor(.litecoinTestnet)?.shortName == "Testnet" && ChainRegistry.descriptor(.bitcoinCashTestnet)?.shortName == "Testnet4")112        #expect(ChainRegistry.descriptor(.bitcoinSignet)?.shortName == "Signet" && ChainRegistry.descriptor(.dogecoin)?.shortName == "Dogecoin")113        #expect(ChainRegistry.descriptor(.arbitrumSepolia)?.displayName == "Arbitrum Sepolia")114    }115116    @Test func hiddenTokensAreListedAndCanBeShownAgain() async throws {117        let h = try await MultiHarness.wallet(chains: [.ethereum, .solana, .tron])118        defer { h.cleanup() }119        let owner = try #require(SolanaPublicKey(base58: MultiHarness.solanaAddress))120        let listedMint = solanaStranger(40).base58, foundMint = solanaStranger(41).base58121        h.backend.solana.lamports[MultiHarness.solanaAddress] = 1_000_000_000122        h.backend.solana.mints[listedMint] = .init(decimals: 6)123        h.backend.solana.mints[foundMint] = .init(decimals: 2)124        h.backend.solana.tokenAccounts = [125            .init(address: try SolanaAddress.associatedTokenAccount(owner: owner, mint: SolanaPublicKey(base58: listedMint)!, tokenProgram: .token).base58,126                  mint: listedMint, owner: MultiHarness.solanaAddress, amount: 12_500_000),127            .init(address: solanaStranger(42).base58, mint: foundMint, owner: MultiHarness.solanaAddress, amount: 700),128        ]129        let contract = tronStranger(0x51)130        let me = TronAddress(MultiHarness.tronAddress)!131        h.backend.tron.balances[me.hex] = 5_000_000132        h.backend.tron.tokens[contract.hex] = .init(decimals: 6, symbol: "TUSD", name: "Test Dollar", balances: [Hex.encode(me.hash): UInt256(3_210_000)])133        let added = try await h.service.addCustomToken(chain: .solanaDevnet, address: listedMint, label: "TEST")134        let tronToken = try await h.service.addCustomToken(chain: .tronNile, address: contract.base58)135        #expect(await h.service.synchronize().allSatisfy(\.succeeded))136        let detected = try #require(await h.service.chainSnapshot(.solanaDevnet)?.data.value?.detectedTokens.first)137138        // nothing hidden: nothing listed, on any chain139        for chain in ChainRegistry.all { #expect(await h.service.hiddenTokens(chain: chain.id).isEmpty) }140141        try await h.service.setTokenHidden(true, token: added)142        try await h.service.setTokenHidden(true, token: detected.token)143        try await h.service.setTokenHidden(true, token: tronToken)144        let requests = h.backend.requests.count145        // the known token comes first with what the wallet knows of it; the one hidden from the detected list is an146        // address and nothing else147        let solana = await h.service.hiddenTokens(chain: .solanaDevnet)148        #expect(solana == [HiddenToken(chain: .solanaDevnet, address: listedMint, token: added), HiddenToken(chain: .solanaDevnet, address: foundMint, token: nil)])149        #expect(await h.service.hiddenTokens(chain: .tronNile) == [HiddenToken(chain: .tronNile, address: contract.base58, token: tronToken)])150        // a list belongs to its network151        #expect(await h.service.hiddenTokens(chain: .solanaTestnet).isEmpty)152        #expect(await h.service.hiddenTokens(chain: .tron).isEmpty)153        #expect(await h.service.hiddenTokens(chain: .bitcoinSignet).isEmpty)154        #expect(await h.service.hiddenTokens(chain: ChainID("unknown")).isEmpty)155        var now = try #require(await h.service.chainSnapshot(.solanaDevnet)?.data.value)156        #expect(now.tokens.isEmpty && now.detectedTokens.isEmpty)157158        // shown again: the listed token returns to the list at once, without network159        try await h.service.showHiddenToken(solana[0])160        now = try #require(await h.service.chainSnapshot(.solanaDevnet)?.data.value)161        #expect(now.tokens.map(\.token) == [added])162        #expect(await h.service.hiddenTokens(chain: .solanaDevnet).map(\.address) == [foundMint])163        try await h.service.showHiddenToken(solana[1])164        try await h.service.showHiddenToken(HiddenToken(chain: .tronNile, address: contract.base58, token: nil))165        #expect(await h.service.hiddenTokens(chain: .solanaDevnet).isEmpty)166        #expect(await h.service.hiddenTokens(chain: .tronNile).isEmpty)167        #expect(await h.service.currentProfile().hiddenTokens.isEmpty)168        #expect(await h.service.chainSnapshot(.tronNile)?.data.value?.tokens.map(\.token) == [tronToken])169        #expect(h.backend.requests.count == requests)170        // showing a token that is not hidden changes nothing171        try await h.service.showHiddenToken(solana[0])172        // the token that had only been detected is found again by the next synchronization173        #expect(await h.service.synchronize(chains: [.solanaDevnet]).allSatisfy(\.succeeded))174        #expect(await h.service.chainSnapshot(.solanaDevnet)?.data.value?.detectedTokens.map(\.token.address) == [foundMint])175176        // an ERC-20 token is filed under its network and listed with the registry's identifier177        if let builtIn = BuiltInTokens.tokens(for: .sepolia).first {178            try await h.service.setTokenHidden(true, token: builtIn)179            let evm = await h.service.hiddenTokens(chain: .ethereumSepolia)180            #expect(evm.count == 1 && evm.first?.token?.symbol == builtIn.symbol && evm.first?.address == builtIn.address.checksummed)181            #expect(await h.service.hiddenTokens(chain: .ethereum).isEmpty)182            #expect(await h.service.hiddenTokens(chain: .baseSepolia).isEmpty)183            try await h.service.showHiddenToken(evm[0])184            #expect(await h.service.hiddenTokens(chain: .ethereumSepolia).isEmpty)185        }186        let stranger = "0x00000000000000000000000000000000000000aa"187        let unknown = TokenInfo(network: .sepolia, address: EthereumAddress(stranger)!, symbol: "X", name: "X", decimals: 18, priceID: nil, custom: true)188        try await h.service.setTokenHidden(true, token: unknown)189        let evm = await h.service.hiddenTokens(chain: .ethereumSepolia)190        #expect(evm.count == 1 && evm.first?.token == nil && evm.first?.address == unknown.address.checksummed)191        try await h.service.showHiddenToken(evm[0])192        #expect(await h.service.currentProfile().hiddenTokens.isEmpty)193    }194195    @Test func aWatchOnlyWalletEnablesTheChainsItHasAndNamesTheOthers() async throws {196        let h = try await MultiHarness.make()197        defer { h.cleanup() }198        try await h.service.importWatchOnly(bitcoinExtendedPublicKey: nil, ethereumAddress: MultiHarness.ethereumAddress, solanaAddress: MultiHarness.solanaAddress)199        #expect(await h.service.currentProfile().enabledChains == [.ethereum, .solana])200        // every chain is asked for: those with an account are enabled, the others are reported, in registry order201        let skipped = try await h.service.setEnabledChains(ChainRegistry.mainChains.map(\.id))202        #expect(skipped == [.bitcoin, .litecoin, .dogecoin, .bitcoinCash, .tron])203        #expect(await h.service.currentProfile().enabledChains == [.ethereum, .base, .arbitrum, .optimism, .polygon, .bsc, .avalanche, .solana])204        // nothing wanted has an account: the call fails and names them, the list is unchanged205        #expect(await walletError { try await h.service.setEnabledChains([.tron, .litecoin]) }206            == .featureUnavailable("This watch-only wallet has no account for Litecoin, TRON."))207        #expect(await h.service.currentProfile().enabledChains.count == 8)208        #expect(try await h.service.setEnabledChains([.solana, .tron]) == [.tron])209        #expect(await h.service.currentProfile().enabledChains == [.solana])210        // one chain at a time still refuses, with the reason211        #expect(await walletError { try await h.service.setChainEnabled(.tron, enabled: true) }212            == .featureUnavailable("This watch-only wallet has no account for TRON."))213214        // a full wallet never skips anything215        let full = try await MultiHarness.make()216        defer { full.cleanup() }217        try await full.service.importWallet(words: Harness.abandon, password: Harness.password)218        #expect(try await full.service.setEnabledChains(ChainRegistry.mainChains.map(\.id)).isEmpty)219        #expect(await full.service.currentProfile().enabledChains == ChainRegistry.mainChains.map(\.id))220    }221}222223// `MainnetPolicy` is process-wide: what touches it runs inside the serialized suite that owns it.224extension MainnetPolicyTests {225    @Test func theLimitsOfAMainNetworkAreKnownBeforeTheOptIn() async throws {226        Self.reset()227        defer { Self.reset() }228        let h = try await MultiHarness.make(internalBuildAllowsMainnet: true)229        defer { h.cleanup() }230        try await h.service.importWallet(words: Harness.abandon, password: Harness.password)231        try await h.service.setEnabledChains(ChainRegistry.mainChains.map(\.id))232        // before the opt-in the snapshots carry no limit, and the preview states every one233        #expect(await h.service.chainSnapshots().allSatisfy { $0.limits == nil })234        var preview = [ChainID: ChainLimits]()235        for main in ChainRegistry.mainChains {236            let limits = ChainRegistry.previewLimits(for: main)237            #expect(!limits.native.isEmpty && !limits.fee.isEmpty && limits.native.hasPrefix("At most "), "\(main.id)")238            #expect((limits.tokens != nil) == main.capabilities.tokens, "\(main.id)")239            // a test network previews the limits of its main network240            for test in main.testCounterparts.compactMap({ ChainRegistry.descriptor($0) }) { #expect(ChainRegistry.previewLimits(for: test) == limits) }241            preview[main.id] = limits242        }243        #expect(preview[.bitcoin]?.native == "At most 0.002 BTC per transaction.")244        // once main networks are on, what applies is word for word what was previewed245        _ = try await h.service.setMainnetOptIn(true)246        try await h.service.setNetworkMode(.main)247        let chains = await h.service.chainSnapshots()248        #expect(chains.count == ChainRegistry.mainChains.count)249        for chain in chains { #expect(chain.limits == preview[chain.id], "\(chain.id)") }250    }251}252253/// Fee estimates before a payment exists, the validity of a Solana review, and what a cold review knows of a token.254@Suite(.readsMainnetPolicy) struct SendPreviewTests {255    @Test func anEVMFeeQuoteIsWhatThePreparedTransferThenCosts() async throws {256        let h = try await MultiHarness.wallet(chains: [.ethereum, .base])257        defer { h.cleanup() }258        let owner = MultiHarness.ethereumAddress.lowercased()259        let base = h.backend.evm(.baseSepolia)260        base.balances[owner] = UInt256(2_000_000_000_000_000_000)261        base.rpcResultOverride["eth_call"] = "\"0x\(Hex.encode(UInt256(8_000_000_000).bytes32))\""262263        let quote = try await h.service.feeQuote(chain: .baseSepolia)264        #expect(quote.chain == .baseSepolia && quote.asset == .native && quote.symbol == "ETH" && quote.decimals == 18 && quote.isEstimate && quote.tron == nil)265        #expect(quote.tiers.map(\.tier) == [.slow, .normal, .fast])266        #expect(quote.basis.contains("Estimate") && quote.basis.contains("21,000 gas") && quote.basis.contains("L1 data fee included"))267        for (a, b) in zip(quote.tiers, quote.tiers.dropFirst()) { #expect(a.maximum <= b.maximum && a.expected <= b.expected) }268        for tier in quote.tiers { #expect(tier.expected <= tier.maximum && !tier.expected.isZero) }269        // the review of a plain transfer at each tier states the same figures270        for tier in SendFeeTier.allCases {271            var options = SendOptions()272            options.feeTier = tier273            let review = try await h.service.prepareSend(chain: .baseSepolia, asset: .native, to: EthereumWalletTests.recipient,274                                                         amount: UInt256(500_000_000_000_000_000), options: options)275            let quoted = try #require(quote.tier(tier))276            #expect(quoted.maximum == review.fee.maximum && quoted.expected == review.fee.expected, "\(tier)")277        }278        // the primary network too, without an L1 component279        h.backend.base.balances[owner] = UInt256(2_000_000_000_000_000_000)280        let primary = try await h.service.feeQuote(chain: .ethereumSepolia)281        let review = try await h.service.prepareSend(chain: .ethereumSepolia, asset: .native, to: EthereumWalletTests.recipient, amount: UInt256(1_000_000))282        #expect(primary.tier(.normal)?.maximum == review.fee.maximum && primary.tier(.normal)?.expected == review.fee.expected)283        #expect(!primary.basis.contains("L1"))284285        // refusals: a chain that is not active, a UTXO chain, a token of another network286        #expect(await walletError { try await h.service.feeQuote(chain: .polygonAmoy) } == .chainNotActive("Polygon Amoy"))287        guard case .invalidInput(let why)? = await walletError({ try await h.service.feeQuote(chain: .bitcoinSignet) }) else {288            Issue.record("a UTXO chain has no fee quote")289            return290        }291        #expect(why.contains("depends on the coins"))292        let foreign = ChainToken(chain: .ethereumSepolia, address: MainnetPolicyTests.usdcMainnet, symbol: "X", name: "X", decimals: 6, standard: .erc20)293        #expect(await walletError { try await h.service.feeQuote(chain: .baseSepolia, asset: .token(foreign)) } == .ethereum(.tokenNetworkMismatch))294    }295296    @Test func aSolanaFeeQuoteFollowsTheRecentPricesAndAReviewSaysWhenItLapses() async throws {297        let h = try await MultiChainSendTests.solanaWallet()298        defer { h.cleanup() }299        let recipient = solanaStranger()300        var quote = try await h.service.feeQuote(chain: .solanaDevnet)301        // no recent data: the floor price at every tier but the fast one, on the 5 000 units of a plain transfer302        #expect(quote.tiers.map(\.expected) == [UInt256(5_025), UInt256(5_025), UInt256(5_050)] && quote.symbol == "SOL" && quote.decimals == 9)303        #expect(quote.tiers.allSatisfy { $0.expected == $0.maximum } && quote.basis.contains("Estimate") && quote.tron == nil)304        var review = try await h.service.prepareSend(chain: .solanaDevnet, asset: .native, to: recipient.base58, amount: UInt256(500_000_000))305        #expect(review.fee.expected == quote.tier(.normal)?.expected)306        // the service says when the review stops being valid: the UI does not guess307        #expect(review.expiresAt == h.clock.now.addingTimeInterval(WalletService.solanaBlockhashLifetime) && WalletService.solanaBlockhashLifetime == 60)308309        h.backend.solana.prioritizationFees = [40_000, 40_000, 40_000, 40_000]310        quote = try await h.service.feeQuote(chain: .solanaDevnet)311        #expect(quote.tiers.map(\.expected) == [UInt256(5_100), UInt256(5_200), UInt256(5_400)])312        for tier in SendFeeTier.allCases {313            var options = SendOptions()314            options.feeTier = tier315            review = try await h.service.prepareSend(chain: .solanaDevnet, asset: .native, to: recipient.base58, amount: UInt256(1_000_000 + UInt64(tier.rawValue.count)),316                                                     options: options)317            #expect(review.fee.expected == quote.tier(tier)?.expected, "\(tier)")318        }319        // a token transfer reserves more compute units: its estimate is higher, and says what it leaves out320        let mint = solanaStranger(40).base58321        h.backend.solana.mints[mint] = .init(decimals: 6)322        let token = try await h.service.addCustomToken(chain: .solanaDevnet, address: mint, label: "TEST")323        let tokenQuote = try await h.service.feeQuote(chain: .solanaDevnet, asset: .token(token))324        #expect(tokenQuote.tier(.normal)?.expected == UInt256(5_000 + 80_000 * 40_000 / 1_000_000) && tokenQuote.basis.contains("is not a fee and is not included"))325    }326327    @Test func aTronFeeQuoteIsAResourceEstimateWithoutTiers() async throws {328        let h = try await MultiChainSendTests.tronWallet()329        defer { h.cleanup() }330        let recipient = tronStranger()331        h.backend.tron.balances[recipient.hex] = 1332        let quote = try await h.service.feeQuote(chain: .tronNile)333        let estimate = try #require(quote.tron)334        #expect(quote.tiers.isEmpty && quote.symbol == "TRX" && quote.decimals == 6 && quote.isEstimate && quote.basis.contains("no fee tiers"))335        #expect(estimate.lines.count == 2 && estimate.lines[0].contains("\(estimate.transferBandwidthBytes) bytes of bandwidth") && estimate.lines[1].contains("never used on TRON"))336        let covered = estimate.freeBandwidth >= estimate.transferBandwidthBytes || estimate.stakedBandwidth >= estimate.transferBandwidthBytes337        #expect((estimate.transferBandwidthFeeSun == 0) == covered)338        // the transfer the wallet then prepares has that size and burns that much for bandwidth339        let review = try await h.service.prepareSend(chain: .tronNile, asset: .native, to: recipient.base58, amount: UInt256(MultiChainSendTests.trx))340        guard case .tron(let details) = review.body else {341            Issue.record("a TRON body is expected")342            return343        }344        #expect(details.plan.bandwidthBytes == estimate.transferBandwidthBytes && details.plan.bandwidthFeeSun == estimate.transferBandwidthFeeSun)345        #expect(details.plan.activationFeeSun == 0)346        // a new address costs at most what the estimate says347        let fresh = try await h.service.prepareSend(chain: .tronNile, asset: .native, to: tronStranger(0x44).base58, amount: UInt256(MultiChainSendTests.trx))348        #expect(fresh.fee.maximum <= UInt256(estimate.maximumActivationFeeSun) && fresh.fee.maximum > .zero)349350        // a token: the energy is not guessed, the account's resources and the price are given351        let contract = tronStranger(0x51)352        let me = try #require(TronAddress(MultiHarness.tronAddress))353        h.backend.tron.tokens[contract.hex] = .init(decimals: 6, symbol: "TUSD", name: "Test Dollar", balances: [Hex.encode(me.hash): UInt256(80_000_000)])354        let token = try await h.service.addCustomToken(chain: .tronNile, address: contract.base58)355        let tokenQuote = try await h.service.feeQuote(chain: .tronNile, asset: .token(token))356        #expect(tokenQuote.tron?.lines.count == 3 && tokenQuote.tron?.lines.last?.contains("known when the payment is prepared") == true)357        #expect(tokenQuote.tron?.energyPriceSun ?? 0 > 0 && tokenQuote.tiers.isEmpty)358    }359360    @Test func aColdReviewNamesTheTokensOfTheWalletsListAndNoOther() async throws {361        let h = try await MultiHarness.wallet(chains: [.solana, .tron])362        defer { h.cleanup() }363        let owner = try #require(SolanaPublicKey(base58: MultiHarness.solanaAddress))364        let mint = solanaStranger(40), recipient = solanaStranger()365        h.backend.solana.lamports[MultiHarness.solanaAddress] = 1_000_000_000366        h.backend.solana.lamports[recipient.base58] = 1_000_000_000367        h.backend.solana.mints[mint.base58] = .init(decimals: 6)368        h.backend.solana.tokenAccounts = [369            .init(address: try SolanaAddress.associatedTokenAccount(owner: owner, mint: mint, tokenProgram: .token).base58, mint: mint.base58,370                  owner: MultiHarness.solanaAddress, amount: 12_500_000),371        ]372        let token = try await h.service.addCustomToken(chain: .solanaDevnet, address: mint.base58, label: "TEST")373        let review = try await h.service.prepareSend(chain: .solanaDevnet, asset: .token(token), to: recipient.base58, amount: UInt256(2_500_000))374        let frames = try await h.service.exportUnsigned(review).frames375        var cold = try await h.service.reviewColdTransaction(frames)376        // symbol and decimals come from the wallet's list; the review can show "2.5 TEST"377        #expect(cold.knownTokens == [token] && cold.knownToken(address: mint.base58)?.symbol == "TEST" && cold.knownToken(address: recipient.base58) == nil)378        // once the token is no longer in the list, nothing is said of it: the amount stays in base units379        try await h.service.removeCustomToken(token)380        cold = try await h.service.reviewColdTransaction(frames)381        #expect(cold.knownTokens.isEmpty)382383        // TRON384        let me = try #require(TronAddress(MultiHarness.tronAddress))385        let tronRecipient = tronStranger()386        h.backend.tron.balances[me.hex] = 50_000_000387        h.backend.tron.balances[tronRecipient.hex] = 1388        let contract = tronStranger(0x51)389        h.backend.tron.tokens[contract.hex] = .init(decimals: 6, symbol: "TUSD", name: "Test Dollar", balances: [Hex.encode(me.hash): UInt256(80_000_000)])390        let tronToken = try await h.service.addCustomToken(chain: .tronNile, address: contract.base58)391        let tronReview = try await h.service.prepareSend(chain: .tronNile, asset: .token(tronToken), to: tronRecipient.base58, amount: UInt256(25_000_000))392        let tronFrames = try await h.service.exportUnsigned(tronReview).frames393        var tronCold = try await h.service.reviewColdTransaction(tronFrames)394        #expect(tronCold.knownTokens == [tronToken] && tronCold.summary.contains("Send 25 TUSD to \(tronRecipient.base58)"))395        try await h.service.removeCustomToken(tronToken)396        tronCold = try await h.service.reviewColdTransaction(tronFrames)397        #expect(tronCold.knownTokens.isEmpty && tronCold.summary.contains { $0.contains("25000000 base units") })398        // a plain TRX transfer names no token399        let plain = try await h.service.prepareSend(chain: .tronNile, asset: .native, to: tronRecipient.base58, amount: UInt256(1_000_000))400        #expect(try await h.service.reviewColdTransaction(try await h.service.exportUnsigned(plain).frames).knownTokens.isEmpty)401    }402403    @Test func unverifiedPSBTAmountsGoThroughTheUnifiedColdSigning() async throws {404        let c = try await PSBTAmountVerificationTests.cold()405        defer { c.h.cleanup() }406        let s = try PSBTAmountVerificationTests.Scenario(c.account)407        var psbt = try PSBT(unsignedTransaction: s.tx)408        try psbt.setWitnessUTXO(s.a.outputs[0], inputIndex: 0)409        try psbt.setWitnessUTXO(s.b.outputs[0], inputIndex: 1)410        // refused by default through the unified call, exactly as through `signPSBT`411        guard case .invalidPSBT(let why)? = await walletError({ try await c.h.service.signColdTransaction([psbt.base64]) }) else {412            Issue.record("unverified amounts must not be signed by default")413            return414        }415        #expect(why.contains("cannot be verified") && why.contains("explicit confirmation"))416        // blind signing is another consent: it does not stand for this one417        guard case .invalidPSBT? = await walletError({ try await c.h.service.signColdTransaction([psbt.base64], allowBlindSigning: true) }) else {418            Issue.record("allowing blind signing must not accept unverified amounts")419            return420        }421        let signed = try await c.h.service.signColdTransaction([psbt.base64], acceptUnverifiedAmounts: true)422        guard case .bitcoin(let review) = signed.review.body else {423            Issue.record("a PSBT review is expected")424            return425        }426        #expect(!review.inputAmountsVerified && review.isFullySigned && signed.id == review.txid && !signed.export.frames.isEmpty)427        // a PSBT whose amounts are verified does not need it, and is signed the same with or without428        var verified = try PSBT(unsignedTransaction: s.tx)429        try verified.setNonWitnessUTXO(s.a, inputIndex: 0)430        try verified.setNonWitnessUTXO(s.b, inputIndex: 1)431        try verified.setWitnessUTXO(s.a.outputs[0], inputIndex: 0)432        try verified.setWitnessUTXO(s.b.outputs[0], inputIndex: 1)433        #expect(try await c.h.service.signColdTransaction([verified.base64]).id == signed.id)434    }435}436437/// The Quantum Shield on every chain: the EVM account with one network, approvals of every EVM network that has a438/// history source, unmeasured coins as entries, the sweep of every UTXO coin, and what is said of a TRON account.439@Suite(.readsMainnetPolicy) struct ShieldEveryChainTests {440    @Test func theEVMAccountExistsWithOneNetworkAndSectionThreeNamesEveryChain() async throws {441        let h = try await MultiHarness.wallet(chains: [.ethereum, .litecoin, .solana])442        defer { h.cleanup() }443        var shield = await h.service.shieldReport()444        // one EVM network: the account has its entry all the same, not measured yet445        var evm = try #require(shield.report.keyExposure.accounts.first { $0.family == .evm })446        #expect(evm.address == MultiHarness.ethereumAddress && evm.networks.map(\.name) == ["Ethereum Sepolia"] && evm.publicKeyExposed == nil)447        #expect(evm.unmeasuredNetworks == ["Ethereum Sepolia"])448        // a coin that was not measured is an entry of its own, and its finding is the same as before449        #expect(shield.report.keyExposure.unmeasuredCoins == [.litecoinTestnet] && shield.report.keyExposure.otherCoins.isEmpty)450        #expect(shield.report.keyExposure.findings.contains { $0.id == "utxo.exposure.unmeasured.litecoin-testnet" } && shield.report.keyExposure.isPartlyUnmeasured)451        // section 3: one case per chain, with the registry identifier of the network452        let chains = shield.report.networkResistance.chains453        #expect(chains.map(\.chain) == [.bitcoin, .litecoin, .ethereum, .solana])454        #expect(chains.map(\.networkID) == ["bitcoin-signet", "litecoin-testnet", "ethereum-sepolia", "solana-devnet"])455        for status in chains {456            let descriptor = try #require(status.networkID.flatMap { ChainRegistry.descriptor(ChainID($0)) })457            #expect(descriptor.displayName == status.networkName)458        }459        #expect(chains.map(\.chain.kind) == [.bitcoin, .bitcoin, .ethereum, .solana])460        // the identifiers of the findings did not change with the new cases461        #expect(shield.report.networkResistance.findings.map(\.id)462            == ["network.bitcoin.not-resistant", "network.bitcoin.litecoin-testnet.not-resistant", "network.ethereum.not-resistant", "network.solana.not-resistant"])463        #expect(NetworkResistance.Chain.allCases.count == 13)464465        _ = await h.service.synchronize(chains: [.ethereumSepolia])466        shield = await h.service.shieldReport()467        evm = try #require(shield.report.keyExposure.accounts.first { $0.family == .evm })468        #expect(evm.networks.count == 1 && evm.publicKeyExposed != nil && evm.unmeasuredNetworks.isEmpty)469    }470471    @Test func approvalsOfEveryEVMNetworkWithAHistorySourceAreReportedAndCanBeRevoked() async throws {472        // Avalanche Fuji has a history source, Polygon Amoy has none473        let h = try await MultiHarness.wallet(chains: [.ethereum, .avalanche, .polygon])474        defer { h.cleanup() }475        let owner = EthereumWalletTests.owner, usdc = EthereumWalletTests.usdc476        let spender = try #require(EthereumAddress(EthereumWalletTests.spender))477        let fuji = h.backend.evm(.avalancheFuji)478        fuji.balances[owner] = EthereumWalletTests.oneEther479        var token = FakeBackend.TokenContract(symbol: "USDC", name: "USD Coin", decimals: UInt256(6))480        token.allowances["\(owner)|\(EthereumWalletTests.spender)"] = .max481        fuji.tokens[usdc.lowercased()] = token482        fuji.indexerTransactions = "{\"items\":[" + EthereumWalletTests.nativeItem(hash: EthereumWalletTests.hash(3), from: Harness.abandonEthereumAddress, to: usdc, value: "0",483                                                                                   method: "approve", time: "2026-11-03T10:00:00.000000Z") + "],\"next_page_params\":null}"484        fuji.transactionsByHash[EthereumWalletTests.hash(3)]485            = "{\"hash\":\"0x\",\"from\":\"\(owner)\",\"to\":\"\(usdc.lowercased())\",\"input\":\"0x\(Hex.encode(ERC20.approve(spender: spender, amount: .max)))\",\"value\":\"0x0\"}"486487        // before any synchronization: the two networks with a history source are listed, not measured; Amoy is not488        var shield = await h.service.shieldReport()489        var evm = try #require(shield.report.keyExposure.accounts.first { $0.family == .evm })490        #expect(evm.approvals.map(\.network) == [.sepolia, .avalancheFuji] && evm.approvals.allSatisfy { $0.approvals == nil })491        #expect(evm.approvals.map(\.isPrimary) == [true, false])492        #expect(evm.findings.contains { $0.id == "evm.approvals.unknown.avalanchefuji" } && !evm.findings.contains { $0.id.contains("polygonamoy") })493494        #expect(await h.service.synchronize().allSatisfy(\.succeeded))495        shield = await h.service.shieldReport()496        evm = try #require(shield.report.keyExposure.accounts.first { $0.family == .evm })497        let onFuji = try #require(evm.approvals.first { $0.network == .avalancheFuji }?.approvals)498        #expect(onFuji.count == 1 && onFuji[0].spender == spender && onFuji[0].isUnlimited && onFuji[0].token.network == .avalancheFuji)499        #expect(evm.approvals.first { $0.network == .sepolia }?.approvals == [] && evm.openApprovals == onFuji)500        // an unlimited approval on a secondary network weighs as much as on the primary one501        let finding = try #require(evm.findings.first { $0.id == "evm.approvals.open.avalanchefuji" })502        #expect(finding.severity == .critical && finding.title == "Open token approvals on Avalanche Fuji" && shield.report.keyExposure.level == .critical)503        // the primary network keeps its own finding, and is counted once in the plan504        #expect(shield.report.keyExposure.ethereum?.openApprovals == [] && shield.report.keyExposure.findings.contains { $0.id == "eth.approvals.none" })505        #expect(shield.report.migrationFigures.openApprovals == 1 && shield.migrationPlan.actionable.contains { $0.id == "revoke-approvals" })506507        // the revocation is built on the network of the approval508        let review = try await h.service.revokeApproval(token: onFuji[0].token, spender: onFuji[0].spender)509        #expect(review.network == .avalancheFuji && review.transaction.chainID == EthereumNetwork.avalancheFuji.chainID && review.amount.isZero)510        let uniform = await h.service.review(for: review)511        #expect(uniform.chain.id == .avalancheFuji)512        _ = try await h.service.signAndBroadcast(uniform)513        #expect(fuji.broadcastEthereum.count == 1 && h.backend.base.broadcastEthereum.isEmpty)514    }515516    @Test func exposedCoinsOfEveryUTXOCoinAreCountedAndSwept() async throws {517        let h = try await CoinFixture.wallet(chain: .litecoin, network: .litecoinTestnet)518        defer { h.cleanup() }519        h.backend.fund(CoinFixture.litecoinTestnet0, 500_000)520        _ = await h.service.synchronize(chains: [.litecoinTestnet])521        // nothing is exposed yet: nothing to sweep, no step in the plan522        guard case .invalidInput? = await walletError({ try await h.service.prepareSweepOfExposed(chain: .litecoinTestnet, feeRate: .minimum(for: .litecoinTestnet)) }) else {523            Issue.record("a sweep without exposed coins must be refused")524            return525        }526        #expect(await h.service.shieldReport().migrationPlan.steps.contains { $0.id == "sweep-ltc" } == false)527528        // spend from the first address, then receive on it again: that coin sits behind a published key529        let payment = try await h.service.prepareSend(chain: .litecoinTestnet, asset: .native, to: CoinFixture.external(.litecoinTestnet), amount: UInt256(100_000))530        _ = try await h.service.signAndBroadcast(payment)531        h.backend.confirmAll(at: 130)532        h.backend.fund(CoinFixture.litecoinTestnet0, 70_000, height: 131)533        h.backend.fund(CoinFixture.litecoinTestnet0, 30_000, height: 132)534        _ = await h.service.synchronize(chains: [.litecoinTestnet])535536        let shield = await h.service.shieldReport()537        let coin = try #require(shield.report.keyExposure.otherCoins.first)538        #expect(coin.network == .litecoinTestnet && coin.exposedUTXOCount == 2 && coin.totals.revealedBySpend == 100_000)539        // counted with its own figures, and in the plan with its own step540        let figures = shield.report.migrationFigures.otherCoins541        #expect(figures.map(\.network) == [.litecoinTestnet] && figures.first?.exposedUTXOs == 2 && figures.first?.reusedAddresses == coin.reusedAddresses.count)542        #expect(shield.report.migrationFigures.exposedBitcoinUTXOs == 0 && shield.report.migrationFigures.exposedUTXOsOfEveryCoin == 2)543        let step = try #require(shield.migrationPlan.steps.first { $0.id == "sweep-ltc" })544        #expect(step.isActionable && step.title == "Sweep exposed Litecoin to fresh addresses" && step.detail.hasPrefix("2 Litecoin output(s)"))545        #expect(!shield.migrationPlan.steps.contains { $0.id == "sweep-btc" })546547        // the sweep: the exposed coins and nothing else, to a never-used address of this wallet548        let requests = h.backend.requests.count549        let plan = try await h.service.prepareSweepOfExposed(chain: .litecoinTestnet, feeRate: .minimum(for: .litecoinTestnet))550        #expect(h.backend.requests.count == requests)551        #expect(plan.purpose == .sweepExposed && plan.network == .litecoinTestnet && plan.isSendMax && plan.inputs.count == 2)552        #expect(plan.inputs.allSatisfy { $0.address == CoinFixture.litecoinTestnet0 && $0.exposure == .revealedBySpend })553        #expect(plan.outputs.count == 1 && plan.outputs[0].isMine && plan.amount + plan.fee == 100_000 && plan.totalSpent == plan.fee)554        #expect(plan.recipient.hasPrefix("tltc1q") && plan.recipient != CoinFixture.litecoinTestnet0)555        guard case .utxo(let coins)? = await h.service.snapshot().chain(.litecoinTestnet)?.data.value?.extras else {556            Issue.record("no UTXO extras")557            return558        }559        #expect(!coins.addresses.contains { $0.address == plan.recipient && $0.isUsed })560        // a sweep is not a payment: none of the warnings about the destination or the exposed inputs561        #expect(!plan.warnings.contains(.destinationIsOwnAddress) && !plan.warnings.contains(.firstPaymentToAddress) && !plan.warnings.contains(.exposedInputs(count: 2)))562563        let review = await h.service.review(for: plan)564        let sent = try await h.service.signAndBroadcast(review)565        let tx = try BitcoinTransaction(hex: try #require(h.backend.broadcastBitcoin.last))566        #expect(tx.txid == sent.id && tx.inputs.count == 2 && tx.outputs.count == 1)567        try BitcoinVerifier.verify(transaction: tx, spentOutputs: plan.plan.inputs.map(\.output))568        h.backend.confirmAll(at: 140)569        _ = await h.service.synchronize(chains: [.litecoinTestnet])570        #expect(await h.service.shieldReport().report.keyExposure.otherCoins.first?.exposedUTXOCount == 0)571572        // refusals: a chain that is not a UTXO chain, one that is not active573        guard case .invalidInput? = await walletError({ try await h.service.prepareSweepOfExposed(chain: .ethereumSepolia, feeRate: .minimumRelay) }) else {574            Issue.record("a sweep exists on UTXO chains only")575            return576        }577        #expect(await walletError { try await h.service.prepareSweepOfExposed(chain: .dogecoinTestnet, feeRate: .minimum(for: .dogecoinTestnet)) }578            == .chainNotActive("Dogecoin Testnet"))579    }580581    /// One page of the index: `entries` transfers of 1 TRX, with a fingerprint when the index has more.582    static func tronPage(from: TronAddress, to: TronAddress, entries: Int, more: Bool, node: FakeTron, salt: UInt64 = 0) throws -> String {583        let reference = try #require(TronBlockReference(number: node.headNumber, id: Endian.be64(node.headNumber) + Bytes(repeating: 0xab, count: 24), timestamp: node.headTimestamp))584        var items = [String]()585        for i in 0..<entries {586            let stamp = node.headTimestamp - UInt64(i + 1) * 60_000 - salt587            let tx = try TronTransaction.transfer(from: from, to: to, amountSun: 1_000_000 + UInt64(i), reference: reference, timestamp: stamp, expiration: stamp + 60_000)588            let id = Hex.encode(SHA256.hash(tx.rawData))589            items.append(#"{"txID":"\#(id)","raw_data_hex":"\#(Hex.encode(tx.rawData))","ret":[{"contractRet":"SUCCESS","fee":0}],"block_timestamp":\#(stamp),"blockNumber":\#(node.headNumber - 30)}"#)590        }591        return #"{"data":["# + items.joined(separator: ",") + #"],"success":true,"meta":{"page_size":\#(entries)"# + (more ? #","fingerprint":"abcDEF123""# : "") + "}}"592    }593594    @Test func aBusyTronAccountIsMeasuredAndWhatIsNotMeasuredSaysWhy() async throws {595        let h = try await MultiChainSendTests.tronWallet()596        defer { h.cleanup() }597        let node = h.backend.tron598        let me = try #require(TronAddress(MultiHarness.tronAddress)), stranger = tronStranger()599        func tron() async throws -> (exposure: ChainExposure, network: AccountKeyExposure.Network) {600            #expect(await h.service.synchronize(chains: [.tronNile]).allSatisfy(\.succeeded))601            let data = try #require(await h.service.chainSnapshot(.tronNile)?.data.value)602            let account = try #require(await h.service.shieldReport().report.keyExposure.accounts.first { $0.family == .tron })603            return (data.exposure, try #require(account.networks.first))604        }605        // the case of a well-known test address: the page read holds only payments received, and the index has more.606        // An index that ignores the question "what did this account send" leaves it open — and the report says that,607        // not "no history source"608        node.history = try Self.tronPage(from: stranger, to: me, entries: 3, more: true, node: node)609        var result = try await tron()610        #expect(result.exposure.publicKeyExposed == nil && result.network.publicKeyExposed == nil && node.ownHistoryRequests == 1)611        #expect(result.network.evidence == "history longer than what was read" && result.exposure.statement.contains("history longer than what was read"))612        #expect(!result.exposure.statement.contains("no history source"))613        #expect(await h.service.chainSnapshot(.tronNile)?.data.value?.history.value?.count == 3)614615        // the index answers the question: the account sent transactions, older than the page shown616        node.ownHistory = try Self.tronPage(from: me, to: stranger, entries: 2, more: true, node: node, salt: 7)617        result = try await tron()618        #expect(result.exposure.publicKeyExposed == true && result.network.publicKeyExposed == true && node.ownHistoryRequests == 2)619        #expect(result.network.evidence == "transactions sent by the account, outside the history shown")620        // entries of somebody else in that answer prove nothing about this account621        node.ownHistory = try Self.tronPage(from: stranger, to: me, entries: 2, more: true, node: node, salt: 9)622        result = try await tron()623        #expect(result.exposure.publicKeyExposed == nil && result.network.evidence == "history longer than what was read")624        // it sent nothing at all: measured, and hidden625        node.ownHistory = #"{"data":[],"success":true,"meta":{"page_size":0}}"#626        result = try await tron()627        #expect(result.exposure.publicKeyExposed == false && result.network.publicKeyExposed == false && result.network.evidence == "history")628629        // a complete history needs no second question630        let asked = node.ownHistoryRequests631        node.history = try Self.tronPage(from: stranger, to: me, entries: 3, more: false, node: node)632        result = try await tron()633        #expect(result.exposure.publicKeyExposed == false && node.ownHistoryRequests == asked)634        node.history = try Self.tronPage(from: me, to: stranger, entries: 1, more: true, node: node)635        result = try await tron()636        #expect(result.exposure.publicKeyExposed == true && result.network.evidence == "history" && node.ownHistoryRequests == asked)637638        // the index does not answer: said as such639        node.historyStatus = 500640        result = try await tron()641        #expect(result.exposure.publicKeyExposed == nil && result.network.evidence == "the history could not be read")642        // no index at all: "no history source", and only then643        var endpoints = MultiBackend.endpoints()644        endpoints.tron.history["nile"] = []645        try await h.service.setChainEndpoints(endpoints)646        result = try await tron()647        #expect(result.exposure.publicKeyExposed == nil && result.network.evidence == "no history source" && result.exposure.statement.contains("no history source"))648    }649}650651/// Litecoin, Dogecoin and Bitcoin Cash keep their last synchronization between launches, like the other chains.652@Suite(.readsMainnetPolicy) struct UTXOCoinPersistenceTests {653    @Test func aCoinShowsItsLastKnownStateAtTheNextLaunchAndNeverSpendsFromIt() async throws {654        let h = try await CoinFixture.wallet(chain: .litecoin, network: .litecoinTestnet)655        defer { h.cleanup() }656        let funding = h.backend.fund(CoinFixture.litecoinTestnet0, 500_000)657        #expect(await h.service.synchronize(chains: [.litecoinTestnet]).allSatisfy(\.succeeded))658        let live = try #require(await h.service.snapshot().chain(.litecoinTestnet)?.data.value)659        #expect(!live.isFromPreviousSession && live.native.confirmed == UInt256(500_000))660        let store = try FileStore(root: h.directory)661        #expect(store.exists("utxo-sync-litecoinTestnet.json"))662663        // the next launch: the same balance, coins, history and receive address, flagged as the previous session's,664        // without a single request665        let requests = h.backend.requests.count666        let reopened = try await Harness.make(backend: h.backend, clock: h.clock, directory: h.directory, configure: false)667        let chain = try #require(await reopened.service.snapshot().chain(.litecoinTestnet))668        let restored = try #require(chain.data.value)669        #expect(restored.isFromPreviousSession && restored.native == live.native && restored.height == live.height && restored.synchronizedAt == live.synchronizedAt)670        #expect(restored.history.value?.map(\.hash) == [funding] && restored.exposure == live.exposure)671        #expect(chain.receive?.address == (await h.service.snapshot().chain(.litecoinTestnet)?.receive?.address))672        guard case .utxo(let coins) = restored.extras else {673            Issue.record("no UTXO extras")674            return675        }676        #expect(coins.utxos.count == 1 && coins.utxos[0].utxo.value == 500_000 && coins.isFromPreviousSession)677        #expect(h.backend.requests.count == requests)678        // the Shield says what it rests on, and the valuation too679        let shield = await reopened.service.shieldReport()680        #expect(shield.isFromPreviousSession && shield.report.keyExposure.otherCoins.map(\.network) == [.litecoinTestnet] && shield.report.keyExposure.unmeasuredCoins.isEmpty)681        #expect(await reopened.service.portfolioValuation().isFromPreviousSession)682683        // nothing is paid from it: its coins may be gone684        try await reopened.service.unlock(password: Harness.password)685        guard case .notSynchronized(let why)? = await walletError({686            try await reopened.service.prepareSend(chain: .litecoinTestnet, asset: .native, to: CoinFixture.external(.litecoinTestnet), amount: UInt256(100_000))687        }) else {688            Issue.record("a payment must not be built from the previous session's coins")689            return690        }691        #expect(why.contains("previous session"))692        guard case .notSynchronized? = await walletError({ try await reopened.service.prepareSweepOfExposed(chain: .litecoinTestnet, feeRate: .minimum(for: .litecoinTestnet)) }) else {693            Issue.record("a sweep must not be built from the previous session's coins")694            return695        }696        // a synchronization makes it current again697        #expect(await reopened.service.synchronize(chains: [.litecoinTestnet]).allSatisfy(\.succeeded))698        #expect(await reopened.service.snapshot().chain(.litecoinTestnet)?.data.value?.isFromPreviousSession == false)699        _ = try await reopened.service.prepareSend(chain: .litecoinTestnet, asset: .native, to: CoinFixture.external(.litecoinTestnet), amount: UInt256(100_000))700    }701702    @Test func aRecordThatIsNotExactlyThisAccountsIsRemoved() async throws {703        let h = try await CoinFixture.wallet(chain: .litecoin, network: .litecoinTestnet)704        defer { h.cleanup() }705        h.backend.fund(CoinFixture.litecoinTestnet0, 500_000)706        #expect(await h.service.synchronize(chains: [.litecoinTestnet]).allSatisfy(\.succeeded))707        let store = try FileStore(root: h.directory)708        let name = "utxo-sync-litecoinTestnet.json"709        let original = try store.read(name)710711        func reopenedData() async throws -> ChainData? {712            let reopened = try await Harness.make(backend: h.backend, clock: h.clock, directory: h.directory, configure: false)713            return await reopened.service.snapshot().chain(.litecoinTestnet)?.data.value714        }715        // an address that is not the account's, an amount that does not add up, an unknown version, not JSON at all716        var object = try #require(try JSONSerialization.jsonObject(with: Data(original)) as? [String: Any])717        var entries = try #require(object["entries"] as? [[String: Any]])718        entries[0]["address"] = CoinFixture.external(.litecoinTestnet)719        object["entries"] = entries720        // (a coin whose amount is not the one of the transaction that created it)721        var inflated = try #require(try JSONSerialization.jsonObject(with: Data(original)) as? [String: Any])722        var inflatedEntries = try #require(inflated["entries"] as? [[String: Any]])723        let used = try #require(inflatedEntries.firstIndex { !(($0["coins"] as? [[String: Any]]) ?? []).isEmpty })724        var coins = try #require(inflatedEntries[used]["coins"] as? [[String: Any]])725        coins[0]["value"] = 900_000726        inflatedEntries[used]["coins"] = coins727        inflated["entries"] = inflatedEntries728        for tampered in [try JSONSerialization.data(withJSONObject: object), try JSONSerialization.data(withJSONObject: inflated),729                         Data(String(decoding: original, as: UTF8.self).replacingOccurrences(of: "\"version\":1", with: "\"version\":9").utf8), Data("not json".utf8)] {730            try store.write(Bytes(tampered), to: name, keepPrevious: false)731            #expect(try await reopenedData() == nil)732            #expect(!store.exists(name))733        }734        // the untouched record is accepted735        try store.write(original, to: name, keepPrevious: false)736        #expect(try await reopenedData()?.isFromPreviousSession == true)737738        // other endpoints: what was read from the previous ones is not carried over739        try await h.service.unlock(password: Harness.password)740        var endpoints = CoinFixture.endpoints([.litecoinTestnet])741        endpoints.esplora["litecoinTestnet"] = ["https://esplora.test/api", "https://other.test/api"]742        try await h.service.setEndpoints(endpoints)743        #expect(!store.exists(name))744        // deleting the wallet removes the record of every coin745        try await h.service.setEndpoints(CoinFixture.endpoints([.litecoinTestnet]))746        #expect(await h.service.synchronize(chains: [.litecoinTestnet]).allSatisfy(\.succeeded))747        #expect(store.exists(name))748        try await h.service.deleteWallet()749        #expect(!store.exists(name))750    }751}752
Files main
Menu

Theme