SPB Git

Repository Public

SyncPersistence.swift 19.6 KB 397 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraWallet/SyncPersistence.swift8// Module           : Qyvora Wallet9// 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 QyvoraMath43import QyvoraCore44import QyvoraBitcoin45import QyvoraEthereum46import QyvoraNetworking47import QyvoraStorage4849// What the last synchronization of each chain read, kept between launches so that the application can show the last50// known state at once instead of "not loaded" until a new synchronization completes.51//52// - Public chain data only: addresses, transactions, balances. Nothing here is secret, and nothing here is needed to53//   spend. It is stored through the same `FileStore` as the profile, with the same data-protection class, excluded54//   from device backups.55// - Each file names the identity it belongs to (network, account, endpoints). A file with another identity, another56//   format version or a content that does not validate is ignored and removed.57// - A restored snapshot is flagged `isFromPreviousSession`: it is the state as of its `synchronizedAt` date.5859/// The addresses of the Bitcoin account as the indexer described them at the last synchronization.60/// The Bitcoin snapshot is rebuilt from it through the same validation as after a synchronization, and the next61/// synchronization reuses the history of the addresses whose statistics did not change.62struct BitcoinSyncCache: Codable, Equatable, Sendable {63    static let currentVersion = 164    static let fileName = "bitcoin-sync.json"65    /// A larger cache is not written (a very large account synchronizes from scratch at each launch).66    static let maximumBytes = 24 << 206768    struct Entry: Codable, Equatable, Sendable {69        var chain: BIP84Account.Chain70        var index: UInt3271        var address: String72        /// Counters of the address when its history was read. nil when they could not be read.73        var stats: EsploraAddressStats?74        var transactions: [EsploraTransaction]75        var truncated: Bool76        var utxos: [EsploraUTXO]7778        init(chain: BIP84Account.Chain, index: UInt32, address: String, stats: EsploraAddressStats?, transactions: [EsploraTransaction],79             truncated: Bool, utxos: [EsploraUTXO]) {80            self.chain = chain81            self.index = index82            self.address = address83            self.stats = stats84            self.transactions = transactions85            self.truncated = truncated86            self.utxos = utxos87        }8889        /// Tolerant decoding: a list missing from an older file is empty.90        init(from decoder: any Decoder) throws {91            let c = try decoder.container(keyedBy: CodingKeys.self)92            chain = try c.decode(BIP84Account.Chain.self, forKey: .chain)93            index = try c.decode(UInt32.self, forKey: .index)94            address = try c.decode(String.self, forKey: .address)95            stats = try c.decodeIfPresent(EsploraAddressStats.self, forKey: .stats)96            transactions = try c.decodeIfPresent([EsploraTransaction].self, forKey: .transactions) ?? []97            truncated = try c.decodeIfPresent(Bool.self, forKey: .truncated) ?? false98            utxos = try c.decodeIfPresent([EsploraUTXO].self, forKey: .utxos) ?? []99        }100    }101102    var version = currentVersion103    /// `WalletService.bitcoinIdentity`: network, account key and endpoint list this data was read for.104    var identity: String105    var synchronizedAt: Date106    var tipHeight: UInt32107    var entries: [Entry]108109    init(identity: String, synchronizedAt: Date, tipHeight: UInt32, entries: [Entry]) {110        self.identity = identity111        self.synchronizedAt = synchronizedAt112        self.tipHeight = tipHeight113        self.entries = entries114    }115116    init(from decoder: any Decoder) throws {117        let c = try decoder.container(keyedBy: CodingKeys.self)118        version = try c.decode(Int.self, forKey: .version)119        guard version >= 1, version <= Self.currentVersion else {120            throw DecodingError.dataCorruptedError(forKey: .version, in: c, debugDescription: "unsupported version")121        }122        identity = try c.decode(String.self, forKey: .identity)123        synchronizedAt = try c.decode(Date.self, forKey: .synchronizedAt)124        tipHeight = try c.decode(UInt32.self, forKey: .tipHeight)125        entries = try c.decodeIfPresent([Entry].self, forKey: .entries) ?? []126    }127}128129/// The last Ethereum snapshot in a storable form.130struct EthereumSnapshotRecord: Codable, Equatable, Sendable {131    static let currentVersion = 1132    static let fileName = "ethereum-sync.json"133    static let maximumBytes = 8 << 20134135    struct Balance: Codable, Equatable, Sendable {136        var token: TokenInfo137        /// "available", "unavailable" or "notLoaded".138        var state: String139        var value: UInt256?140        var reason: String?141    }142143    struct Entry: Codable, Equatable, Sendable {144        var hash: String145        /// "ether", "token", "approval" or "contractCall".146        var kind: String147        var tokenAddress: String?148        var symbol: String?149        var decimals: Int?150        var verified: Bool?151        var method: String?152        var direction: String153        var counterparty: String154        var amount: UInt256155        var fee: UInt256?156        var succeeded: Bool157        var time: Date?158        var blockNumber: UInt64?159        var id: String160    }161162    struct Approval: Codable, Equatable, Sendable {163        var token: TokenInfo164        var spender: EthereumAddress165        var allowance: UInt256166    }167168    /// A list that was read (`items`), or the reason why it was not.169    struct Listing<Item: Codable & Equatable & Sendable>: Codable, Equatable, Sendable {170        var items: [Item]?171        var reason: String?172    }173174    var version = currentVersion175    /// `WalletService.ethereumIdentity`: network, account and endpoint lists this data was read for.176    var identity: String177    var network: EthereumNetwork178    var address: EthereumAddress179    var synchronizedAt: Date180    var blockNumber: UInt64181    var balance: UInt256182    var latestNonce: UInt64183    var pendingNonce: UInt64184    var tokens: [Balance]185    var detectedTokens: [Balance]186    var history: Listing<Entry>187    var approvals: Listing<Approval>188    var notes: [String]189190    init(_ s: EthereumSnapshot, identity: String) {191        func balance(_ b: TokenBalance) -> Balance {192            switch b.balance {193            case .available(let v): return Balance(token: b.token, state: "available", value: v, reason: nil)194            case .unavailable(let reason): return Balance(token: b.token, state: "unavailable", value: nil, reason: reason)195            case .notLoaded: return Balance(token: b.token, state: "notLoaded", value: nil, reason: nil)196            }197        }198        func entry(_ e: EthereumHistoryEntry) -> Entry {199            var r = Entry(hash: e.hash, kind: "ether", tokenAddress: nil, symbol: nil, decimals: nil, verified: nil, method: nil,200                          direction: e.direction.rawValue, counterparty: e.counterparty, amount: e.amount, fee: e.fee, succeeded: e.succeeded,201                          time: e.time, blockNumber: e.blockNumber, id: e.id)202            switch e.kind {203            case .ether: break204            case .token(let address, let symbol, let decimals, let verified):205                r.kind = "token"206                r.tokenAddress = address207                r.symbol = symbol208                r.decimals = decimals209                r.verified = verified210            case .approval(let token):211                r.kind = "approval"212                r.tokenAddress = token213            case .contractCall(let method):214                r.kind = "contractCall"215                r.method = method216            }217            return r218        }219        self.identity = identity220        network = s.network221        address = s.address222        synchronizedAt = s.synchronizedAt223        blockNumber = s.blockNumber224        self.balance = s.balance225        latestNonce = s.latestNonce226        pendingNonce = s.pendingNonce227        tokens = s.tokens.map(balance)228        detectedTokens = s.detectedTokens.map(balance)229        switch s.history {230        case .available(let list): history = Listing(items: list.map(entry), reason: nil)231        case .unavailable(let reason): history = Listing(items: nil, reason: reason)232        case .notLoaded: history = Listing(items: nil, reason: nil)233        }234        switch s.approvals {235        case .available(let list):236            approvals = Listing(items: list.map { Approval(token: $0.token, spender: $0.spender, allowance: $0.allowance) }, reason: nil)237        case .unavailable(let reason): approvals = Listing(items: nil, reason: reason)238        case .notLoaded: approvals = Listing(items: nil, reason: nil)239        }240        notes = s.notes241    }242243    /// Tolerant decoding: lists and remarks missing from an older file are empty; a newer format is refused.244    init(from decoder: any Decoder) throws {245        let c = try decoder.container(keyedBy: CodingKeys.self)246        version = try c.decode(Int.self, forKey: .version)247        guard version >= 1, version <= Self.currentVersion else {248            throw DecodingError.dataCorruptedError(forKey: .version, in: c, debugDescription: "unsupported version")249        }250        identity = try c.decode(String.self, forKey: .identity)251        network = try c.decode(EthereumNetwork.self, forKey: .network)252        address = try c.decode(EthereumAddress.self, forKey: .address)253        synchronizedAt = try c.decode(Date.self, forKey: .synchronizedAt)254        blockNumber = try c.decode(UInt64.self, forKey: .blockNumber)255        balance = try c.decode(UInt256.self, forKey: .balance)256        latestNonce = try c.decode(UInt64.self, forKey: .latestNonce)257        pendingNonce = try c.decodeIfPresent(UInt64.self, forKey: .pendingNonce) ?? latestNonce258        tokens = try c.decodeIfPresent([Balance].self, forKey: .tokens) ?? []259        detectedTokens = try c.decodeIfPresent([Balance].self, forKey: .detectedTokens) ?? []260        history = try c.decodeIfPresent(Listing<Entry>.self, forKey: .history) ?? Listing(items: nil, reason: nil)261        approvals = try c.decodeIfPresent(Listing<Approval>.self, forKey: .approvals) ?? Listing(items: nil, reason: nil)262        notes = try c.decodeIfPresent([String].self, forKey: .notes) ?? []263    }264265    /// The snapshot this record describes, flagged as coming from a previous session; nil when a value is out of the266    /// ranges the service accepts from the network (the file is then ignored).267    func snapshot() -> EthereumSnapshot? {268        guard pendingNonce >= latestNonce, pendingNonce - latestNonce <= 10_000 else { return nil }269        func valid(_ token: TokenInfo) -> Bool {270            token.network == network && token.decimals >= 0 && token.decimals <= WalletService.maximumTokenDecimals && !token.address.isZero271        }272        func balance(_ b: Balance) -> TokenBalance? {273            guard valid(b.token) else { return nil }274            switch b.state {275            case "available": return b.value.map { TokenBalance(token: b.token, balance: .available($0)) }276            case "unavailable": return TokenBalance(token: b.token, balance: .unavailable(reason: b.reason ?? "Not read at the last synchronization."))277            case "notLoaded": return TokenBalance(token: b.token, balance: .notLoaded)278            default: return nil279            }280        }281        func entry(_ e: Entry) -> EthereumHistoryEntry? {282            guard let direction = EthereumHistoryEntry.Direction(rawValue: e.direction) else { return nil }283            let kind: EthereumHistoryEntry.Kind284            switch e.kind {285            case "ether": kind = .ether286            case "token":287                guard let address = e.tokenAddress else { return nil }288                let decimals = e.decimals.flatMap { $0 >= 0 && $0 <= WalletService.maximumTokenDecimals ? $0 : nil }289                kind = .token(address: address, symbol: e.symbol, decimals: decimals, verified: e.verified ?? false)290            case "approval":291                guard let address = e.tokenAddress else { return nil }292                kind = .approval(token: address)293            case "contractCall": kind = .contractCall(method: e.method)294            default: return nil295            }296            return EthereumHistoryEntry(hash: e.hash, kind: kind, direction: direction, counterparty: e.counterparty, amount: e.amount, fee: e.fee,297                                        succeeded: e.succeeded, time: e.time, blockNumber: e.blockNumber, id: e.id)298        }299        let listed = tokens.compactMap(balance), detected = detectedTokens.compactMap(balance)300        guard listed.count == tokens.count, detected.count == detectedTokens.count else { return nil }301        let restoredHistory: Availability<[EthereumHistoryEntry]>302        if let items = history.items {303            let entries = items.compactMap(entry)304            guard entries.count == items.count else { return nil }305            restoredHistory = .available(entries)306        } else {307            restoredHistory = history.reason.map { .unavailable(reason: $0) } ?? .notLoaded308        }309        let restoredApprovals: Availability<[TokenApproval]>310        if let items = approvals.items {311            guard items.allSatisfy({ valid($0.token) || ($0.token.network == network && $0.token.decimals == 0) }) else { return nil }312            restoredApprovals = .available(items.map {313                TokenApproval(token: $0.token, spender: $0.spender, allowance: $0.allowance, isUnlimited: ERC20.isUnlimited($0.allowance))314            })315        } else {316            restoredApprovals = approvals.reason.map { .unavailable(reason: $0) } ?? .notLoaded317        }318        return EthereumSnapshot(network: network, address: address, synchronizedAt: synchronizedAt, blockNumber: blockNumber, balance: self.balance,319                                latestNonce: latestNonce, pendingNonce: pendingNonce, tokens: listed, detectedTokens: detected,320                                history: restoredHistory, approvals: restoredApprovals, notes: notes, isFromPreviousSession: true)321    }322}323324/// Reads and writes the two files. Failures are never fatal: a cache that cannot be read is as if there were none,325/// one that cannot be written leaves the previous launch behaviour (a full synchronization).326enum SyncStore {327    static func load<T: Decodable>(_ type: T.Type, from fileStore: FileStore, name: String, maximumBytes: Int) -> T? {328        guard fileStore.exists(name), let bytes = try? fileStore.read(name), bytes.count <= maximumBytes else { return nil }329        return try? JSONDecoder().decode(T.self, from: Data(bytes))330    }331332    /// Returns false when the value was not stored (too large, or the file system refused).333    @discardableResult334    static func save<T: Encodable>(_ value: T, to fileStore: FileStore, name: String, maximumBytes: Int) -> Bool {335        let encoder = JSONEncoder()336        encoder.outputFormatting = [.sortedKeys]337        guard let data = try? encoder.encode(value), data.count <= maximumBytes else {338            remove(from: fileStore, name: name)339            return false340        }341        do {342            // no older generation is kept: a cache that is lost is simply read again from the network343            try fileStore.write(Bytes(data), to: name, keepPrevious: false)344            return true345        } catch {346            return false347        }348    }349350    static func remove(from fileStore: FileStore, name: String) {351        try? fileStore.remove(name)352    }353}354355extension WalletService {356    /// What a persisted Bitcoin synchronization belongs to: the network, the account key and the endpoint list.357    /// nil without a Bitcoin account on the active network.358    static func bitcoinIdentity(_ profile: WalletProfile) -> String? {359        guard profile.kind != nil, let account = profile.bitcoinAccounts[WalletProfile.coinKey(profile.bitcoinNetwork)] else { return nil }360        let endpoints = (profile.endpoints.esplora[profile.bitcoinNetwork.rawValue] ?? []).joined(separator: ",")361        return "btc|v\(BitcoinSyncCache.currentVersion)|\(profile.bitcoinNetwork.rawValue)|\(account.extendedPublicKey)|\(endpoints)"362    }363364    /// What the persisted snapshot of the primary EVM network belongs to.365    static func ethereumIdentity(_ profile: WalletProfile) -> String? { ethereumIdentity(profile, network: profile.ethereumNetwork) }366367    /// The Bitcoin state of the previous session, when a cache exists for exactly this profile and still validates.368    static func restoredBitcoin(fileStore: FileStore, profile: WalletProfile) -> (cache: BitcoinSyncCache, assembled: AssembledBitcoin)? {369        guard fileStore.exists(BitcoinSyncCache.fileName) else { return nil }370        let network = profile.bitcoinNetwork371        // anything that is not exactly the state of this account on this network and these endpoints is removed372        guard let identity = bitcoinIdentity(profile),373              let cache = SyncStore.load(BitcoinSyncCache.self, from: fileStore, name: BitcoinSyncCache.fileName, maximumBytes: BitcoinSyncCache.maximumBytes),374              cache.identity == identity, cache.tipHeight < 100_000_000, MainnetPolicy.mainnetEnabled || network != .mainnet,375              let data = profile.bitcoinAccounts[WalletProfile.coinKey(network)],376              let account = try? BIP84Account(extendedKey: data.extendedPublicKey, network: network, masterFingerprint: data.masterFingerprint.flatMap { Hex.decode($0) }),377              let scans = try? cache.entries.map({ try AddressScan($0, network: network) }),378              let assembled = try? assembleBitcoin(account: account, tip: cache.tipHeight, scans: scans, profile: profile,379                                                   synchronizedAt: cache.synchronizedAt, fromPreviousSession: true) else {380            SyncStore.remove(from: fileStore, name: BitcoinSyncCache.fileName)381            return nil382        }383        return (cache, assembled)384    }385386    /// Stores the snapshot of the primary EVM network for the next launch.387    func persistEthereumSnapshot() { persistEVMSnapshot(profile.ethereumNetwork) }388389    /// Forgets what was persisted for the Bitcoin account (the network, the account or the endpoints changed).390    func forgetBitcoinSynchronization() {391        bitcoinCache = nil392        SyncStore.remove(from: fileStore, name: BitcoinSyncCache.fileName)393    }394395    func forgetEthereumSynchronization() { forgetEVMSynchronization(profile.ethereumNetwork) }396}397
Files main
Menu

Theme