Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Tests/QyvoraWalletTests/SyncPersistenceTests.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 QyvoraVault50@testable import QyvoraWallet5152/// Synchronization as the interface experiences it: progress that never goes silent, failures that say where they53/// happened, the last known state shown at once after a restart, and a second synchronization that reads only what changed.54@Suite(.readsMainnetPolicy) struct SynchronizationTests {55 /// Collects the events of one Bitcoin synchronization.56 static func eventsOfOneSync(_ service: WalletService, _ work: () async throws -> Void) async rethrows -> [WalletEvent] {57 let stream = await service.events()58 try await work()59 var events = [WalletEvent]()60 for await event in stream {61 events.append(event)62 if case .syncFinished(.bitcoin) = event { break }63 if case .syncFailed(.bitcoin, _) = event { break }64 }65 return events66 }6768 static func progress(_ events: [WalletEvent]) -> [(stage: String, completed: Int, total: Int?)] {69 events.compactMap {70 if case .syncProgress(.bitcoin, let stage, let completed, let total) = $0 { return (stage, completed, total) }71 return nil72 }73 }7475 @Test func progressIsReportedPerAddressAndPerHistoryPage() async throws {76 let h = try await Harness.abandonWallet()77 defer { h.cleanup() }78 let a0 = try await h.receive(0)79 for i in 0..<60 { h.backend.fund(a0, 1_000 + UInt64(i), height: 100 + i) } // three pages of history80 h.backend.fund(try await h.change(1), 7_000, height: 150)8182 let events = try await Self.eventsOfOneSync(h.service) { _ = try await h.service.syncBitcoin() }83 let steps = Self.progress(events)84 #expect(events.first == .syncStarted(.bitcoin) && events.last == .syncFinished(.bitcoin))8586 // one event per address of the receive chain: 1…20 of 20, then 21…40 of 40 (the window grows with discovery)87 let receive = steps.filter { $0.stage == "Scanning receive addresses" }88 #expect(receive.filter { $0.total == 20 }.map(\.completed) == Array(0...20))89 #expect(receive.filter { $0.total == 40 }.map(\.completed) == Array(20...40))90 let change = steps.filter { $0.stage == "Scanning change addresses" }91 #expect(change.filter { $0.total == 20 }.map(\.completed) == Array(0...20))92 #expect(change.filter { $0.total == 40 }.map(\.completed) == Array(20...40))93 // counts never exceed their total and never go backwards within a stage94 #expect(steps.allSatisfy { $0.total == nil || $0.completed <= $0.total! })9596 // one event per page of the long history, naming the address and the page97 let pages = steps.filter { $0.stage.hasPrefix("Scanning receive addresses · history of address 0, page ") }98 #expect(pages.map(\.stage) == [1, 2, 3].map { "Scanning receive addresses · history of address 0, page \($0)" })99 #expect(pages.allSatisfy { $0.total == 20 })100 #expect(steps.contains { $0.stage == "Scanning change addresses · history of address 1, page 1" })101102 // unspent outputs: per used address103 #expect(steps.filter { $0.stage == "Reading unspent outputs" }.map(\.completed) == [0, 1, 2])104 #expect(steps.filter { $0.stage == "Reading unspent outputs" }.allSatisfy { $0.total == 2 })105 // nothing but real stages: every event carries a stage name106 #expect(steps.allSatisfy { !$0.stage.isEmpty })107 }108109 @Test func aFailureNamesItsStageAndItsEndpoint() async throws {110 let h = try await Harness.abandonWallet()111 defer { h.cleanup() }112 let a3 = try await h.receive(3)113 for i in 0..<60 { h.backend.fund(a3, 1_000 + UInt64(i), height: 100 + i) }114 _ = try await h.service.syncBitcoin()115116 // the second page of a long history is rate-limited for good, long after the synchronization started117 h.clock.advance(60)118 h.backend.fund(a3, 5_000, height: 199) // the counters change: the history is read again119 h.backend.overrides = [(match: "GET esplora.test/api/address/\(a3)/txs/chain/", status: 429, body: "Too Many Requests")]120 guard case .network(let text)? = await walletError({ try await h.service.syncBitcoin() }) else {121 Issue.record("expected a network error")122 return123 }124 #expect(text.contains("reading the history of receive address 3") && text.contains("page 2"))125 #expect(text.contains("esplora.test") && text.contains("HTTP 429 (too many requests)"))126 #expect(!ErrorMessageTests.looksRaw(text))127 // the same sentence reaches the dashboard, and the older snapshot stays128 let dashboard = await h.service.snapshot()129 #expect(dashboard.bitcoinSyncError == WalletError.network(text).userMessage)130 #expect(dashboard.bitcoin.value?.transactions.count == 60)131 let events = await Self.eventsOfOneSync(h.service) { _ = await walletError { try await h.service.syncBitcoin() } }132 #expect(events.last == .syncFailed(.bitcoin, reason: WalletError.network(text).userMessage))133134 // the unspent outputs of one address135 h.backend.overrides = [(match: "GET esplora.test/api/address/\(a3)/utxo", status: 500, body: "Internal Server Error")]136 guard case .network(let unspent)? = await walletError({ try await h.service.syncBitcoin() }) else {137 Issue.record("expected a network error")138 return139 }140 #expect(unspent.contains("reading the unspent outputs of receive address 3") && unspent.contains("esplora.test: HTTP 500 (server error)"))141142 // the counters of one address, answered with something else than JSON143 let a7 = try await h.receive(7)144 h.backend.overrides = [(match: "GET esplora.test/api/address/\(a7)", status: 200, body: "<html>blocked</html>")]145 guard case .network(let invalid)? = await walletError({ try await h.service.syncBitcoin() }) else {146 Issue.record("expected a network error")147 return148 }149 #expect(invalid.contains("reading the statistics of receive address 7") && invalid.contains("esplora.test: invalid answer"))150 #expect(!ErrorMessageTests.looksRaw(invalid))151152 // the chain tip153 h.backend.overrides = [(match: "GET esplora.test/api/blocks/tip/height", status: 503, body: "down")]154 guard case .network(let tip)? = await walletError({ try await h.service.syncBitcoin() }) else {155 Issue.record("expected a network error")156 return157 }158 #expect(tip == "reading the chain tip: esplora.test: HTTP 503 (server error)")159160 // an endpoint that does not answer, and a device without connection: the reason, not the name of an error type161 h.backend.overrides = []162 h.backend.silentHosts = ["esplora.test"]163 guard case .network(let silent)? = await walletError({ try await h.service.syncBitcoin() }) else {164 Issue.record("expected a network error")165 return166 }167 #expect(silent == "reading the chain tip: esplora.test: the server did not answer in time")168 #expect(await h.service.snapshot().bitcoinSyncError == "Network: reading the chain tip: esplora.test: the server did not answer in time")169 }170171 /// A wallet that never received anything: its first synchronization is the chain check, the tip, and one small172 /// request per address of the two gap windows — no history page, no unspent-output list.173 @Test func aFreshWalletNeedsOneSmallRequestPerAddress() async throws {174 let h = try await Harness.abandonWallet()175 defer { h.cleanup() }176 let snapshot = try await h.service.syncBitcoin()177 #expect(snapshot.balance.total == 0 && snapshot.transactions.isEmpty && snapshot.receiveAddress.index == 0)178 #expect(h.backend.requests.count == 2 + 40)179 #expect(h.backend.statisticsRequests == 40)180 #expect(!h.backend.requests.contains { $0.hasSuffix("/txs") || $0.hasSuffix("/utxo") })181 }182183 /// With two endpoints for the network, one that rate-limits (or stops answering) is left alone at once: the wallet184 /// does not wait on it request after request.185 @Test func aRateLimitedEndpointIsLeftForTheOtherOne() async throws {186 for failure in ["rate limit", "silence"] {187 let h = try await Harness.abandonWallet()188 defer { h.cleanup() }189 h.backend.fund(try await h.receive(0), 50_000)190 try await h.service.setEndpoints(FakeBackend.endpoints.with { $0.esplora["signet"] = ["https://esplora.test/api", "https://esplora2.test/api"] })191 if failure == "rate limit" { h.backend.rateLimitedHosts = ["esplora.test"] } else { h.backend.silentHosts = ["esplora.test"] }192 let snapshot = try await h.service.syncBitcoin()193 #expect(snapshot.balance.total == 50_000, "\(failure)")194 // asked once; every later request went straight to the endpoint that answers195 #expect(h.backend.requests.filter { $0.contains(" esplora.test/") }.count == 1, "\(failure)")196 // chain check, tip, 60 addresses (two receive windows, one change window), one history page, one unspent-output list197 let served = h.backend.requests.filter { $0.contains(" esplora2.test/") }.count198 #expect(served == 2 + 60 + 1 + 1, "\(failure)")199 // and the next synchronization does not go back to it while it rests200 _ = try await h.service.syncBitcoin()201 #expect(h.backend.requests.filter { $0.contains(" esplora.test/") }.count == 1, "\(failure)")202 }203 // both endpoints rate-limit: nothing to fail over to, so the wallet waits and retries as with a single endpoint204 let h = try await Harness.abandonWallet()205 defer { h.cleanup() }206 try await h.service.setEndpoints(FakeBackend.endpoints.with { $0.esplora["signet"] = ["https://esplora.test/api", "https://esplora2.test/api"] })207 h.backend.rateLimitedHosts = ["esplora.test", "esplora2.test"]208 guard case .network(let text)? = await walletError({ try await h.service.syncBitcoin() }) else {209 Issue.record("expected a network error")210 return211 }212 #expect(text.contains("esplora.test: HTTP 429") && text.contains("esplora2.test: HTTP 429"))213 #expect(h.backend.requests.filter { $0.contains(" esplora2.test/") }.count == 4)214 }215216 @Test func theSecondSynchronizationReadsOnlyWhatChanged() async throws {217 let h = try await Harness.abandonWallet()218 defer { h.cleanup() }219 let a0 = try await h.receive(0), a5 = try await h.receive(5)220 for i in 0..<60 { h.backend.fund(a0, 1_000 + UInt64(i), height: 100 + i) }221 h.backend.fund(a5, 30_000, height: 120)222 func history() -> [String] { h.backend.requests.filter { $0.contains("/txs") } }223 func unspent() -> Int { h.backend.requests.filter { $0.hasSuffix("/utxo") }.count }224 func historyOf(_ address: String, since mark: Int) -> Int { history().dropFirst(mark).filter { $0.contains(address) }.count }225226 // first: three pages for A0, one for A5227 let first = try await h.service.syncBitcoin()228 #expect(history().count == 4 && unspent() == 2 && h.backend.statisticsRequests == 40 + 20)229 #expect(first.transactions.count == 61 && first.balance.total == 30_000 + (0..<60).reduce(0) { $0 + 1_000 + $1 })230231 // second, nothing changed: every address is asked for its counters, no history is read again, and the232 // balances are still read from the unspent-output lists233 h.clock.advance(120)234 var mark = history().count235 let second = try await h.service.syncBitcoin()236 #expect(history().count == mark && unspent() == 4 && h.backend.statisticsRequests == 2 * 60)237 #expect(second.synchronizedAt == h.clock.now && second.synchronizedAt != first.synchronizedAt && !second.isFromPreviousSession)238 #expect(second.balance == first.balance && second.transactions == first.transactions && second.utxos == first.utxos)239 #expect(second.addresses == first.addresses && second.activity == first.activity)240241 // a payment arrives on A5: only A5 is read again242 h.backend.fund(a5, 4_000, height: 190)243 mark = history().count244 let third = try await h.service.syncBitcoin()245 #expect(historyOf(a5, since: mark) == 1 && historyOf(a0, since: mark) == 0)246 #expect(third.balance.total == second.balance.total + 4_000 && third.transactions.count == 62)247248 // a pending payment on A0: its history is read again now, and again while the transaction is not buried249 let pending = h.backend.fund(a0, 9_000, height: nil)250 mark = history().count251 var snapshot = try await h.service.syncBitcoin()252 #expect(historyOf(a0, since: mark) == 3 && historyOf(a5, since: mark) == 0)253 #expect(snapshot.balance.pending == 9_000 && snapshot.transactions.first?.txid == pending)254 mark = history().count255 _ = try await h.service.syncBitcoin()256 #expect(historyOf(a0, since: mark) == 3) // still in the mempool257 h.backend.confirmAll(at: 200)258 mark = history().count259 snapshot = try await h.service.syncBitcoin()260 #expect(historyOf(a0, since: mark) == 3 && snapshot.balance.pending == 0)261 #expect(snapshot.transactions.first { $0.txid == pending }?.confirmations == 1)262 // one confirmation is not final: read again until it has six263 mark = history().count264 _ = try await h.service.syncBitcoin()265 #expect(historyOf(a0, since: mark) == 3)266 h.backend.tip = 205267 mark = history().count268 snapshot = try await h.service.syncBitcoin()269 #expect(historyOf(a0, since: mark) == 0)270 #expect(snapshot.transactions.first { $0.txid == pending }?.confirmations == 6) // confirmations follow the tip without a new reading271272 // a spend from A5 changes its counters although nothing new is received273 h.backend.spend([(h.backend.txs.first { $0.outputs.contains { $0.value == 30_000 } }!.txid, 0)], to: [(externalAddress(), 29_000)], height: 195)274 mark = history().count275 snapshot = try await h.service.syncBitcoin()276 #expect(historyOf(a5, since: mark) == 1 && historyOf(a0, since: mark) == 0)277 #expect(snapshot.addresses.first { $0.address == a5 }?.exposure == .revealedBySpend)278 let total = snapshot.balance.total279280 // after a restart the persisted scans serve the same purpose281 let reopened = try await Harness.make(backend: h.backend, clock: h.clock, directory: h.directory, configure: false)282 mark = history().count283 let utxosBefore = unspent()284 let again = try await reopened.service.syncBitcoin()285 #expect(history().count == mark && unspent() == utxosBefore + 2)286 #expect(again.balance.total == total && again.transactions == snapshot.transactions && !again.isFromPreviousSession)287288 // an endpoint change discards what was read from the previous endpoints289 // changing the endpoints of a full wallet needs a credential verified recently (QYV-APP-002)290 try await reopened.service.unlock(password: Harness.password)291 try await reopened.service.setEndpoints(FakeBackend.endpoints.with { $0.esplora["signet"] = ["https://esplora2.test/api"] })292 mark = history().count293 _ = try await reopened.service.syncBitcoin()294 #expect(historyOf(a0, since: mark) == 3 && historyOf(a5, since: mark) == 1)295 }296297 @Test func theLastSnapshotsAreRestoredAsThoseOfThePreviousSession() async throws {298 let s = try await BitcoinWalletTests.scenario()299 defer { s.h.cleanup() }300 let h = s.h301 h.backend.balances[EthereumWalletTests.owner] = EthereumWalletTests.oneEther302 h.backend.latestNonce[EthereumWalletTests.owner] = 4303 var contract = FakeBackend.TokenContract(symbol: "OTH", name: "Other", decimals: UInt256(8))304 contract.balances[EthereumWalletTests.owner] = UInt256(1_234)305 let other = "0x" + String(repeating: "e5", count: 20)306 h.backend.tokens[other] = contract307 h.backend.indexerTransactions = "{\"items\":[\(EthereumWalletTests.nativeItem(hash: EthereumWalletTests.hash(1), from: EthereumWalletTests.recipient, to: Harness.abandonEthereumAddress, value: "1000000000000000000"))]}"308 _ = try await h.service.addCustomToken(address: other)309 try await h.service.setAddressLabel("Savings", for: s.a0)310 let bitcoin = try await h.service.syncBitcoin()311 let ethereum = try await h.service.syncEthereum()312 let synchronizedAt = h.clock.now313 #expect(!bitcoin.isFromPreviousSession && !ethereum.isFromPreviousSession)314 let fresh = await h.service.portfolioValuation()315 #expect(!fresh.isFromPreviousSession && fresh.balancesAsOf == synchronizedAt)316 let freshShield = await h.service.shieldReport()317 #expect(!freshShield.isFromPreviousSession && freshShield.bitcoinMeasuredAt == synchronizedAt && freshShield.ethereumMeasuredAt == synchronizedAt)318319 // the files hold public chain data only320 let store = try FileStore(root: h.directory)321 for name in [BitcoinSyncCache.fileName, EthereumSnapshotRecord.fileName] {322 let text = String(decoding: try store.read(name), as: UTF8.self)323 #expect(Harness.abandon.dropLast().allSatisfy { !text.contains("\"\($0)\"") } && !text.contains("about") && !text.contains(Harness.password))324 #expect(!store.previousExists(name))325 }326327 // next launch, hours later, with no network at all: the last known state is there at once, and says what it is328 h.clock.advance(7_200)329 let offline = FakeBackend()330 offline.forbidAllRequests = true331 let reopened = try await Harness.make(backend: offline, clock: h.clock, directory: h.directory, configure: false)332 let dashboard = await reopened.service.snapshot()333 var restoredBitcoin = try #require(dashboard.bitcoin.value), restoredEthereum = try #require(dashboard.ethereum.value)334 #expect(restoredBitcoin.isFromPreviousSession && restoredEthereum.isFromPreviousSession)335 #expect(restoredBitcoin.synchronizedAt == synchronizedAt && restoredEthereum.synchronizedAt == synchronizedAt)336 #expect(dashboard.bitcoinSyncError == nil && dashboard.ethereumSyncError == nil)337 #expect(!dashboard.isSynchronizingBitcoin && !dashboard.isSynchronizingEthereum)338 // identical to what was synchronized, flag apart — labels and coin-control state included339 restoredBitcoin.isFromPreviousSession = false340 restoredEthereum.isFromPreviousSession = false341 #expect(restoredBitcoin == bitcoin)342 #expect(restoredEthereum == ethereum)343 #expect(restoredBitcoin.addresses.first { $0.address == s.a0 }?.label == "Savings")344 #expect(await reopened.service.latestBitcoinSnapshot()?.isFromPreviousSession == true)345 #expect(await reopened.service.latestEthereumSnapshot()?.isFromPreviousSession == true)346347 // the valuation and the Shield are built from it and say so348 let valuation = dashboard.valuation349 #expect(valuation.isFromPreviousSession && valuation.balancesAsOf == synchronizedAt)350 #expect(valuation.lines.map(\.amount) == fresh.lines.map(\.amount) && valuation.lines.map(\.id) == fresh.lines.map(\.id))351 let shield = await reopened.service.shieldReport()352 #expect(shield.isFromPreviousSession && shield.bitcoinMeasuredAt == synchronizedAt && shield.ethereumMeasuredAt == synchronizedAt)353 #expect(shield.report.keyExposure == freshShield.report.keyExposure)354 #expect(shield.report.keyExposure.bitcoin?.exposedUTXOCount == 1 && shield.report.keyExposure.ethereum?.outgoingTransactionCount == 4)355 #expect(!shield.report.keyExposure.isPartlyUnmeasured)356357 // coins that may have been spent since are not spent from: a payment needs a fresh reading358 for attempt in [359 { try await reopened.service.prepareBitcoinSend(to: externalAddress(), amount: 10_000, feeRate: FeeRate(satPerVByte: 2)) },360 { try await reopened.service.prepareSweepOfExposedBitcoin(feeRate: FeeRate(satPerVByte: 2)) },361 ] as [@Sendable () async throws -> BitcoinSendPlan] {362 guard case .notSynchronized(let text)? = await walletError(attempt) else {363 Issue.record("a payment must not be built from the previous session")364 continue365 }366 #expect(text.contains("previous session"))367 }368 #expect(offline.requests.isEmpty)369370 // a synchronization replaces it with a fresh reading371 let online = try await Harness.make(backend: h.backend, clock: h.clock, directory: h.directory, configure: false)372 #expect(await online.service.latestBitcoinSnapshot()?.isFromPreviousSession == true)373 let resynced = try await online.service.syncBitcoin()374 #expect(!resynced.isFromPreviousSession && resynced.synchronizedAt == h.clock.now && resynced.balance == bitcoin.balance)375 #expect(await online.service.portfolioValuation().isFromPreviousSession) // Ethereum is still the previous session's376 #expect(await online.service.portfolioValuation().balancesAsOf == synchronizedAt)377 _ = try await online.service.syncEthereum()378 #expect(await online.service.portfolioValuation().isFromPreviousSession == false)379 #expect(await online.service.shieldReport().isFromPreviousSession == false)380 // a failed synchronization keeps the restored state, with the error next to it381 let failing = try await Harness.make(backend: h.backend, clock: h.clock, directory: h.directory, configure: false)382 h.backend.overrides = [(match: "GET esplora.test/api/blocks/tip/height", status: 503, body: "down")]383 _ = await walletError { try await failing.service.syncBitcoin() }384 let afterFailure = await failing.service.snapshot()385 #expect(afterFailure.bitcoin.value?.isFromPreviousSession == true && afterFailure.bitcoinSyncError?.contains("HTTP 503") == true)386 }387388 @Test func persistedSnapshotsAreInvalidatedWithTheirIdentity() async throws {389 let s = try await BitcoinWalletTests.scenario()390 defer { s.h.cleanup() }391 let h = s.h392 h.backend.balances[EthereumWalletTests.owner] = EthereumWalletTests.oneEther393 _ = try await h.service.syncBitcoin()394 _ = try await h.service.syncEthereum()395 let store = try FileStore(root: h.directory)396 let names = [BitcoinSyncCache.fileName, EthereumSnapshotRecord.fileName]397 let saved = try names.map { try store.read($0) }398 func putBack() throws { for (name, bytes) in zip(names, saved) { try store.write(bytes, to: name, keepPrevious: false) } }399 func reopen() async throws -> WalletSnapshot {400 let offline = FakeBackend()401 offline.forbidAllRequests = true402 return await (try await Harness.make(backend: offline, clock: h.clock, directory: h.directory, configure: false)).service.snapshot()403 }404 func expectNothingRestored(_ what: String) async throws {405 let dashboard = try await reopen()406 #expect(dashboard.bitcoin.value == nil && dashboard.ethereum.value == nil, "\(what)")407 #expect(dashboard.valuation.lines.isEmpty && !dashboard.valuation.isFromPreviousSession && dashboard.valuation.balancesAsOf == nil, "\(what)")408 #expect(names.allSatisfy { !store.exists($0) }, "\(what): the stale files are removed")409 }410 #expect(try await reopen().bitcoin.value != nil)411412 // the endpoints change: nothing read from the previous ones is carried over, even if the files reappear413 try await h.service.setEndpoints(FakeBackend.endpoints.with {414 $0.esplora["signet"] = ["https://esplora2.test/api"]415 $0.ethereumRPC["sepolia"] = ["https://rpc2.test"]416 })417 #expect(names.allSatisfy { !store.exists($0) })418 try putBack()419 try await expectNothingRestored("other endpoints")420 try await h.service.setEndpoints(FakeBackend.endpoints)421 try putBack()422 let both = try await reopen()423 #expect(both.bitcoin.value != nil)424 #expect(both.ethereum.value != nil)425426 // only the indexer changes: the Ethereum snapshot goes, the Bitcoin one stays427 try await h.service.setEndpoints(FakeBackend.endpoints.with { $0.ethereumIndexer = [:] })428 #expect(store.exists(BitcoinSyncCache.fileName) && !store.exists(EthereumSnapshotRecord.fileName))429 try await h.service.setEndpoints(FakeBackend.endpoints)430431 // the network changes432 try putBack()433 try await h.service.setBitcoinNetwork(.testnet)434 #expect(!store.exists(BitcoinSyncCache.fileName) && store.exists(EthereumSnapshotRecord.fileName))435 try putBack()436 let onTestnet = try await reopen()437 #expect(onTestnet.bitcoin == .notLoaded && onTestnet.ethereum.value != nil && !store.exists(BitcoinSyncCache.fileName))438 try await h.service.setBitcoinNetwork(.signet)439440 // the account changes: the wallet is deleted and another one is created in its place441 try putBack()442 try await h.service.deleteWallet()443 #expect(names.allSatisfy { !store.exists($0) })444 try putBack()445 try await expectNothingRestored("no wallet")446 _ = try await h.service.createWallet(password: Harness.password)447 try await h.service.setEndpoints(FakeBackend.endpoints)448 try putBack()449 try await expectNothingRestored("another account")450451 // back to the original account: damaged, future-format and tampered files are ignored and removed452 try await h.service.deleteWallet()453 try await h.service.importWallet(words: Harness.abandon, password: Harness.password)454 try await h.service.setEndpoints(FakeBackend.endpoints)455 try putBack()456 #expect(try await reopen().bitcoin.value != nil)457 func rewrite(_ name: String, _ change: (inout [String: Any]) -> Void) throws {458 var object = try #require(try JSONSerialization.jsonObject(with: Data(saved[names.firstIndex(of: name)!])) as? [String: Any])459 change(&object)460 try store.write(Bytes(try JSONSerialization.data(withJSONObject: object)), to: name, keepPrevious: false)461 }462 for name in names { try store.write(Bytes("{ not json".utf8), to: name, keepPrevious: false) }463 try await expectNothingRestored("damaged files")464 for name in names { try rewrite(name) { $0["version"] = 99 } }465 try await expectNothingRestored("a newer format")466 for name in names { try rewrite(name) { $0["identity"] = "btc|v1|signet|tpubSomethingElse|" } }467 try await expectNothingRestored("another identity")468 // content that fails the checks applied to network answers: an unspent output that its transaction contradicts,469 // and a pending nonce below the latest one470 try rewrite(BitcoinSyncCache.fileName) { object in471 var entries = object["entries"] as! [[String: Any]]472 let i = entries.firstIndex { !(($0["utxos"] as? [Any]) ?? []).isEmpty }!473 var utxos = entries[i]["utxos"] as! [[String: Any]]474 utxos[0]["value"] = 2_000_000_000_000_000475 entries[i]["utxos"] = utxos476 object["entries"] = entries477 }478 try rewrite(EthereumSnapshotRecord.fileName) { $0["pendingNonce"] = 0; $0["latestNonce"] = 9 }479 try await expectNothingRestored("content that does not validate")480 // an older file without the optional lists still loads (tolerant decoding)481 try putBack()482 try rewrite(EthereumSnapshotRecord.fileName) { object in483 for key in ["notes", "detectedTokens", "history", "approvals", "pendingNonce"] { object[key] = nil }484 }485 let tolerant = try #require(try await reopen().ethereum.value)486 #expect(tolerant.isFromPreviousSession && tolerant.history == .notLoaded && tolerant.approvals == .notLoaded && tolerant.notes.isEmpty)487 #expect(tolerant.balance == EthereumWalletTests.oneEther)488 }489}490