SPB Git

Repository Public

MultiChainTests.swift 44.4 KB 599 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Tests/QyvoraWalletTests/MultiChainTests.swift8// Module           : Tests9// Repository       : https://git.spboucher.ai/qyvora10// Project Website  : Not specified11// Created          : 2026-12-0512// Last Modified    : 2026-12-0513//14// Author           : Simon-Pierre Boucher15// Position         : Professor of Finance16// Institution      : Université du Québec en Outaouais (UQO)17// Organization     : SP Boucher18// Website          : https://spboucher.ai19// Git              : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development      : dev@spboucher.ai23// Support          : support@spboucher.ai24// Security/Admin   : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License          : None specified (no license file in this repository)33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import Foundation42import Testing43import QyvoraMath44import QyvoraCore45import QyvoraBitcoin46import QyvoraEthereum47import QyvoraNetworking48import QyvoraStorage49import QyvoraVault50import QyvoraRecovery51import QyvoraQuantumShield52import QyvoraSolana53import QyvoraTron54@testable import QyvoraWallet5556@Suite(.readsMainnetPolicy) struct MultiChainModelTests {57    @Test func theRegistryDescribesEveryChain() {58        let all = ChainRegistry.all59        #expect(Set(all.map(\.id)).count == all.count)60        for d in all {61            #expect(ChainRegistry.descriptor(d.id) == d)62            let main = try! #require(ChainRegistry.descriptor(d.mainCounterpart))63            #expect(!main.isTest && main.family == d.family && main.nativeSymbol == d.nativeSymbol && main.nativeDecimals == d.nativeDecimals)64            #expect(!d.testCounterparts.isEmpty && d.testCounterparts.allSatisfy { ChainRegistry.descriptor($0)?.isTest == true })65            if d.isTest { #expect(d.testCounterparts.contains(d.id)) }66        }67        #expect(ChainRegistry.defaultEnabled == [.bitcoin, .ethereum])68        #expect(ChainRegistry.groups.map(\.family) == [.utxo, .evm, .solana, .tron])69        #expect(ChainRegistry.groups.flatMap(\.chains).map(\.id) == ChainRegistry.mainChains.map(\.id))70        // the documented test network of each chain71        #expect(ChainRegistry.defaultTestNetwork(of: .bitcoin) == .bitcoinSignet && ChainRegistry.defaultTestNetwork(of: .solana) == .solanaDevnet)72        #expect(ChainRegistry.defaultTestNetwork(of: .tron) == .tronNile && ChainRegistry.defaultTestNetwork(of: .base) == .baseSepolia)73        #expect(ChainRegistry.descriptor(.polygon)?.testCounterparts == [.polygonAmoy] && ChainRegistry.descriptor(.avalanche)?.testCounterparts == [.avalancheFuji])74        // facts of the families75        let solana = try! #require(ChainRegistry.descriptor(.solanaDevnet)), tron = try! #require(ChainRegistry.descriptor(.tronNile))76        #expect(solana.nativeDecimals == 9 && solana.signatureScheme == "Ed25519" && solana.derivationPath == "m/44'/501'/0'/0'" && solana.capabilities.memo)77        #expect(tron.nativeDecimals == 6 && tron.derivationPath == "m/44'/195'/0'/0/0" && !tron.capabilities.feeTiers && tron.capabilities.tokens)78        #expect(ChainRegistry.descriptor(.base)?.evmChainID == 8_453 && ChainRegistry.descriptor(.ethereum)?.derivationPath == "m/44'/60'/0'/0/0")79        // seven EVM networks ship without a history source, and say so80        let withoutHistory = all.filter { $0.family == .evm && !$0.capabilities.historyAvailable }.map(\.id)81        #expect(Set(withoutHistory) == [.base, .arbitrum, .arbitrumSepolia, .polygon, .polygonAmoy, .bsc, .bscTestnet])82        // explorer links are built only for identifiers of the chain83        #expect(solana.explorerTransactionURL("not a signature") == nil && tron.explorerAddressURL(MultiHarness.ethereumAddress) == nil)84        #expect(tron.explorerAddressURL(MultiHarness.tronAddress)?.absoluteString == "https://nile.tronscan.org/#/address/\(MultiHarness.tronAddress)")85        #expect(solana.explorerAddressURL(MultiHarness.solanaAddress)?.absoluteString == "https://explorer.solana.com/address/\(MultiHarness.solanaAddress)?cluster=devnet")86        #expect(ChainRegistry.descriptor(.bitcoinSignet)?.explorerTransactionURL(String(repeating: "ab", count: 32))?.absoluteString87            == "https://mempool.space/signet/tx/" + String(repeating: "ab", count: 32))88    }8990    @Test func onePhraseGivesTheAccountsOfEveryFamily() async throws {91        let h = try await MultiHarness.make()92        defer { h.cleanup() }93        try await h.service.importWallet(words: Harness.abandon, password: Harness.password)94        let profile = await h.service.currentProfile()95        // the vectors published by the chain modules for "abandon … about"96        #expect(profile.solanaAddress == MultiHarness.solanaAddress)97        #expect(profile.tronAddress == MultiHarness.tronAddress)98        #expect(profile.ethereumAddress?.checksummed == MultiHarness.ethereumAddress)99        #expect(profile.version == WalletProfile.currentVersion && profile.enabledChains == [.bitcoin, .ethereum] && profile.networkMode == .test)100        // the vault vouches for the same data101        let binding = try #require(try await h.service.accountBindingRecord()?.data)102        #expect(binding.solana == MultiHarness.solanaAddress && binding.tron == MultiHarness.tronAddress && binding.isComplete)103        #expect(binding == profile.publicData)104105        // the recovery sheet lists every chain with its path106        let sheet = try await h.service.recoverySheet()107        #expect(sheet.formatVersion == 2 && sheet.privateMaterial == nil)108        #expect(sheet.ethereum.first?.address == MultiHarness.ethereumAddress && sheet.ethereum.first?.derivationPath == "m/44'/60'/0'/0/0")109        let solana = try #require(sheet.otherChains.first { $0.chain == "Solana" }), tron = try #require(sheet.otherChains.first { $0.chain == "TRON" })110        #expect(solana.address == MultiHarness.solanaAddress && solana.derivationPath == "m/44'/501'/0'/0'" && solana.scheme == "SLIP-0010 Ed25519")111        #expect(tron.address == MultiHarness.tronAddress && tron.derivationPath == "m/44'/195'/0'/0/0")112        let text = sheet.plainText()113        #expect(text.contains(MultiHarness.solanaAddress) && text.contains(MultiHarness.tronAddress) && text.contains("m/44'/501'/0'/0'") && text.contains("EVM NETWORKS"))114        // a sheet of format 1 (no "otherChains") is still read115        var object = try #require(try JSONSerialization.jsonObject(with: try sheet.json()) as? [String: Any])116        object["otherChains"] = nil117        object["formatVersion"] = 1118        let old = try RecoverySheet.fromJSON(try JSONSerialization.data(withJSONObject: object))119        #expect(old.otherChains.isEmpty && old.formatVersion == 1 && old.bitcoin == sheet.bitcoin)120    }121122    /// A wallet made by QYVORA 1.0: a profile without the multi-chain fields and a version-1 binding in the vault.123    @Test func aWalletOfVersionOneGetsTheNewAccountsAtItsNextUnlock() async throws {124        let h = try await MultiHarness.make()125        defer { h.cleanup() }126        try await h.service.importWallet(words: Harness.abandon, password: Harness.password)127        let before = await h.service.currentProfile()128        // the binding as version 1 wrote it129        let record = try #require(try await h.service.accountBindingRecord())130        let accounts = before.bitcoinAccounts.filter { $0.key == "test" || $0.key == "main" }131        let legacy: [String: Any] = ["format": "qyvora-account-binding", "version": 1, "ethereumAddress": MultiHarness.ethereumAddress,132                                     "bitcoinAccounts": accounts.mapValues { ["extendedPublicKey": $0.extendedPublicKey, "masterFingerprint": $0.masterFingerprint ?? ""] }]133        try await h.vault.updateRecord(record.id, payload: Bytes(try JSONSerialization.data(withJSONObject: legacy)))134        // the profile as version 1 wrote it135        let path = h.directory.appendingPathComponent("wallet-profile.json")136        var object = try #require(try JSONSerialization.jsonObject(with: Data(contentsOf: path)) as? [String: Any])137        for key in ["enabledChains", "networkMode", "testNetworks", "solanaAddress", "tronAddress", "solanaEndpoints", "tronEndpoints", "customSolanaTokens",138                    "customTronTokens", "hasTronAPIKey"] { object[key] = nil }139        object["version"] = 1140        object["bitcoinAccounts"] = (object["bitcoinAccounts"] as? [String: Any])?.filter { $0.key == "test" || $0.key == "main" }141        try JSONSerialization.data(withJSONObject: object).write(to: path)142143        let reopened = try await MultiHarness.make(backend: h.backend, clock: h.clock, directory: h.directory, configure: false)144        let locked = await reopened.service.currentProfile()145        // nothing is lost and nothing is invented while the vault is locked146        #expect(locked.kind == .full && locked.solanaAddress == nil && locked.tronAddress == nil && locked.enabledChains == [.bitcoin, .ethereum])147        #expect(locked.networkMode == .test && locked.solanaEndpoints == .default && locked.tronEndpoints == .default && locked.version == 2)148        #expect(locked.ethereumAddress == before.ethereumAddress && locked.bitcoinNetwork == .signet)149150        try await reopened.service.unlock(password: Harness.password)151        let after = await reopened.service.currentProfile()152        #expect(after.solanaAddress == MultiHarness.solanaAddress && after.tronAddress == MultiHarness.tronAddress)153        #expect(after.bitcoinAccounts["test"] == before.bitcoinAccounts["test"] && after.ethereumAddress == before.ethereumAddress)154        // a migration is not a repair155        #expect(await reopened.service.accountBindingRepairCount() == 0)156        let binding = try #require(try await reopened.service.accountBindingRecord()?.data)157        #expect(binding.isComplete && binding.solana == MultiHarness.solanaAddress && binding.tron == MultiHarness.tronAddress)158        // and it is written: the next launch has the accounts before any unlock159        let third = try await MultiHarness.make(backend: h.backend, clock: h.clock, directory: h.directory, configure: false)160        #expect(await third.service.currentProfile().solanaAddress == MultiHarness.solanaAddress)161        #expect(h.backend.requests.isEmpty)162163        // a profile that names another Solana account than the vault's is repaired, and counted164        var tampered = try #require(try JSONSerialization.jsonObject(with: Data(contentsOf: path)) as? [String: Any])165        tampered["solanaAddress"] = solanaStranger().base58166        try JSONSerialization.data(withJSONObject: tampered).write(to: path)167        let fourth = try await MultiHarness.make(backend: h.backend, clock: h.clock, directory: h.directory, configure: false)168        #expect(await fourth.service.currentProfile().solanaAddress == solanaStranger().base58)169        try await fourth.service.unlock(password: Harness.password)170        #expect(await fourth.service.currentProfile().solanaAddress == MultiHarness.solanaAddress)171        #expect(await fourth.service.accountBindingRepairCount() == 1)172    }173174    @Test func chainsAreEnabledAndDisabled() async throws {175        let h = try await MultiHarness.make()176        defer { h.cleanup() }177        try await h.service.importWallet(words: Harness.abandon, password: Harness.password)178        #expect(await h.service.activeChains().map(\.id) == [.bitcoinSignet, .ethereumSepolia])179        #expect(await h.service.snapshot().chains.map(\.id) == [.bitcoinSignet, .ethereumSepolia])180181        try await h.service.setChainEnabled(.solana, enabled: true)182        try await h.service.setChainEnabled(.tronNile, enabled: true)     // a test identifier means its chain183        try await h.service.setChainEnabled(.base, enabled: true)184        #expect(await h.service.currentProfile().enabledChains == [.bitcoin, .ethereum, .base, .solana, .tron])185        let snapshot = await h.service.snapshot()186        #expect(snapshot.chains.map(\.id) == [.bitcoinSignet, .ethereumSepolia, .baseSepolia, .solanaDevnet, .tronNile])187        #expect(snapshot.chains.map(\.isPrimary) == [true, true, false, false, false])188        #expect(snapshot.chains.allSatisfy { $0.data == .notLoaded && !$0.isSynchronizing && $0.limits == nil })189        // where to be paid is known offline, with the rule of each family190        let receive = snapshot.chains.map { $0.receive }191        #expect(receive[0]?.rule == .freshAddressPerPayment && receive[0]?.address == Harness.abandonFirstTestAddress)192        #expect(receive[2]?.address == MultiHarness.ethereumAddress && receive[2]?.rule == .fixedAddress && receive[2]?.notes.first?.contains("Base Sepolia") == true)193        #expect(receive[3]?.address == MultiHarness.solanaAddress && receive[3]?.notes.first?.contains("public key") == true)194        #expect(receive[4]?.address == MultiHarness.tronAddress && snapshot.chain(.tronNile)?.accountAddress == MultiHarness.tronAddress)195196        // the test network of a chain that has several197        try await h.service.setTestNetwork(.solanaTestnet)198        try await h.service.setTestNetwork(.tronShasta)199        try await h.service.setTestNetwork(.bitcoinTestnet)200        #expect(await h.service.activeChains().map(\.id) == [.bitcoinTestnet, .ethereumSepolia, .baseSepolia, .solanaTestnet, .tronShasta])201        #expect(await h.service.currentProfile().bitcoinNetwork == .testnet)202        #expect(await walletError { try await h.service.setTestNetwork(.solana) } == .invalidInput("Solana is not a test network."))203204        // disabling: the primary EVM network moves to an enabled EVM chain; one chain at least stays205        try await h.service.setChainEnabled(.ethereum, enabled: false)206        #expect(await h.service.currentProfile().ethereumNetwork == .baseSepolia)207        #expect(await h.service.snapshot().chains.first { $0.id == .baseSepolia }?.isPrimary == true)208        try await h.service.setEnabledChains([.tron])209        #expect(await h.service.activeChains().map(\.id) == [.tronShasta])210        #expect(await walletError { try await h.service.setChainEnabled(.tron, enabled: false) } == .invalidInput("At least one chain must stay enabled."))211        #expect(await walletError { try await h.service.setChainEnabled(ChainID("dogeclassic"), enabled: true) } == .unknownChain("dogeclassic"))212        // a chain that is not active is refused by name, without a request213        #expect(await walletError { try await h.service.synchronize(chain: .solanaDevnet) } == .chainNotActive("Solana Devnet"))214        // (the refusal of a main network while mainnet is off reads the process-wide policy: it is checked in the215        // serialized suite, MainnetPolicyTests.aMainNetworkIsRefusedByNameWhileMainnetIsOff)216        #expect(h.backend.requests.isEmpty)217218        // the choice is kept between launches219        let reopened = try await MultiHarness.make(backend: h.backend, clock: h.clock, directory: h.directory, configure: false)220        #expect(await reopened.service.activeChains().map(\.id) == [.tronShasta])221    }222223    @Test func oneChainFailingNeverStopsTheOthers() async throws {224        let h = try await MultiHarness.wallet(chains: [.bitcoin, .ethereum, .polygon, .optimism, .solana, .tron])225        defer { h.cleanup() }226        let stream = await h.service.events()227        let owner = MultiHarness.ethereumAddress.lowercased()228        h.backend.base.balances[owner] = UInt256(1_000)229        h.backend.evm(.polygonAmoy).balances[owner] = UInt256(7_000)230        h.backend.evm(.polygonAmoy).latestNonce[owner] = 3231        h.backend.solana.lamports[MultiHarness.solanaAddress] = 2_500_000_000232        h.backend.tron.balances[MultiHarness.tronHex(MultiHarness.tronAddress)] = 42_000_000233        // OP Sepolia does not answer; everything else does234        h.backend.silentHosts = ["optimismSepolia.evm.test"]235236        let results = await h.service.synchronize()237        #expect(results.map(\.chain) == [.bitcoinSignet, .ethereumSepolia, .optimismSepolia, .polygonAmoy, .solanaDevnet, .tronNile])238        let failed = results.filter { !$0.succeeded }239        #expect(failed.map(\.chain) == [.optimismSepolia])240        #expect(failed.first?.error?.contains("optimismSepolia.evm.test") == true)241242        let snapshot = await h.service.snapshot()243        let chains = Dictionary(uniqueKeysWithValues: snapshot.chains.map { ($0.id, $0) })244        #expect(chains[.optimismSepolia]?.data == .unavailable(reason: failed.first?.error ?? "") && chains[.optimismSepolia]?.syncError == failed.first?.error)245        let polygon = try #require(chains[.polygonAmoy]?.data.value)246        #expect(polygon.native.confirmed == UInt256(7_000) && polygon.native.symbol == "POL" && polygon.native.pending.isZero && !polygon.isFromPreviousSession)247        // no indexer exists for Amoy: the history is unavailable, with the reason, and nothing stands in for it248        #expect(polygon.history.value == nil && polygon.historyUnavailableReason?.contains("no keyless public history source") == true)249        #expect(polygon.exposure.publicKeyExposed == true && polygon.exposure.evidence == .nonce && polygon.exposure.outgoingTransactionCount == 3)250        let solana = try #require(chains[.solanaDevnet]?.data.value)251        #expect(solana.native.confirmed == UInt256(2_500_000_000) && solana.native.decimals == 9 && solana.height == 5_000 && solana.history.value == [])252        #expect(solana.extras == .solana(SolanaExtras(accountExists: true, systemAccountRent: 890_880, tokenAccountRent: 2_039_280, token2022AccountRent: 2_074_080,253                                                      tokenAccountCount: 0)))254        #expect(solana.exposure.publicKeyExposed == true && solana.exposure.evidence == .addressIsPublicKey)255        let tron = try #require(chains[.tronNile]?.data.value)256        #expect(tron.native.confirmed == UInt256(42_000_000) && tron.native.symbol == "TRX" && tron.height == 60_000_000)257        guard case .tron(let extras) = tron.extras else {258            Issue.record("TRON extras expected")259            return260        }261        #expect(extras.isActivated && extras.freeBandwidth == 600 && extras.energy == 0 && extras.parameters.energyPriceSun == 100)262        // nothing sent was found in a complete history263        #expect(tron.exposure.publicKeyExposed == false && tron.exposure.evidence == .history && tron.history.value == [])264        // the 1.0 accessors show the two primary chains265        #expect(snapshot.ethereum.value?.balance == UInt256(1_000) && snapshot.bitcoin.value != nil)266        #expect(snapshot.ethereum.value == chains[.ethereumSepolia]?.data.value.flatMap { if case .evm(let s) = $0.extras { return s } else { return nil } })267268        // events: every chain reported, the failure with its reason269        var started = Set<ChainID>(), finished = Set<ChainID>(), failures = [ChainID: String]()270        var progress = Set<ChainID>()271        for await event in stream {272            switch event {273            case .chainSyncStarted(let id): started.insert(id)274            case .chainSyncProgress(let id, _, _, _): progress.insert(id)275            case .chainSyncFinished(let id): finished.insert(id)276            case .chainSyncFailed(let id, let reason): failures[id] = reason277            default: break278            }279            if finished.count + failures.count == 6 { break }280        }281        #expect(started.count == 6 && finished.count == 5 && failures[.optimismSepolia] == failed.first?.error)282        #expect(progress.isSuperset(of: [.bitcoinSignet, .ethereumSepolia, .polygonAmoy, .solanaDevnet, .tronNile]))283284        // the chain that failed synchronizes once its endpoint answers; the others are untouched285        h.backend.silentHosts = []286        h.backend.evm(.optimismSepolia).balances[owner] = UInt256(9)287        try await h.service.synchronize(chain: .optimismSepolia)288        let recovered = try #require(await h.service.chainSnapshot(.optimismSepolia))289        #expect(recovered.syncError == nil && recovered.data.value?.native.confirmed == UInt256(9))290        // OP Sepolia has an indexer: its history is read (empty here), not "unavailable"291        #expect(recovered.data.value?.history.value == [])292    }293294    @Test func anEndpointOfAnotherChainIsRefusedPerChain() async throws {295        let h = try await MultiHarness.wallet(chains: [.ethereum, .solana, .tron])296        defer { h.cleanup() }297        // the Solana endpoint serves mainnet-beta, the TRON node serves Shasta: neither is what was asked298        h.backend.solana.genesis = SolanaNetwork.mainnetBeta.genesisHash299        h.backend.tron.genesisID = TronNetwork.shasta.genesisBlockID300        let results = await h.service.synchronize()301        #expect(results.map(\.succeeded) == [true, false, false])302        guard case .wrongChain? = await walletError({ try await h.service.synchronize(chain: .solanaDevnet) }),303              case .wrongChain? = await walletError({ try await h.service.synchronize(chain: .tronNile) }) else {304            Issue.record("an endpoint of another chain must be refused")305            return306        }307        // nothing they said was used308        #expect(await h.service.chainSnapshot(.solanaDevnet)?.data.value == nil)309        #expect(await h.service.chainSnapshot(.tronNile)?.data.value == nil)310        #expect(h.backend.requests.filter { $0.contains("sol.test") }.count == 2)311    }312313    @Test func tokensHistoryAndPersistenceOnSolanaAndTron() async throws {314        let h = try await MultiHarness.wallet(chains: [.solana, .tron])315        defer { h.cleanup() }316        let owner = try #require(SolanaPublicKey(base58: MultiHarness.solanaAddress))317        // Solana: a mint the user adds, another one found on the account318        let listedMint = solanaStranger(40).base58, foundMint = solanaStranger(41).base58319        h.backend.solana.lamports[MultiHarness.solanaAddress] = 1_000_000_000320        h.backend.solana.mints[listedMint] = .init(decimals: 6)321        h.backend.solana.mints[foundMint] = .init(decimals: 2, program: .token2022)322        h.backend.solana.tokenAccounts = [323            .init(address: try SolanaAddress.associatedTokenAccount(owner: owner, mint: SolanaPublicKey(base58: listedMint)!, tokenProgram: .token).base58,324                  mint: listedMint, owner: MultiHarness.solanaAddress, amount: 12_500_000),325            .init(address: solanaStranger(42).base58, mint: foundMint, owner: MultiHarness.solanaAddress, amount: 700, program: .token2022, frozen: true),326        ]327        // TRON: a token the user adds328        let contract = tronStranger(0x51)329        let me = TronAddress(MultiHarness.tronAddress)!330        h.backend.tron.balances[me.hex] = 5_000_000331        h.backend.tron.tokens[contract.hex] = .init(decimals: 6, symbol: "TUSD", name: "Test Dollar", balances: [Hex.encode(me.hash): UInt256(3_210_000)])332333        let added = try await h.service.addCustomToken(chain: .solanaDevnet, address: listedMint, label: "TEST")334        #expect(added.symbol == "TEST" && added.decimals == 6 && added.standard == .spl && added.isCustom && added.chain == .solanaDevnet)335        let tronToken = try await h.service.addCustomToken(chain: .tronNile, address: contract.base58)336        #expect(tronToken.symbol == "TUSD" && tronToken.name == "Test Dollar" && tronToken.decimals == 6 && tronToken.standard == .trc20)337        // an address of another family is refused with its name338        #expect(await walletError { try await h.service.addCustomToken(chain: .solanaDevnet, address: MultiHarness.ethereumAddress) }339            == .address(.wrongFamily(chain: "Solana", found: "an Ethereum (EVM)")))340        #expect(await walletError { try await h.service.addCustomToken(chain: .tronNile, address: tronStranger(0x52).base58) } == .tron(.tokenIsNotAContract))341342        #expect(await h.service.synchronize().allSatisfy(\.succeeded))343        let solana = try #require(await h.service.chainSnapshot(.solanaDevnet)?.data.value)344        #expect(solana.tokens.map(\.token) == [added] && solana.tokens.first?.balance == .available(UInt256(12_500_000)))345        // a token found on the account is kept apart, with what the chain says of it and no invented name346        let detected = try #require(solana.detectedTokens.first)347        #expect(solana.detectedTokens.count == 1 && detected.token.address == foundMint && detected.token.decimals == 2 && detected.token.standard == .splToken2022)348        #expect(detected.balance == .available(UInt256(700)) && detected.warning?.contains("frozen") == true && detected.token.name == "Unlisted SPL token")349        let tron = try #require(await h.service.chainSnapshot(.tronNile)?.data.value)350        #expect(tron.tokens.map(\.token) == [tronToken] && tron.tokens.first?.balance == .available(UInt256(3_210_000)))351352        // accepting, hiding and removing reach the snapshot without network353        let requests = h.backend.requests.count354        try await h.service.acceptDetectedToken(detected.token)355        var now = try #require(await h.service.chainSnapshot(.solanaDevnet)?.data.value)356        #expect(now.detectedTokens.isEmpty && now.tokens.count == 2 && now.tokens.last?.balance == .available(UInt256(700)))357        try await h.service.setTokenHidden(true, token: added)358        now = try #require(await h.service.chainSnapshot(.solanaDevnet)?.data.value)359        #expect(now.tokens.map(\.token.address) == [foundMint])360        try await h.service.removeCustomToken(tronToken)361        #expect(await h.service.chainSnapshot(.tronNile)?.data.value?.tokens.isEmpty == true)362        #expect(h.backend.requests.count == requests)363364        // the next launch shows the last known state, flagged as such, and a change of endpoints forgets it365        let store = try h.store366        #expect(store.exists("solana-sync-devnet.json") && store.exists("tron-sync-nile.json"))367        let reopened = try await MultiHarness.make(backend: h.backend, clock: h.clock, directory: h.directory, configure: false)368        let restored = try #require(await reopened.service.chainSnapshot(.solanaDevnet)?.data.value)369        #expect(restored.isFromPreviousSession && restored.native == now.native && restored.tokens.map(\.token.address) == [foundMint])370        #expect(await reopened.service.chainSnapshot(.tronNile)?.data.value?.isFromPreviousSession == true)371        #expect(await reopened.service.portfolioValuation().isFromPreviousSession)372        try await reopened.service.unlock(password: Harness.password)373        var endpoints = MultiBackend.endpoints()374        endpoints.solana.rpc["devnet"] = ["https://sol2.test"]375        try await reopened.service.setChainEndpoints(endpoints)376        #expect(!store.exists("solana-sync-devnet.json") && store.exists("tron-sync-nile.json"))377        // a file of another account, or with values out of range, is ignored and removed378        let path = h.directory.appendingPathComponent("tron-sync-nile.json")379        var object = try #require(try JSONSerialization.jsonObject(with: Data(contentsOf: path)) as? [String: Any])380        object["balanceSun"] = UInt64.max381        try JSONSerialization.data(withJSONObject: object).write(to: path)382        let third = try await MultiHarness.make(backend: h.backend, clock: h.clock, directory: h.directory, configure: false)383        #expect(await third.service.chainSnapshot(.tronNile)?.data == .notLoaded && !store.exists("tron-sync-nile.json"))384    }385386    @Test func addressesOfAnotherFamilyAreRefusedByName() async throws {387        let h = try await MultiHarness.wallet(chains: [.bitcoin, .ethereum, .solana, .tron])388        defer { h.cleanup() }389        let bitcoin = externalAddress(), evm = "0x00000000219ab540356cBB839Cbe05303d7705Fa", solana = solanaStranger().base58, tron = tronStranger().base58390        func refusal(_ text: String, _ chain: ChainID) async -> AddressRefusal? {391            if case .address(let r)? = await walletError({ try await h.service.checkAddress(text, chain: chain) }) { return r }392            return nil393        }394        // an EVM address pasted on TRON, and the other crossings395        #expect(await refusal(evm, .tronNile) == .wrongFamily(chain: "TRON", found: "an Ethereum (EVM)"))396        #expect(await refusal(tron, .ethereumSepolia) == .wrongFamily(chain: "Ethereum Sepolia", found: "a TRON"))397        #expect(await refusal(tron, .solanaDevnet) == .wrongFamily(chain: "Solana", found: "a TRON"))398        #expect(await refusal(solana, .tronNile) == .wrongFamily(chain: "TRON", found: "a Solana"))399        #expect(await refusal(bitcoin, .solanaDevnet) == .wrongFamily(chain: "Solana", found: "a Bitcoin"))400        #expect(await refusal(evm, .bitcoinSignet) == .wrongFamily(chain: "Bitcoin", found: "an Ethereum (EVM)"))401        #expect(await refusal(solana, .bitcoinSignet) == .wrongFamily(chain: "Bitcoin", found: "a Solana"))402        // the right family, wrong in itself403        #expect(await refusal("", .tronNile) == .empty)404        #expect(await refusal(String(tron.dropLast()) + (tron.hasSuffix("a") ? "b" : "a"), .tronNile) == .invalidChecksum(chain: "TRON"))405        #expect(await refusal("0x00000000219ab540356cBB839Cbe05303d7705fa", .ethereumSepolia) == .invalidChecksum(chain: "Ethereum Sepolia"))406        #expect(await refusal("0x" + String(repeating: "0", count: 40), .ethereumSepolia) == .zeroAddress)407        #expect(await refusal("bc1qw508d5qgjfc7ghfdsg8tm9r4ljtrcpa7xnxnxn", .bitcoinSignet) != nil)408        #expect(await refusal("bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdq", .bitcoinSignet) == .wrongNetwork(chain: "Bitcoin Signet", found: "Bitcoin"))409        guard case .unsupported? = await refusal(TronAddress(tron)!.hex, .tronNile), case .unsupported? = await refusal(SolanaProgram.token.base58, .solanaDevnet),410              case .malformed? = await refusal("hello", .solanaDevnet) else {411            Issue.record("precise refusals expected")412            return413        }414        // every refusal has a sentence that names both chains415        #expect(WalletError.address(.wrongFamily(chain: "TRON", found: "an Ethereum (EVM)")).userMessage.contains("an Ethereum (EVM) address, not a TRON address"))416        // accepted addresses come back in canonical form, with what to know417        let ok = try await h.service.checkAddress(evm.lowercased(), chain: .ethereumSepolia)418        #expect(ok.canonical == evm && !ok.isOwnAddress && ok.notes.count == 1)419        #expect(try await h.service.checkAddress(MultiHarness.solanaAddress, chain: .solanaDevnet).isOwnAddress)420        #expect(try await h.service.checkAddress(" \(MultiHarness.tronAddress)\n", chain: .tronNile).isOwnAddress)421        #expect(try await h.service.checkAddress(Harness.abandonFirstTestAddress, chain: .bitcoinSignet).isOwnAddress)422        // the same refusals stop a payment before any request423        #expect(await walletError { try await h.service.prepareSend(chain: .tronNile, asset: .native, to: evm, amount: UInt256(1)) }424            == .address(.wrongFamily(chain: "TRON", found: "an Ethereum (EVM)")))425        #expect(await walletError { try await h.service.prepareSend(chain: .solanaDevnet, asset: .native, to: tron, amount: UInt256(1)) }426            == .address(.wrongFamily(chain: "Solana", found: "a TRON")))427        #expect(h.backend.requests.isEmpty)428    }429430    @Test func watchOnlyWalletsTakeTheAddressesOfEveryFamily() async throws {431        let cold = try await MultiHarness.wallet(chains: [.bitcoin, .ethereum, .solana, .tron])432        defer { cold.cleanup() }433        let package = try await cold.service.exportWatchOnlyPackage()434        let decoded = try JSONDecoder().decode(WatchOnlyPackage.self, from: Data(package.text.utf8))435        #expect(decoded.version == 2 && decoded.solanaAddress == MultiHarness.solanaAddress && decoded.tronAddress == MultiHarness.tronAddress)436437        let online = try await MultiHarness.make()438        defer { online.cleanup() }439        try await online.service.importWatchOnly(package: package.frames)440        var profile = await online.service.currentProfile()441        #expect(profile.kind == .watchOnly && profile.solanaAddress == MultiHarness.solanaAddress && profile.tronAddress == MultiHarness.tronAddress)442        #expect(profile.ethereumAddress?.checksummed == MultiHarness.ethereumAddress && profile.enabledChains == [.bitcoin, .ethereum, .solana, .tron])443        #expect(await online.service.vaultStatus().exists == false)444445        // a package of version 1 (Bitcoin and Ethereum only) is still accepted446        var object = try #require(try JSONSerialization.jsonObject(with: Data(package.text.utf8)) as? [String: Any])447        object["version"] = 1448        object["solanaAddress"] = nil449        object["tronAddress"] = nil450        object["accounts"] = nil451        object["enabledChains"] = nil452        let legacy = try await MultiHarness.make()453        defer { legacy.cleanup() }454        try await legacy.service.importWatchOnly(package: [String(decoding: try JSONSerialization.data(withJSONObject: object), as: UTF8.self)])455        profile = await legacy.service.currentProfile()456        #expect(profile.solanaAddress == nil && profile.tronAddress == nil && profile.enabledChains == [.bitcoin, .ethereum])457        // it has no account for the other families and says so458        #expect(await walletError { try await legacy.service.setChainEnabled(.solana, enabled: true) }459            == .featureUnavailable("This watch-only wallet has no account for Solana."))460461        // addresses alone462        let single = try await MultiHarness.make()463        defer { single.cleanup() }464        try await single.service.importWatchOnly(bitcoinExtendedPublicKey: nil, ethereumAddress: nil, solanaAddress: MultiHarness.solanaAddress)465        #expect(await single.service.currentProfile().enabledChains == [.solana])466        #expect(await single.service.snapshot().chains.map(\.id) == [.solanaDevnet])467        let other = try await MultiHarness.make()468        defer { other.cleanup() }469        #expect(await walletError { try await other.service.importWatchOnly(bitcoinExtendedPublicKey: nil, ethereumAddress: nil, tronAddress: MultiHarness.ethereumAddress) }470            == .address(.wrongFamily(chain: "TRON", found: "an Ethereum (EVM)")))471        #expect(await other.service.currentProfile().kind == nil)472    }473474    @Test func pricesAndValuationCoverEveryChain() async throws {475        let h = try await MultiHarness.wallet(chains: [.bitcoin, .ethereum, .polygon, .solana, .tron])476        defer { h.cleanup() }477        #expect(await h.service.priceIDs() == ["bitcoin", "ethereum", "polygon-ecosystem-token", "solana", "tron"])478        h.backend.base.markets = ServiceTests.market([("bitcoin", "50000"), ("ethereum", "2000"), ("polygon-ecosystem-token", "0.5"), ("solana", "100"), ("tron", "0.25")])479        h.backend.solana.lamports[MultiHarness.solanaAddress] = 3_000_000_000480        h.backend.tron.balances[MultiHarness.tronHex(MultiHarness.tronAddress)] = 40_000_000481        h.backend.evm(.polygonAmoy).balances[MultiHarness.ethereumAddress.lowercased()] = UInt256(2_000_000_000_000_000_000)482        _ = await h.service.synchronize()483        try await h.service.refreshMarket()484        // one batched request for every identifier485        #expect(h.backend.requests.filter { $0.contains("prices.test") }.count == 1)486        let valuation = await h.service.portfolioValuation()487        // test networks: a reference value at the prices of the main networks, never real money488        #expect(valuation.realValue == nil && valuation.isTestNetwork && valuation.referenceValue == 300 + 10 + 1)489        let chains = Dictionary(uniqueKeysWithValues: valuation.chains.map { ($0.chain, $0) })490        #expect(chains[.solanaDevnet]?.referenceValue == 300 && chains[.tronNile]?.referenceValue == 10 && chains[.polygonAmoy]?.referenceValue == 1)491        #expect(valuation.chains.allSatisfy { $0.realValue == nil })492        #expect(valuation.lines.map(\.id).prefix(2) == ["btc", "eth"] && valuation.lines.first { $0.chain == .solanaDevnet }?.amount == "3")493        // without a quote a holding is listed as unpriced, never valued at zero494        h.backend.base.markets = ServiceTests.market([("bitcoin", "50000")])495        let fresh = try await MultiHarness.wallet(chains: [.solana], backend: h.backend)496        defer { fresh.cleanup() }497        _ = await fresh.service.synchronize()498        try await fresh.service.refreshMarket()499        let partial = await fresh.service.portfolioValuation()500        #expect(partial.unpricedAssets == ["SOL"] && partial.referenceValue == nil && partial.lines.first?.referenceValue == nil)501    }502503    @Test func theShieldCoversEveryFamily() async throws {504        let h = try await MultiHarness.wallet(chains: [.ethereum, .polygon, .optimism, .solana, .tron])505        defer { h.cleanup() }506        let owner = MultiHarness.ethereumAddress.lowercased()507        // before any synchronization nothing is assumed508        var shield = await h.service.shieldReport()509        var accounts = Dictionary(uniqueKeysWithValues: shield.report.keyExposure.accounts.map { ($0.family, $0) })510        #expect(accounts[.evm]?.publicKeyExposed == nil && accounts[.evm]?.unmeasuredNetworks.count == 3)511        #expect(accounts[.tron]?.publicKeyExposed == nil && shield.report.keyExposure.isPartlyUnmeasured)512        // Solana needs no measurement: the address is the key513        #expect(accounts[.solana]?.publicKeyExposed == true && accounts[.solana]?.unmeasuredNetworks.isEmpty == true)514        #expect(accounts[.solana]?.findings.map(\.id) == ["sol.exposure.address-is-key"] && accounts[.solana]?.findings.first?.severity == .info)515516        // the EVM key was used on Amoy only; OP Sepolia does not answer517        h.backend.evm(.polygonAmoy).latestNonce[owner] = 2518        h.backend.silentHosts = ["optimismSepolia.evm.test"]519        h.backend.solana.lamports[MultiHarness.solanaAddress] = 1_000_000_000520        h.backend.tron.balances[MultiHarness.tronHex(MultiHarness.tronAddress)] = 1_000_000521        h.backend.tron.resources = #"{"freeNetLimit":600,"freeNetUsed":269}"#522        _ = await h.service.synchronize()523        shield = await h.service.shieldReport()524        accounts = Dictionary(uniqueKeysWithValues: shield.report.keyExposure.accounts.map { ($0.family, $0) })525        let evm = try #require(accounts[.evm])526        // one key for every EVM network: used on one, public on all; the network that was not measured is named527        #expect(evm.publicKeyExposed == true && evm.unmeasuredNetworks == ["OP Sepolia"])528        #expect(evm.networks.map(\.publicKeyExposed) == [false, nil, true] && evm.networks.last?.evidence == "account nonce 2")529        // (OP Sepolia has a history source and was not read: its approvals are reported as not measured)530        #expect(Set(evm.findings.map(\.id)) == ["evm.exposure.revealed", "evm.exposure.unmeasured", "evm.approvals.unknown.optimismsepolia"])531        #expect(evm.findings.first { $0.id == "evm.exposure.revealed" }?.detail.contains("every EVM network") == true)532        // Sepolia alone shows no transaction, and the 1.0 part of the section still says so for that network533        #expect(shield.report.keyExposure.ethereum?.publicKeyRecoverable == false)534        // but the migration plan follows the key, not one network535        #expect(shield.report.migrationFigures.ethereumKeyExposed && shield.migrationPlan.steps.contains { $0.id == "rotate-eth" })536        #expect(accounts[.solana]?.findings.first?.severity == .warning)537        // TRON has no nonce: bandwidth already used is the trace of a transaction sent538        #expect(accounts[.tron]?.publicKeyExposed == true && shield.report.migrationFigures.tronKeyExposed)539        #expect(shield.migrationPlan.steps.map(\.id).contains("rotate-trx") && shield.migrationPlan.steps.map(\.id).suffix(2) == ["sol-pq", "trx-pq"])540        #expect(shield.migrationPlan.blocked.map(\.id).contains("sol-pq") && shield.migrationPlan.blocked.map(\.id).contains("trx-pq"))541        // section 3 lists every enabled chain with its signature scheme, the primary Bitcoin network first as before542        let networks = shield.report.networkResistance.chains543        #expect(networks.map(\.networkName) == ["Bitcoin Signet", "Ethereum Sepolia", "OP Sepolia", "Polygon Amoy", "Solana Devnet", "TRON Nile"])544        #expect(networks.map(\.chain) == [.bitcoin, .ethereum, .optimism, .polygon, .solana, .tron])545        #expect(networks.map(\.chain.kind) == [.bitcoin, .ethereum, .ethereum, .ethereum, .solana, .tron])546        #expect(networks[4].signatureSchemes == ["Ed25519"] && networks[5].signatureSchemes == ["secp256k1 ECDSA"])547        #expect(networks.allSatisfy { !$0.offersQuantumResistance } && Set(networks.map(\.id)).count == networks.count)548        #expect(Set(shield.report.networkResistance.findings.map(\.id)).count == networks.count)549        #expect(shield.additionalDisclaimer == QuantumShield.multiChainDisclaimer && shield.measuredAt[.solanaDevnet] != nil && shield.measuredAt[.optimismSepolia] == nil)550        // the three sections stay separate: there is still no overall score to read551        #expect(shield.report.keyExposure.level == .attention && shield.report.networkResistance.findings.allSatisfy { $0.severity == .info })552    }553554    @Test func hostileAnswersNeverCrashTheNewFamilies() async throws {555        let h = try await MultiHarness.wallet(chains: [.solana, .tron])556        defer { h.cleanup() }557        h.backend.solana.lamports[MultiHarness.solanaAddress] = 1_000_000_000558        h.backend.tron.balances[MultiHarness.tronHex(MultiHarness.tronAddress)] = 1_000_000559        let hostile = ["null", "{}", "[]", "\"x\"", "-1", "1e400", "{\"value\":null}", "{\"value\":-5}", "{\"value\":\"18446744073709551616\"}",560                       "{\"value\":[{\"account\":null,\"pubkey\":5}]}", "18446744073709551616", "[{\"signature\":7}]", "{\"value\":{\"blockhash\":\"\",\"lastValidBlockHeight\":-1}}"]561        for method in ["getSlot", "getBalance", "getTokenAccountsByOwner", "getMinimumBalanceForRentExemption", "getSignaturesForAddress", "getLatestBlockhash",562                       "getAccountInfo", "simulateTransaction", "getRecentPrioritizationFees"] {563            for answer in hostile {564                h.backend.solana.resultOverride = [method: answer]565                _ = await h.service.synchronize(chains: [.solanaDevnet])566                _ = try? await h.service.prepareSend(chain: .solanaDevnet, asset: .native, to: solanaStranger().base58, amount: UInt256(5_000_000))567            }568        }569        h.backend.solana.resultOverride = [:]570        // rent figures beyond anything plausible are an untrusted answer, not a balance571        h.backend.solana.rent[0] = 50_000_000_000572        #expect(await walletError { try await h.service.synchronize(chain: .solanaDevnet) } == .untrustedResponse("rent minimums out of range"))573        h.backend.solana.rent[0] = 890_880574        #expect(await h.service.synchronize(chains: [.solanaDevnet]).first?.succeeded == true)575576        let me = MultiHarness.tronHex(MultiHarness.tronAddress)577        for answer in ["[]", "null", "{\"address\":5}", "{\"address\":\"\(me)\",\"balance\":-1}", "{\"address\":\"\(me)\",\"balance\":18446744073709551615}",578                       "{\"address\":\"41\(String(repeating: "22", count: 20))\",\"balance\":1}", "{\"chainParameter\":7}", "{\"freeNetLimit\":\"many\"}", "{\"blockID\":\"zz\"}"] {579            for path in ["getaccount", "getaccountresource", "getchainparameters", "getblock"] {580                switch path {581                case "getaccountresource": h.backend.tron.resources = answer582                case "getchainparameters": h.backend.tron.parameters = answer583                default: break584                }585                _ = await h.service.synchronize(chains: [.tronNile])586                _ = try? await h.service.prepareSend(chain: .tronNile, asset: .native, to: tronStranger().base58, amount: UInt256(1_000_000))587            }588        }589        // a chain whose parameters make a plain transfer cost a fortune is not believed590        h.backend.tron.resources = #"{"freeNetLimit":600,"freeNetUsed":0}"#591        h.backend.tron.parameters = #"{"chainParameter":[{"key":"getCreateAccountFee","value":100000},{"key":"getTransactionFee","value":1000},{"key":"getCreateNewAccountFeeInSystemContract","value":900000000000},{"key":"getCreateNewAccountBandwidthRate","value":1},{"key":"getEnergyFee","value":100},{"key":"getMaxFeeLimit","value":15000000000}]}"#592        h.backend.tron.balances[me] = 2_000_000_000_000593        guard case .untrustedResponse? = await walletError({ try await h.service.prepareSend(chain: .tronNile, asset: .native, to: tronStranger().base58, amount: UInt256(1_000_000)) }) else {594            Issue.record("absurd chain parameters must be refused")595            return596        }597    }598}599
Files main
Menu

Theme