SPB Git

Repository Public

IntegrationFixTests.swift 24.5 KB 390 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Tests/QyvoraWalletTests/IntegrationFixTests.swift8// Module           : Tests9// Repository       : https://git.spboucher.ai/qyvora10// Project Website  : Not specified11// Created          : 2026-12-0412// Last Modified    : 2026-12-0413//14// Author           : Simon-Pierre Boucher15// Position         : Professor of Finance16// Institution      : Université du Québec en Outaouais (UQO)17// Organization     : SP Boucher18// Website          : https://spboucher.ai19// Git              : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development      : dev@spboucher.ai23// Support          : support@spboucher.ai24// Security/Admin   : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License          : None specified (no license file in this repository)33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import Foundation42import Testing43import QyvoraMath44import QyvoraCore45import QyvoraBitcoin46import QyvoraEthereum47import QyvoraNetworking48import QyvoraStorage49import QyvoraVault50import QyvoraQuantumShield51@testable import QyvoraWallet5253/// Regression tests of the integration gaps reported by the interface before build 2: the service must keep its54/// snapshots in step with what the user just changed, and say what it does not know.55@Suite(.readsMainnetPolicy) struct SnapshotConsistencyTests {56    /// A label set after a synchronization shows on the addresses and coins of the snapshot at once.57    @Test func addressLabelReachesTheBitcoinSnapshot() async throws {58        let s = try await BitcoinWalletTests.scenario()59        defer { s.h.cleanup() }60        let before = try await s.h.service.syncBitcoin()61        #expect(before.addresses.allSatisfy { $0.label == nil })62        let requests = s.h.backend.requests.count6364        try await s.h.service.setAddressLabel("Savings", for: s.a0)65        let labelled = try #require(await s.h.service.latestBitcoinSnapshot())66        #expect(labelled.addresses.first { $0.address == s.a0 }?.label == "Savings")67        #expect(labelled.reusedAddresses.first { $0.address == s.a0 }?.label == "Savings")68        #expect(labelled.utxos.filter { $0.address == s.a0 }.allSatisfy { $0.label == "Savings" })69        #expect(labelled.utxos.contains { $0.address == s.a0 })70        #expect(labelled.addresses.filter { $0.address != s.a0 }.allSatisfy { $0.label == nil })71        // nothing else moved, and no request was needed72        #expect(labelled.balance == before.balance && labelled.transactions == before.transactions && labelled.synchronizedAt == before.synchronizedAt)73        #expect(s.h.backend.requests.count == requests)74        guard case .available(let inDashboard) = await s.h.service.snapshot().bitcoin else {75            Issue.record("the dashboard snapshot should hold the Bitcoin state")76            return77        }78        #expect(inDashboard == labelled)7980        // the label of the next receive address too81        try await s.h.service.setAddressLabel("Next", for: before.receiveAddress.address)82        #expect(await s.h.service.latestBitcoinSnapshot()?.receiveAddress.label == "Next")83        try await s.h.service.setAddressLabel("  ", for: s.a0)84        #expect(await s.h.service.latestBitcoinSnapshot()?.addresses.first { $0.address == s.a0 }?.label == nil)85    }8687    /// Adding, hiding, showing and removing a token changes the Ethereum snapshot without waiting for a synchronization.88    @Test func tokenListChangesReachTheEthereumSnapshot() async throws {89        let h = try await EthereumWalletTests.funded()90        defer { h.cleanup() }91        let first = try await h.service.syncEthereum()92        #expect(!first.tokens.contains { $0.token.address == EthereumAddress(EthereumWalletTests.usdc) && $0.token.custom })93        let builtIn = first.tokens9495        // added: in the snapshot with the balance read on chain at that moment96        let other = "0x" + String(repeating: "e5", count: 20)97        var contract = FakeBackend.TokenContract(symbol: "OTH", name: "Other", decimals: UInt256(8))98        contract.balances[EthereumWalletTests.owner] = UInt256(1_234)99        h.backend.tokens[other] = contract100        let token = try await h.service.addCustomToken(address: other)101        var snapshot = try #require(await h.service.latestEthereumSnapshot())102        #expect(snapshot.tokens == builtIn + [TokenBalance(token: token, balance: .available(UInt256(1_234)))])103        #expect(snapshot.synchronizedAt == first.synchronizedAt && snapshot.balance == first.balance)104105        // hidden: gone at once; shown again: back, with a balance that says it has not been read106        try await h.service.setTokenHidden(true, token: token)107        snapshot = try #require(await h.service.latestEthereumSnapshot())108        #expect(snapshot.tokens == builtIn)109        try await h.service.setTokenHidden(false, token: token)110        snapshot = try #require(await h.service.latestEthereumSnapshot())111        #expect(snapshot.tokens == builtIn + [TokenBalance(token: token, balance: .notLoaded)])112        #expect(try await h.service.syncEthereum().tokens.last == TokenBalance(token: token, balance: .available(UInt256(1_234))))113114        // adding a hidden token again shows it again, without network115        try await h.service.setTokenHidden(true, token: token)116        let requests = h.backend.requests.count117        _ = try await h.service.addCustomToken(address: other)118        #expect(h.backend.requests.count == requests)119        #expect(await h.service.latestEthereumSnapshot()?.tokens.map(\.token).contains(token) == true)120121        // removed: gone at once, and from the valuation lines too122        try await h.service.removeCustomToken(token)123        snapshot = try #require(await h.service.latestEthereumSnapshot())124        #expect(snapshot.tokens == builtIn)125        #expect(await h.service.portfolioValuation().lines.contains { $0.id == token.id } == false)126        guard case .available(let inDashboard) = await h.service.snapshot().ethereum else {127            Issue.record("the dashboard snapshot should hold the Ethereum state")128            return129        }130        #expect(inDashboard == snapshot)131132        // a built-in token can be hidden and shown as well133        if let usdc = builtIn.first {134            try await h.service.setTokenHidden(true, token: usdc.token)135            #expect(await h.service.latestEthereumSnapshot()?.tokens.contains { $0.token == usdc.token } == false)136            try await h.service.setTokenHidden(false, token: usdc.token)137            #expect(await h.service.latestEthereumSnapshot()?.tokens.first == TokenBalance(token: usdc.token, balance: .notLoaded))138        }139140        // before any synchronization there is no snapshot to edit, and none is invented141        let fresh = try await EthereumWalletTests.funded()142        defer { fresh.cleanup() }143        fresh.backend.tokens[other] = contract144        _ = try await fresh.service.addCustomToken(address: other)145        #expect(await fresh.service.latestEthereumSnapshot() == nil)146    }147}148149/// Every error the service can throw has a plain English sentence, and the sentence kept in the snapshot for a failed150/// synchronization says what failed.151@Suite(.readsMainnetPolicy) struct ErrorMessageTests {152    /// What a raw Swift value looks like when it leaks into a message: `invalidInput("…")`, `http(status: 429, …)`,153    /// `Optional(…)`, a type name.154    static func looksRaw(_ text: String) -> Bool {155        // an identifier glued to an opening parenthesis ("transaction(s)" is the one legitimate form)156        if text.range(of: #"[A-Za-z]\((?!s\))"#, options: .regularExpression) != nil { return true }157        if text.range(of: #"Qyvora[A-Z][A-Za-z]+\."#, options: .regularExpression) != nil { return true }158        return ["NSURLError", "URLError", "NSError", "Swift.", "Error Domain", " nil"].contains { text.contains($0) }159    }160161    @Test func everyErrorHasASentence() throws {162        let outPoint = try #require(BitcoinOutPoint(txid: String(repeating: "ab", count: 32), vout: 1))163        let date = Date(timeIntervalSince1970: 1_800_000_000)164        let refusals: [EthereumRefusal] = [165            .pendingTransaction(latestNonce: 3, pendingNonce: 4), .invalidAddress, .zeroAddress, .recipientIsTokenContract, .recipientIsContract,166            .tokenContractMissing, .zeroAmount, .insufficientBalance(available: UInt256(1), required: UInt256(2)),167            .insufficientFundsForFee(available: UInt256(1), required: UInt256(2)), .gasLimitTooHigh(estimated: 300_000, limit: 200_000),168            .simulationFailed("execution reverted"), .unexpectedTokenReturn, .feeOutOfRange, .tokenNetworkMismatch,169            .chainMismatch(expected: 11_155_111, found: 1), .foreignSender, .unsupportedTransaction("contract creation"),170        ]171        let builds: [BitcoinBuildError] = [172            .noRecipients, .dustOutput(index: 0), .invalidAmount, .duplicateUTXO, .requiredInputUnavailable(outPoint), .unknownInputSize(outPoint),173            .insufficientFunds(available: 10, required: 20), .changeScriptRequired, .sendMaxBelowDust, .feeRateOutOfRange,174            .feeExceedsCap(fee: 2_000_000, cap: 1_000_000), .absurdFee(fee: 9_000, expected: 200), .transactionTooLarge,175        ]176        let vaults: [VaultError] = [177            .notFound, .alreadyExists, .locked, .wrongPassword, .wrongPIN(retryAllowedAt: nil), .wrongPIN(retryAllowedAt: date), .pinLocked(until: date),178            .wiped, .pinNotEnabled, .deviceSlotNotEnabled, .deviceAuthenticationFailed, .deviceKeyUnavailable, .secureEnclaveUnavailable,179            .corrupted(.truncated), .corrupted(.badMagic), .corrupted(.unsupportedVersion(9)), .corrupted(.checksumMismatch), .corrupted(.malformed),180            .integrityFailure, .recordNotFound, .invalidParameters, .kdfFailure, .selfTestFailed,181            .storage(.notFound), .storage(.invalidName), .storage(.io(operation: "rename", code: 13)), .storage(.keychain(status: -25_300)),182            .storage(.authenticationFailed), .storage(.interactionNotAllowed), .storage(.secureEnclaveUnavailable), .storage(.invalidData),183        ]184        var wallets: [WalletError] = [185            .mainnetDisabled(WalletError.mainnetText), .noWallet, .walletAlreadyExists, .watchOnly, .vaultLocked, .wrongPassword,186            .wrongPIN(retryAllowedAt: nil), .wrongPIN(retryAllowedAt: date), .pinLocked(until: date, remaining: 42), .pinLocked(until: date, remaining: 5_000),187            .biometricUnavailable("This device has no Secure Enclave."), .vaultWiped, .invalidRecoveryPhrase("Word 3 is not in the BIP-39 word list."),188            .invalidInput("The backup password is empty."), .invalidAddress("This is not a Bitcoin Signet address."), .offline,189            .network("mempool.space: HTTP 429 (too many requests)"), .wrongChain("esplora.test serves another chain than Bitcoin Signet"),190            .untrustedResponse("tip height"), .notSynchronized("Synchronize the Bitcoin account before preparing a payment."),191            .stalePlan("the active network changed"), .signingFailed("the key does not match the account"),192            .broadcastMismatch(local: "aa", remote: "bb"), .invalidPSBT("It is not a PSBT."), .invalidPayload("This is not a QYVORA backup file."),193            .storage("the wallet profile cannot be read"), .featureUnavailable("No identity has been created."),194            .exceedsUnauditedLimit(limit: "0.002 BTC per transaction"), .unauditedLimitUnverifiable("No fresh price for this token."),195        ]196        wallets += refusals.map { .ethereum($0) } + builds.map { .bitcoinBuild($0) } + vaults.map { .vault($0) }197        // what the lower layers throw, as the service converts it198        let lower: [any Error] = [199            StorageError.io(operation: "read", code: 5), StorageError.invalidData, PSBTError.invalidMagic, PSBTError.notEnoughSignatures,200            PSBTError.unsupportedVersion(2), BIP39.Error.unknownWord(position: 2), BIP39.Error.invalidChecksum, BIP39.Error.invalidWordCount,201            NetworkError.http(status: 429, body: "Too Many Requests"), NetworkError.http(status: 503, body: ""), NetworkError.invalidURL,202            NetworkError.rpc(code: -32_000, message: "header not found"), NetworkError.invalidResponse("eth_getBalance"),203            NetworkError.disagreement("rpc.test and rpc2.test differ"), NetworkError.offline,204            NetworkError.allEndpointsFailed(["mempool.space: \(NetworkError.http(status: 429, body: "x").summary)", "blockstream.info: \(NetworkError.transportSummary(URLError(.timedOut)))"]),205            URLError(.notConnectedToInternet), URLError(.cannotFindHost), URLError(.dnsLookupFailed), URLError(.timedOut), URLError(.cannotConnectToHost),206            URLError(.networkConnectionLost), URLError(.secureConnectionFailed), URLError(.badServerResponse), URLError(.unknown), CancellationError(),207            VaultError.kdfFailure, EthereumRefusal.zeroAmount, BitcoinBuildError.transactionTooLarge,208        ]209        wallets += lower.map { WalletError.wrap($0, now: date) }210211        for error in wallets {212            let message = error.userMessage213            #expect(message.count >= 10, "too short for \(error): \(message)")214            #expect(!Self.looksRaw(message), "raw value in the message of \(error): \(message)")215            #expect(message.first?.isUppercase == true || message.first?.isNumber == true, "not a sentence: \(message)")216            #expect(WalletMessages.text(for: error) == message)217            // the sentence kept in the snapshot is the same one218            #expect(WalletService.describe(error) == message)219        }220        for error in lower {221            #expect(!Self.looksRaw(WalletMessages.text(for: error)), "raw value for \(error): \(WalletMessages.text(for: error))")222        }223        #expect(refusals.allSatisfy { !Self.looksRaw($0.userMessage) } && builds.allSatisfy { !Self.looksRaw($0.userMessage) })224        #expect(vaults.allSatisfy { !Self.looksRaw($0.userMessage) })225226        // the detector itself recognises what used to be shown227        #expect(Self.looksRaw("invalidInput(\"address\")") && Self.looksRaw("Network error: NSURLError") && Self.looksRaw("http(status: 429, body: \"x\")"))228        #expect(Self.looksRaw("Vault error: corrupted(QyvoraVault.VaultError.Corruption.truncated).") && Self.looksRaw("dustOutput(index: 0)"))229    }230231    @Test func aDeviceWithoutConnectionIsNotReportedAsColdMode() {232        // no connection, a name that does not resolve, a timeout: a network failure with its reason233        guard case .network(let offline) = WalletError.wrap(URLError(.notConnectedToInternet)) else {234            Issue.record("a device without connection must be a network error")235            return236        }237        #expect(offline == "this device is not connected to the Internet")238        #expect(WalletError.wrap(URLError(.cannotFindHost)) == .network("the server name could not be resolved (DNS)"))239        #expect(WalletError.wrap(URLError(.timedOut)) == .network("the server did not answer in time"))240        // every endpoint unreachable because the device is offline: still not cold mode241        let unreachable = NetworkError.allEndpointsFailed(["mempool.space: \(NetworkError.transportSummary(URLError(.notConnectedToInternet)))",242                                                           "blockstream.info: \(NetworkError.transportSummary(URLError(.notConnectedToInternet)))"])243        guard case .network(let text) = WalletError.from(unreachable) else {244            Issue.record("an offline device must not be reported as cold mode")245            return246        }247        #expect(text.contains("mempool.space") && text.contains("blockstream.info") && text.contains("not connected to the Internet"))248        // cold mode stays cold mode249        #expect(WalletError.from(.offline) == .offline)250        #expect(WalletError.from(.allEndpointsFailed(["a.test: \(NetworkError.offline.summary)", "b.test: \(NetworkError.offline.summary)"])) == .offline)251        // HTTP failures keep their status, with what it means252        #expect(WalletError.from(.http(status: 429, body: "")) == .network("HTTP 429 (too many requests)"))253        #expect(WalletError.from(.http(status: 503, body: "")) == .network("HTTP 503 (server error)"))254    }255256    /// The very first synchronization fails: the snapshot says why for each chain, in `bitcoinSyncError` /257    /// `ethereumSyncError` as well as in the chain's state.258    @Test func aFailedFirstSynchronizationIsReportedInTheSnapshot() async throws {259        let h = try await Harness.abandonWallet()260        defer { h.cleanup() }261        var dashboard = await h.service.snapshot()262        #expect(dashboard.bitcoin == .notLoaded && dashboard.ethereum == .notLoaded)263        #expect(dashboard.bitcoinSyncError == nil && dashboard.ethereumSyncError == nil)264265        // hosts that do not resolve (the fake transport throws URLError.cannotFindHost for unknown hosts)266        try await h.service.setEndpoints(FakeBackend.endpoints.with {267            $0.esplora["signet"] = ["https://nowhere.test/api"]268            $0.ethereumRPC["sepolia"] = ["https://nowhere-rpc.test"]269        })270        guard case .network(let bitcoinText)? = await walletError({ try await h.service.syncBitcoin() }),271              case .network(let ethereumText)? = await walletError({ try await h.service.syncEthereum() }) else {272            Issue.record("expected network errors")273            return274        }275        #expect(bitcoinText.contains("nowhere.test") && bitcoinText.contains("DNS") && !Self.looksRaw(bitcoinText))276        #expect(ethereumText.contains("nowhere-rpc.test") && ethereumText.contains("DNS") && !Self.looksRaw(ethereumText))277278        dashboard = await h.service.snapshot()279        let bitcoinError = try #require(dashboard.bitcoinSyncError), ethereumError = try #require(dashboard.ethereumSyncError)280        #expect(bitcoinError.contains("nowhere.test") && bitcoinError.contains("could not be resolved"))281        #expect(ethereumError.contains("nowhere-rpc.test") && ethereumError.contains("could not be resolved"))282        #expect(dashboard.bitcoin == .unavailable(reason: bitcoinError) && dashboard.ethereum == .unavailable(reason: ethereumError))283        #expect(!dashboard.isSynchronizingBitcoin && !dashboard.isSynchronizingEthereum)284285        // a later success clears the error286        try await h.service.setEndpoints(FakeBackend.endpoints)287        _ = try await h.service.syncBitcoin()288        _ = try await h.service.syncEthereum()289        dashboard = await h.service.snapshot()290        #expect(dashboard.bitcoinSyncError == nil && dashboard.ethereumSyncError == nil)291        #expect(dashboard.bitcoin.value != nil && dashboard.ethereum.value != nil)292293        // and a failure after a success keeps the older snapshot, with the error next to it294        h.backend.overrides = [(match: "GET esplora.test/api/blocks/tip/height", status: 503, body: "down")]295        _ = await walletError { try await h.service.syncBitcoin() }296        dashboard = await h.service.snapshot()297        #expect(dashboard.bitcoin.value != nil)298        #expect(dashboard.bitcoinSyncError?.contains("HTTP 503") == true && dashboard.bitcoinSyncError?.contains("esplora.test") == true)299    }300}301302/// Two honest JSON-RPC endpoints are not at the same block: on a busy account their transaction counts differ by a few303/// at the same instant. Reading tolerates a small window; preparing a transaction requires exact agreement.304@Suite(.readsMainnetPolicy) struct NonceCrossCheckTests {305    static let twoEndpoints = FakeBackend.endpoints.with { $0.ethereumRPC["sepolia"] = ["https://rpc.test", "https://rpc2.test"] }306307    static func busyAccount() async throws -> Harness {308        let h = try await EthereumWalletTests.funded()309        try await h.service.setEndpoints(twoEndpoints)310        return h311    }312313    @Test func synchronizationAcceptsEndpointsAFewTransactionsApart() async throws {314        let h = try await Self.busyAccount()315        defer { h.cleanup() }316        // in step: no remark317        var snapshot = try await h.service.syncEthereum()318        #expect(snapshot.latestNonce == 3 && snapshot.pendingNonce == 3 && snapshot.notes.isEmpty)319320        // the second endpoint is three transactions ahead: the highest count is shown, and the snapshot says so321        h.backend.secondEndpointNonceLead = 3322        snapshot = try await h.service.syncEthereum()323        #expect(snapshot.latestNonce == 6 && snapshot.pendingNonce == 6 && !snapshot.hasPendingTransaction)324        #expect(snapshot.notes.count == 2)325        #expect(snapshot.notes.allSatisfy { $0.contains("3 transaction(s) apart") && $0.contains("rpc.test: 3") && $0.contains("rpc2.test: 6") })326        // the Shield reads the same figure327        #expect(await h.service.shieldReport().report.keyExposure.ethereum?.outgoingTransactionCount == 6)328329        // exactly at the window: still accepted330        h.backend.secondEndpointNonceLead = WalletService.nonceReadWindow331        #expect(try await h.service.syncEthereum().latestNonce == 3 + WalletService.nonceReadWindow)332333        // beyond the window this is not lag: refused, and the previous snapshot stays334        h.backend.secondEndpointNonceLead = WalletService.nonceReadWindow + 1335        guard case .untrustedResponse(let text)? = await walletError({ try await h.service.syncEthereum() }) else {336            Issue.record("a difference beyond the window must be refused")337            return338        }339        #expect(text.contains("disagree") && text.contains("rpc2.test: \(3 + WalletService.nonceReadWindow + 1)"))340        #expect(await h.service.latestEthereumSnapshot()?.latestNonce == 3 + WalletService.nonceReadWindow)341        let dashboard = await h.service.snapshot()342        #expect(dashboard.ethereumSyncError?.contains("disagree") == true)343344        // one endpoint down: the other one answers alone345        h.backend.secondEndpointNonceLead = 0346        h.backend.overrides = [(match: "POST rpc2.test", status: 503, body: "down")]347        #expect(try await h.service.syncEthereum().latestNonce == 3)348    }349350    @Test func preparingASendRequiresExactAgreement() async throws {351        let h = try await Self.busyAccount()352        defer { h.cleanup() }353        let amount = UInt256(1_000_000_000_000_000)354        func secondEndpointCalls() -> Int { h.backend.requests.filter { $0 == "POST rpc2.test" }.count }355        _ = try await h.service.syncEthereum()   // the chain identity of both endpoints is checked here356357        // persistent difference: one retry, then refusal — nothing is prepared358        h.backend.secondEndpointNonceLead = 1359        var before = secondEndpointCalls()360        guard case .untrustedResponse(let text)? = await walletError({361            try await h.service.prepareEthereumSend(asset: .ether, to: EthereumWalletTests.recipient, amount: amount)362        }) else {363            Issue.record("a nonce the endpoints do not agree on must be refused")364            return365        }366        #expect(text.contains("do not agree") && text.contains("rpc.test: 3") && text.contains("rpc2.test: 4"))367        // asked twice (the retry), and nothing after the refusal368        #expect(secondEndpointCalls() == before + 2)369        #expect(h.backend.broadcastEthereum.isEmpty)370371        // a difference that is gone on the retry (the endpoints were one block apart): accepted, with the agreed nonce372        h.backend.secondEndpointNonceLead = 0373        h.backend.secondEndpointNonceLeadQueue = [1]374        before = secondEndpointCalls()375        let review = try await h.service.prepareEthereumSend(asset: .ether, to: EthereumWalletTests.recipient, amount: amount)376        #expect(review.nonce == 3)377        // latest twice (the retry) and pending once on the second endpoint378        #expect(secondEndpointCalls() == before + 3)379380        // the same strict rule guards the broadcast of a transaction signed elsewhere381        let result = try await h.service.signAndBroadcastEthereum(review)382        #expect(result.nonce == 3)383        h.backend.secondEndpointNonceLead = 2384        guard case .untrustedResponse? = await walletError({ try await h.service.broadcastSignedEthereum([result.rawHex]) }) else {385            Issue.record("broadcasting must not proceed on a nonce the endpoints do not agree on")386            return387        }388    }389}390
Files main
Menu

Theme