Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Sources/QyvoraWallet/WalletService.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 QyvoraStorage48import QyvoraVault49import QyvoraIdentity50import QyvoraSolana51import QyvoraTron5253/// The wallet service: everything the interface needs, behind one actor.54///55/// - No account, no server of its own, no telemetry: the only network traffic goes to the endpoints of the profile.56/// - Secrets live in the vault only; they are read for the duration of a derivation or a signature, then wiped.57/// - Amounts are integers. `Double` appears only in fiat prices and valuations.58/// - Every network answer is validated before use; missing data is reported as missing, never replaced.59/// - Every method throws `WalletError` only.60public actor WalletService {61 // MARK: Constants6263 /// Quotes older than this are labelled stale.64 public static let quoteFreshness: TimeInterval = 60065 /// Absolute fee above which a Bitcoin plan carries a warning, in satoshis.66 public static let bitcoinFeeWarningThreshold: UInt64 = 50_00067 /// Hard cap on the absolute fee of a Bitcoin transaction the wallet builds or signs, in satoshis.68 public static let bitcoinMaximumFee: UInt64 = 1_000_00069 /// Highest fee rate the wallet accepts, in sat/vB.70 public static let bitcoinMaximumFeeRate: UInt64 = 1_00071 /// Gas limit above which a token or contract call is refused.72 public static let ethereumGasLimitCeiling: UInt64 = 200_00073 /// Gas of a plain ether transfer.74 public static let ethereumTransferGas: UInt64 = 21_00075 /// Largest `decimals()` accepted for a token.76 public static let maximumTokenDecimals = 3677 /// How long a verified credential (password, PIN, biometrics) authorizes the sensitive actions: revealing the78 /// recovery phrase, exporting private material or a backup, signing, disabling an unlock method, switching mainnet79 /// on, changing the endpoints (QYV-APP-002). Seconds, measured on the monotonic clock.80 public static let authenticationWindow: TimeInterval = 12081 /// The same for adding an unlock method (PIN, biometrics): long enough for the first set-up after creating a wallet.82 public static let setupAuthenticationWindow: TimeInterval = 90083 /// Longest auto-lock delay of a wallet that holds keys, in seconds (QYV-APP-004): fifteen minutes. There is no84 /// "never": the auto-lock is the only time-based protection of an unlocked vault.85 public static let maximumAutoLockDelay: TimeInterval = 90086 /// Fewest characters of a vault or backup password (QYV-APP-001).87 public static let minimumPasswordLength = 1088 /// Lowest `PasswordQuality` level accepted for a vault or backup password: "fair", an estimate of 45 bits or more.89 public static let minimumPasswordLevel = PasswordQuality.Level.fair90 /// A PIN is exactly this many decimal digits, everywhere: setup, lock screen, re-authentication.91 public static let pinLength = 692 /// Read-only synchronization: how far apart the transaction counts of two endpoints may be at the same instant93 /// (they are not at the same block on a busy account). Preparing a transaction requires exact agreement instead.94 public static let nonceReadWindow: UInt64 = 1695 /// Pause before the single retry when the endpoints disagree on the nonce while a transaction is being prepared.96 static let nonceAgreementRetryDelay: Duration = .milliseconds(1_500)97 /// Addresses scanned per chain at most.98 static let maximumScanIndex: UInt32 = 2_00099100 /// Events kept for a listener that reads slowly (each Bitcoin event is also sent in its per-chain form).101 static let eventBufferSize = 1_024102103 static let profileFile = "wallet-profile.json"104 static let marketFile = "market-cache.json"105106 // MARK: Dependencies107108 let vault: Vault109 let fileStore: FileStore110 let settings: SettingsStore111 let marketStore: SettingsStore112 let gate: GatedTransport113 let now: @Sendable () -> Date114 /// Clock the user cannot set: ages the last authentication.115 let monotonic: @Sendable () -> MonotonicInstant116 /// Fixed seed of the transaction builder's shuffles (tests); nil draws from the system generator.117 let transactionSeed: UInt64?118 /// Cost of the key derivation of backup files.119 let backupKDF: KDFParameters120 /// What the application declared about this build (Info.plist `QYInternalMainnet`).121 let internalBuildAllowsMainnet: Bool122 /// History pages read per Bitcoin address before the history is flagged as truncated.123 let historyPagesPerAddress: Int124 /// Spacing of the requests to TRON endpoints (tests remove it).125 let tronPacing: TronPacing126127 // MARK: State128129 var profile: WalletProfile130 var bitcoinSnapshot: BitcoinSnapshot?131 var bitcoinError: String?132 var bitcoinSyncTask: Task<BitcoinSnapshot, any Error>?133 /// What the last synchronization read per address (also persisted): the next one reuses unchanged histories.134 var bitcoinCache: BitcoinSyncCache?135 /// Stage of the running Bitcoin synchronization, with its real counts.136 var bitcoinProgress: (stage: String, completed: Int, total: Int)?137 /// Scripts this wallet paid in the past (address-reuse warning).138 var paidScripts: Set<Bytes> = []139 /// Outputs spent by a transaction broadcast in this session, until the next synchronization.140 var locallySpent: Set<BitcoinOutPoint> = []141 /// EVM state, one entry per network that was synchronized in this session or restored from the last one.142 var evmSnapshots: [EthereumNetwork: EthereumSnapshot] = [:]143 var evmErrors: [EthereumNetwork: String] = [:]144 var evmSyncTasks: [EthereumNetwork: Task<EthereumSnapshot, any Error>] = [:]145 /// The primary EVM network's entries, under the names the 1.0 code uses.146 var ethereumSnapshot: EthereumSnapshot? {147 get { evmSnapshots[profile.ethereumNetwork] }148 set { evmSnapshots[profile.ethereumNetwork] = newValue }149 }150 var ethereumError: String? {151 get { evmErrors[profile.ethereumNetwork] }152 set { evmErrors[profile.ethereumNetwork] = newValue }153 }154 /// Litecoin, Dogecoin and Bitcoin Cash state, per network (WalletService+UTXOCoins.swift).155 var utxoCoinStates: [BitcoinNetwork: UTXOCoinState] = [:]156 var utxoCoinSyncTasks: [BitcoinNetwork: Task<BitcoinSnapshot, any Error>] = [:]157 /// Solana and TRON state, per network.158 var solanaRecords: [SolanaNetwork: SolanaChainRecord] = [:]159 var tronRecords: [TronNetwork: TronChainRecord] = [:]160 /// Error of the last failed synchronization of a Solana or TRON network.161 var chainErrors: [ChainID: String] = [:]162 var chainSyncTasks: [ChainID: Task<Void, any Error>] = [:]163 /// Stage of the running synchronization of each chain, with its real counts.164 var chainProgress: [ChainID: ChainSyncProgress] = [:]165 /// Transactions signed in this session on Solana and TRON, by identifier: what `track` and the "same payment166 /// still in flight" rule need (the signed bytes, so that a retry re-sends them instead of signing again).167 var sentTransactions: [String: SentTransaction] = [:]168 /// Review → identifier of the transaction signed for it. A review is signed once.169 var signedReviews: [UUID: String] = [:]170 /// TronGrid API key, read from the vault at unlock and dropped at lock. Never stored anywhere else.171 var tronAPIKey: TronAPIKey?172 /// Tokens whose metadata was read on chain in this session, by `TokenInfo.id`.173 var verifiedTokens: [String: TokenInfo] = [:]174 var verifiedChains: Set<String> = []175 /// TRC-20 tokens whose decimals were read on chain in this session, by `ChainToken.id`.176 var verifiedTronTokens: Set<String> = []177 var market = MarketCache()178 /// USD prices read from the second price source in this session, by asset identifier (QYV-SVC-087). Memory only.179 var priceChecks: [String: PriceCheck] = [:]180 var marketError: String?181 var charts: [String: PriceChart] = [:]182 var listeners: [UUID: AsyncStream<WalletEvent>.Continuation] = [:]183 /// Temporary identity of a device waiting for a transfer package (never stored).184 var transferIdentity: Identity?185 /// How many times, in this session, the public account data of the profile differed from the vault's and was186 /// replaced by it at unlock (QYV-SVC-011). Anything but zero means the profile file was modified outside the wallet.187 var accountBindingRepairs = 0188 /// Recipients paid by a transaction broadcast in this session (first-payment warning), as "<chain id>|<address>"189 /// (EVM addresses in lower case).190 var paidRecipients: Set<String> = []191 /// When a credential was last verified by the vault in this session; nil after a lock.192 var lastAuthentication: MonotonicInstant?193194 // MARK: Creation195196 /// - Parameters:197 /// - vault: the Quantum Vault (tests pass one built on a temporary directory and an in-memory Keychain).198 /// - fileStore: where the non-secret profile and the price cache are stored.199 /// - transport: HTTP transport; the service wraps it so that cold mode and rate limits are enforced centrally.200 /// - now: wall clock.201 /// - sleep: pause used by the retry on HTTP 429.202 /// - transactionSeed: fixed seed for reproducible Bitcoin transactions in tests; leave nil in production.203 /// - backupKDF: key-derivation cost of backup files (tests lower it).204 /// - historyPagesPerAddress: pages of history read per Bitcoin address (1…100, default 20). Beyond it the history is205 /// flagged as truncated; balances stay exact and key exposure is taken from the address statistics.206 /// - internalBuildAllowsMainnet: true only on an internal build that declares mainnet testing. When true, the207 /// initializer calls `MainnetPolicy.configure` with it and the opt-in stored in the profile.208 /// - monotonic: clock the user cannot set (ages the last authentication); tests inject one.209 public init(vault: Vault, fileStore: FileStore, transport: any HTTPTransport, now: @escaping @Sendable () -> Date = { Date() },210 monotonic: @escaping @Sendable () -> MonotonicInstant = { MonotonicInstant.system() },211 sleep: @escaping @Sendable (Duration) async -> Void = { try? await Task.sleep(for: $0) },212 transactionSeed: UInt64? = nil, backupKDF: KDFParameters = .standard,213 internalBuildAllowsMainnet: Bool = false, historyPagesPerAddress: Int = 20,214 tronPacing: TronPacing = .default) throws(WalletError) {215 self.vault = vault216 self.fileStore = fileStore217 self.now = now218 self.monotonic = monotonic219 self.transactionSeed = transactionSeed220 self.backupKDF = backupKDF221 self.internalBuildAllowsMainnet = internalBuildAllowsMainnet222 self.historyPagesPerAddress = min(max(historyPagesPerAddress, 1), 100)223 self.tronPacing = tronPacing224 settings = SettingsStore(fileStore: fileStore, name: Self.profileFile)225 marketStore = SettingsStore(fileStore: fileStore, name: Self.marketFile)226 gate = GatedTransport(inner: transport, sleep: sleep)227 var loaded: WalletProfile228 do {229 loaded = try settings.load(WalletProfile.self) ?? WalletProfile()230 } catch {231 throw WalletError.storage("the wallet profile cannot be read: \(WalletMessages.storageReason(error))")232 }233 // The policy is process-wide: it is only touched by a build that declares mainnet testing.234 if internalBuildAllowsMainnet {235 MainnetPolicy.configure(internalBuildAllowsMainnet: true, userOptedIn: loaded.mainnetOptIn)236 }237 // A profile written before QYV-APP-004 may hold "never" or a longer delay than the service now accepts.238 loaded.autoLock = Self.boundedAutoLock(loaded.autoLock)239 // A stored profile can never widen what the policy allows.240 if !MainnetPolicy.mainnetEnabled {241 if !loaded.bitcoinNetwork.isTest { loaded.bitcoinNetwork = loaded.bitcoinNetwork.testCounterpart }242 if !loaded.ethereumNetwork.isTest { loaded.ethereumNetwork = loaded.ethereumNetwork.testCounterpart }243 loaded.networkMode = .test244 }245 profile = loaded246 gate.setOffline(loaded.coldMode)247 gate.setAlternatives(Self.endpointGroups(loaded))248 // The last known state of each chain, flagged as coming from the previous session (public data only)249 if let restored = Self.restoredBitcoin(fileStore: fileStore, profile: loaded) {250 bitcoinCache = restored.cache251 bitcoinSnapshot = restored.assembled.snapshot252 paidScripts = restored.assembled.paidScripts253 }254 Self.migrateLegacyEVMFile(fileStore: fileStore)255 for kind in Self.activeKinds(loaded) {256 switch kind {257 case .utxo(let network):258 // Bitcoin was restored above; the other coins have one record each259 if !Self.isPrimaryUTXO(network) { utxoCoinStates[network] = Self.restoredUTXOCoin(fileStore: fileStore, profile: loaded, network: network) }260 case .evm(let network): evmSnapshots[network] = Self.restoredEthereum(fileStore: fileStore, profile: loaded, network: network)261 case .solana(let network): solanaRecords[network] = Self.restoredSolana(fileStore: fileStore, profile: loaded, network: network)262 case .tron(let network): tronRecords[network] = Self.restoredTron(fileStore: fileStore, profile: loaded, network: network)263 }264 }265 // the primary EVM network is restored even when its chain is not in the enabled list (the 1.0 screens show it)266 if evmSnapshots[loaded.ethereumNetwork] == nil {267 evmSnapshots[loaded.ethereumNetwork] = Self.restoredEthereum(fileStore: fileStore, profile: loaded, network: loaded.ethereumNetwork)268 }269 if var cached = try? marketStore.load(MarketCache.self) {270 cached.markAllPersisted()271 market = cached272 }273 }274275 // MARK: Events276277 /// A stream of progress and state events. Each call returns an independent stream; it ends when the consumer stops.278 public func events() -> AsyncStream<WalletEvent> {279 let id = UUID()280 let (stream, continuation) = AsyncStream<WalletEvent>.makeStream(bufferingPolicy: .bufferingNewest(Self.eventBufferSize))281 listeners[id] = continuation282 continuation.onTermination = { [weak self] _ in283 Task { await self?.removeListener(id) }284 }285 return stream286 }287288 private func removeListener(_ id: UUID) { listeners[id] = nil }289290 func emit(_ event: WalletEvent) {291 for c in listeners.values { c.yield(event) }292 // the Bitcoin code sends the 1.0 events; listeners of the per-chain events get them in that form too293 if let mirrored = chainEvent(mirroring: event) { for c in listeners.values { c.yield(mirrored) } }294 }295296 // MARK: Internals shared by the extensions297298 /// Runs `body` and converts whatever it throws into a `WalletError`.299 func run<T>(_ body: () async throws -> T) async throws(WalletError) -> T {300 do {301 return try await body()302 } catch {303 throw WalletError.wrap(error, now: now())304 }305 }306307 /// Hosts that serve the same data (the endpoints of one network): when one of them rate-limits or stops308 /// answering, requests go to the others instead of waiting for it.309 static func endpointGroups(_ profile: WalletProfile) -> [Set<String>] {310 let endpoints = profile.endpoints311 let lists = Self.utxoEndpointLists(endpoints) + Array(endpoints.ethereumRPC.values) + Array(endpoints.ethereumIndexer.values)312 + Array(profile.solanaEndpoints.rpc.values) + Array(profile.tronEndpoints.fullNodes.values)313 return lists.map { Set($0.compactMap { URL(string: $0)?.host }) }.filter { $0.count > 1 }314 }315316 /// Every list of UTXO indexer URLs that serve the same data.317 static func utxoEndpointLists(_ endpoints: EndpointConfiguration) -> [[String]] {318 Array(endpoints.esplora.values) + Array(endpoints.blockbook.values) + Array(endpoints.bitcore.values)319 }320321 func saveProfile() throws {322 do {323 try settings.save(profile)324 } catch {325 throw WalletError.storage("the wallet profile cannot be written: \(WalletMessages.storageReason(error))")326 }327 emit(.profileChanged)328 }329330 func requireWallet() throws -> WalletKind {331 guard let kind = profile.kind else { throw WalletError.noWallet }332 return kind333 }334335 func requireAllowed(_ network: BitcoinNetwork) throws {336 // every production network is "mainnet" for the gate (Litecoin, Dogecoin and Bitcoin Cash included)337 if !network.isTest, !MainnetPolicy.mainnetEnabled { throw WalletError.mainnetDisabled(WalletError.mainnetText) }338 }339340 func requireAllowed(_ network: EthereumNetwork) throws {341 if !network.isTest, !MainnetPolicy.mainnetEnabled { throw WalletError.mainnetDisabled(WalletError.mainnetText) }342 }343344 func requireAllowed(_ kind: ChainKind) throws {345 if !kind.isTest, !MainnetPolicy.mainnetEnabled { throw WalletError.mainnetDisabled(WalletError.mainnetText) }346 }347348 /// The watch-only BIP-84 account of the active (or given) network, from public profile data.349 func bitcoinAccount(_ network: BitcoinNetwork? = nil) throws -> BIP84Account {350 _ = try requireWallet()351 let network = network ?? profile.bitcoinNetwork352 try requireAllowed(network)353 guard let data = profile.bitcoinAccounts[WalletProfile.coinKey(network)] else {354 throw WalletError.featureUnavailable("This wallet has no Bitcoin account for \(network.displayName).")355 }356 let fingerprint = data.masterFingerprint.flatMap { Hex.decode($0) }357 do {358 return try BIP84Account(extendedKey: data.extendedPublicKey, network: network, masterFingerprint: fingerprint)359 } catch {360 throw WalletError.storage("the stored Bitcoin account key is invalid")361 }362 }363364 func ethereumAccount(_ network: EthereumNetwork? = nil) throws -> EthereumAddress {365 _ = try requireWallet()366 try requireAllowed(network ?? profile.ethereumNetwork)367 guard let address = profile.ethereumAddress else {368 throw WalletError.featureUnavailable("This wallet has no Ethereum account.")369 }370 return address371 }372373 // MARK: Fresh authentication (QYV-APP-002)374375 /// Records that the vault has just accepted a credential.376 func noteAuthentication() { lastAuthentication = monotonic() }377378 /// True when a credential was verified within `window` seconds, in this boot session.379 func isAuthenticationFresh(within window: TimeInterval) -> Bool {380 guard let last = lastAuthentication else { return false }381 let instant = monotonic()382 return instant.bootSession == last.bootSession && instant.seconds >= last.seconds && Double(instant.seconds - last.seconds) <= window383 }384385 /// Throws `authenticationRequired` unless a credential was verified recently. A wallet without a vault (watch-only,386 /// or none) has no credential and nothing secret: the rule does not apply to it.387 func requireFreshAuthentication(within window: TimeInterval = WalletService.authenticationWindow) async throws {388 guard profile.kind == .full, await vault.exists else { return }389 guard isAuthenticationFresh(within: window) else { throw WalletError.authenticationRequired }390 }391392 /// Seconds for which the last authentication still authorizes a sensitive action; 0 when one is needed now.393 /// The interface uses it to say so; the rule itself is enforced by every sensitive call.394 public func authenticationValidity() -> TimeInterval {395 guard let last = lastAuthentication else { return 0 }396 let instant = monotonic()397 guard instant.bootSession == last.bootSession, instant.seconds >= last.seconds else { return 0 }398 return max(0, Self.authenticationWindow - Double(instant.seconds - last.seconds))399 }400401 /// Reads the recovery phrase from the vault, derives the master key and hands it to `body`; every intermediate402 /// buffer this function owns is wiped before it returns. The vault must be unlocked and a credential must have403 /// been verified recently: no signature is made on the strength of an unlocked vault alone.404 func withMasterKey<T>(_ body: (ExtendedKey) throws -> T) async throws -> T {405 try await withSeed { seed in406 var master = try ExtendedKey.master(seed: seed)407 // runs after `body` has returned and released the copy it was given408 defer { master.wipe() }409 return try body(master)410 }411 }412413 /// The same, one step earlier: hands the BIP-39 seed (64 bytes) to `body`. Solana derives its Ed25519 key from the414 /// seed itself (SLIP-0010), not from the secp256k1 master key. `body` must not keep the seed: it is erased when415 /// this function returns.416 func withSeed<T>(_ body: (Bytes) throws -> T) async throws -> T {417 guard try requireWallet() == .full else { throw WalletError.watchOnly }418 guard await vault.isUnlocked else { throw WalletError.vaultLocked }419 try await requireFreshAuthentication()420 // QYV-CRY-003. Each secret below is the only owner of its buffer when it is erased (the vault records that421 // carried it are released first), so the bytes are overwritten where they are; no `String` of the phrase or of422 // the passphrase is built: the vault stores both in the normalized form BIP-39 hashes.423 var phrase = Bytes()424 defer { SecureMemory.zero(&phrase) }425 var passphrase = Bytes()426 defer { SecureMemory.zero(&passphrase) }427 do {428 guard let record = try await vault.records(ofType: .recoveryPhrase).first else { throw WalletError.noWallet }429 phrase = record.payload430 }431 do {432 if let record = try await vault.records(ofType: .bip39Passphrase).first { passphrase = record.payload }433 }434 var seed: Bytes435 if PhraseCodec.isNormalized(phrase) {436 seed = BIP39.seed(normalizedMnemonic: phrase, normalizedPassphrase: passphrase)437 } else {438 // a record that is not in the stored form (never written by this service): normalize it the long way439 seed = try BIP39.seed(mnemonic: PhraseCodec.words(phrase), passphrase: String(decoding: passphrase, as: UTF8.self))440 }441 defer { SecureMemory.zero(&seed) }442 return try body(seed)443 }444445 /// Verifies once per session (and per endpoint list) that the Esplora endpoints serve the expected chain.446 func verifiedEsplora(_ network: BitcoinNetwork) async throws -> EsploraClient {447 try requireAllowed(network)448 if gate.isOffline { throw WalletError.offline }449 let client = EsploraClient(network: network, configuration: profile.endpoints, transport: gate)450 guard client.isConfigured else { throw WalletError.network("No Esplora endpoint is configured for \(network.displayName).") }451 let key = "btc|\(network.rawValue)|" + (profile.endpoints.esplora[network.rawValue] ?? []).joined(separator: ",")452 if !verifiedChains.contains(key) {453 do {454 try await client.verifyChain()455 } catch NetworkError.disagreement(let text) {456 throw WalletError.wrongChain(text)457 }458 verifiedChains.insert(key)459 }460 return client461 }462463 func verifiedRPC(_ network: EthereumNetwork) async throws -> EthereumRPC {464 try requireAllowed(network)465 if gate.isOffline { throw WalletError.offline }466 let client = EthereumRPC(network: network, configuration: profile.endpoints, transport: gate)467 guard client.isConfigured else { throw WalletError.network("No JSON-RPC endpoint is configured for \(network.displayName).") }468 let key = "eth|\(network.rawValue)|" + (profile.endpoints.ethereumRPC[network.rawValue] ?? []).joined(separator: ",")469 if !verifiedChains.contains(key) {470 do {471 try await client.verifyChain()472 } catch NetworkError.disagreement(let text) {473 throw WalletError.wrongChain(text)474 }475 verifiedChains.insert(key)476 }477 return client478 }479480 // MARK: Profile481482 /// The persistent, non-secret profile.483 public func currentProfile() -> WalletProfile { profile }484485 /// Switches the primary Bitcoin network (.testnet or .signet; .mainnet throws `mainnetDisabled` unless mainnet is486 /// enabled, and with a full wallet moving from a test network to mainnet needs a fresh authentication, as487 /// `setNetworkMode(.main)` does). A test network is also recorded as the test network Bitcoin uses in test mode.488 ///489 /// Kept for the 1.0 screens. It moves the primary Bitcoin network only: `setNetworkMode` and `setTestNetwork`490 /// are the multi-chain way, and they keep every chain on the same side (test or main).491 public func setBitcoinNetwork(_ network: BitcoinNetwork) async throws(WalletError) {492 try await run {493 try requireAllowed(network)494 guard Self.isPrimaryUTXO(network) else {495 throw WalletError.invalidInput("\(network.displayName) is not a Bitcoin network: enable its chain instead.")496 }497 guard network != profile.bitcoinNetwork else {498 if network.isTest { profile.testNetworks[ChainID.bitcoin.rawValue] = ChainRegistry.id(network) }499 return500 }501 // leaving the test networks is the same decision as `setNetworkMode(.main)`: same authentication (QYV-SVC-080)502 if !network.isTest, profile.bitcoinNetwork.isTest { try await requireFreshAuthentication() }503 if network.isTest { profile.testNetworks[ChainID.bitcoin.rawValue] = ChainRegistry.id(network) }504 profile.bitcoinNetwork = network505 bitcoinSnapshot = nil506 bitcoinError = nil507 paidScripts = []508 locallySpent = []509 forgetBitcoinSynchronization()510 try saveProfile()511 }512 }513514 /// Switches the primary EVM network: the one `WalletSnapshot.ethereum` and the 1.0 Ethereum screens show. Its515 /// chain is enabled if it was not. A main network throws `mainnetDisabled` unless mainnet is enabled; with a full516 /// wallet, moving from a test network to a main one needs a fresh authentication (`authenticationRequired`).517 public func setEthereumNetwork(_ network: EthereumNetwork) async throws(WalletError) {518 try await run {519 try requireAllowed(network)520 guard network != profile.ethereumNetwork else { return }521 // leaving the test networks is the same decision as `setNetworkMode(.main)`: same authentication (QYV-SVC-080)522 if !network.isTest, profile.ethereumNetwork.isTest { try await requireFreshAuthentication() }523 profile.ethereumNetwork = network524 let main = ChainRegistry.id(network.mainCounterpart)525 if !profile.enabledChains.contains(main) { profile.enabledChains.append(main) }526 reconcileChainState()527 try saveProfile()528 }529 }530531 /// Replaces the Bitcoin, EVM and price endpoints (`setChainEndpoints` replaces every chain's at once). Every URL532 /// must pass `EndpointConfiguration.isAcceptable` (https, or http to a local host); an empty price API or indexer533 /// list disables that feature. Chain identity is checked again on next use.534 /// With a full wallet this needs a fresh authentication (`authenticationRequired`): the endpoints decide what the535 /// wallet is shown and where its requests go.536 public func setEndpoints(_ endpoints: EndpointConfiguration) async throws(WalletError) {537 try await run { try await applyEndpoints(core: endpoints, solana: profile.solanaEndpoints, tron: profile.tronEndpoints) }538 }539540 /// Validates and stores the three endpoint sets, and forgets what was persisted for a chain whose endpoints changed541 /// (it was read from other hosts).542 func applyEndpoints(core endpoints: EndpointConfiguration, solana: SolanaEndpoints, tron: TronEndpoints) async throws {543 let changed = endpoints != profile.endpoints || solana != profile.solanaEndpoints || tron != profile.tronEndpoints544 if changed { try await requireFreshAuthentication() }545 var all = [String]()546 for list in Self.utxoEndpointLists(endpoints) { all += list }547 for list in endpoints.ethereumRPC.values { all += list }548 for list in endpoints.ethereumIndexer.values { all += list }549 if !endpoints.priceAPI.isEmpty { all.append(endpoints.priceAPI) }550 if !endpoints.priceCheckAPI.isEmpty { all.append(endpoints.priceCheckAPI) }551 for list in solana.rpc.values { all += list }552 for list in tron.fullNodes.values { all += list }553 for list in tron.history.values { all += list }554 for url in all where !EndpointConfiguration.isAcceptable(url) {555 throw WalletError.invalidInput("Endpoint not accepted (https required, http only for local hosts): \(url)")556 }557 // the second price source exists to contradict the first: the same host cannot do that (QYV-SVC-087)558 guard !PriceClient.sourcesShareHost(endpoints) else {559 throw WalletError.invalidInput("The second price source must be another host than the price API: it exists to cross-check it.")560 }561 guard all.count <= 400, all.allSatisfy({ $0.utf8.count <= 300 }) else {562 throw WalletError.invalidInput("Too many endpoints, or an endpoint that is too long.")563 }564 let known = Set(BitcoinNetwork.allCases.map(\.rawValue)), knownEth = Set(EthereumNetwork.allCases.map(\.rawValue))565 let knownSolana = Set(SolanaNetwork.allCases.map(\.rawValue)), knownTron = Set(TronNetwork.allCases.map(\.rawValue))566 guard Self.utxoEndpointKeys(endpoints).isSubset(of: known), Set(endpoints.ethereumRPC.keys).isSubset(of: knownEth),567 Set(endpoints.ethereumIndexer.keys).isSubset(of: knownEth), Set(solana.rpc.keys).isSubset(of: knownSolana),568 Set(tron.fullNodes.keys).isSubset(of: knownTron), Set(tron.history.keys).isSubset(of: knownTron) else {569 throw WalletError.invalidInput("Unknown network name in the endpoint configuration.")570 }571 // what was persisted was read from the previous endpoints: it is not carried over to other ones572 // a price read from other hosts is not a price of the new ones573 if endpoints.priceAPI != profile.endpoints.priceAPI || endpoints.priceCheckAPI != profile.endpoints.priceCheckAPI {574 priceChecks = [:]575 market.quotes["usd"] = nil576 }577 var next = profile578 next.endpoints = endpoints579 next.solanaEndpoints = solana580 next.tronEndpoints = tron581 if Self.bitcoinIdentity(next) != Self.bitcoinIdentity(profile) { forgetBitcoinSynchronization() }582 for network in EthereumNetwork.allCases where Self.ethereumIdentity(next, network: network) != Self.ethereumIdentity(profile, network: network) {583 if evmSnapshots[network] != nil || network == profile.ethereumNetwork { forgetEVMSynchronization(network) }584 }585 for network in BitcoinNetwork.allCases where !Self.isPrimaryUTXO(network) && Self.utxoCoinIdentity(next, network: network) != Self.utxoCoinIdentity(profile, network: network) {586 forgetUTXOCoinSynchronization(network)587 }588 for network in SolanaNetwork.allCases where Self.solanaIdentity(next, network: network) != Self.solanaIdentity(profile, network: network) {589 if solanaRecords[network] != nil { SyncStore.remove(from: fileStore, name: SolanaChainRecord.fileName(network)) }590 }591 for network in TronNetwork.allCases where Self.tronIdentity(next, network: network) != Self.tronIdentity(profile, network: network) {592 if tronRecords[network] != nil { SyncStore.remove(from: fileStore, name: TronChainRecord.fileName(network)) }593 }594 profile = next595 gate.setAlternatives(Self.endpointGroups(profile))596 verifiedChains = []597 try saveProfile()598 }599600 static func utxoEndpointKeys(_ endpoints: EndpointConfiguration) -> Set<String> {601 Set(endpoints.esplora.keys).union(endpoints.blockbook.keys).union(endpoints.bitcore.keys)602 }603604 /// Switches both primary networks at once. A mainnet is refused (`mainnetDisabled`) unless `MainnetPolicy.mainnetEnabled`605 /// is true at the time of the call.606 public func setActiveNetworks(bitcoin: BitcoinNetwork, ethereum: EthereumNetwork) async throws(WalletError) {607 try await run {608 try requireAllowed(bitcoin)609 try requireAllowed(ethereum)610 }611 try await setBitcoinNetwork(bitcoin)612 try await setEthereumNetwork(ethereum)613 }614615 /// Records the user's choice to use mainnet and applies it to `MainnetPolicy` (together with what the build declared616 /// at creation). The choice alone enables nothing on a build that does not allow mainnet. Turning it off moves617 /// every chain back to its test network (`networkMode` becomes `.test`). Turning it on changes no network: call618 /// `setNetworkMode(.main)` next. Returns `MainnetPolicy.mainnetEnabled` after the change.619 /// Switching it on with a full wallet needs a fresh authentication (`authenticationRequired`).620 @discardableResult621 public func setMainnetOptIn(_ enabled: Bool) async throws(WalletError) -> Bool {622 try await run {623 if enabled, !profile.mainnetOptIn { try await requireFreshAuthentication() }624 profile.mainnetOptIn = enabled625 MainnetPolicy.configure(internalBuildAllowsMainnet: internalBuildAllowsMainnet, userOptedIn: enabled)626 if !MainnetPolicy.mainnetEnabled { applyNetworkMode(.test) }627 try saveProfile()628 return MainnetPolicy.mainnetEnabled629 }630 }631632 // MARK: Limits of an unaudited build on mainnet633634 static func bitcoinLimitText() -> String {635 BaseUnits.format(UInt256(MainnetPolicy.limits.bitcoinSatoshisPerTransaction), decimals: 8) + " BTC"636 }637638 /// Throws when real bitcoin above the ceiling would leave in one transaction of an unaudited build.639 func enforceUnauditedBitcoinLimit(network: BitcoinNetwork, amount: UInt64, sendMax: Bool = false) throws {640 guard network == .mainnet, MainnetPolicy.unauditedMainnet else { return }641 guard amount <= MainnetPolicy.limits.bitcoinSatoshisPerTransaction else {642 throw WalletError.exceedsUnauditedLimit(limit: Self.bitcoinLimitText() + (sendMax ? " per transaction (sending everything is above it)" : " per transaction"))643 }644 }645646 /// Fee ceilings of an unaudited build on mainnet (QYV-SVC-009): the value ceilings alone would let a hostile fee647 /// estimate, or a defect in the fee arithmetic, burn many times the amount they are meant to bound.648 /// `vsize` is the (estimated) virtual size the fee pays for.649 func enforceUnauditedBitcoinFeeLimit(network: BitcoinNetwork, fee: UInt64, vsize: Int) throws {650 guard network == .mainnet, MainnetPolicy.unauditedMainnet else { return }651 let limits = MainnetPolicy.limits652 guard fee <= limits.bitcoinFeeSatoshisPerTransaction else {653 throw WalletError.exceedsUnauditedLimit(limit: "a fee of \(limits.bitcoinFeeSatoshisPerTransaction) sat per transaction")654 }655 let (ceiling, overflow) = limits.bitcoinFeeRateSatPerVByte.multipliedReportingOverflow(by: UInt64(max(vsize, 1)))656 guard overflow || fee <= ceiling else {657 throw WalletError.exceedsUnauditedLimit(limit: "a fee rate of \(limits.bitcoinFeeRateSatPerVByte) sat/vB")658 }659 }660661 /// The highest fee rate the wallet accepts on the given network right now, in sat/vB.662 public static func bitcoinFeeRateCeiling(_ network: BitcoinNetwork) -> UInt64 {663 network == .mainnet && MainnetPolicy.unauditedMainnet ? min(bitcoinMaximumFeeRate, MainnetPolicy.limits.bitcoinFeeRateSatPerVByte) : bitcoinMaximumFeeRate664 }665666 /// Restores the built-in endpoints of every chain.667 public func resetEndpoints() async throws(WalletError) {668 try await run { try await applyEndpoints(core: .default, solana: .default, tron: .default) }669 }670671 public func setDisplayCurrency(_ currency: DisplayCurrency) async throws(WalletError) {672 try await run {673 profile.displayCurrency = currency674 try saveProfile()675 }676 }677678 /// The policy the service applies for a stored one: "never" becomes the default five minutes and a delay is capped679 /// at `maximumAutoLockDelay`.680 static func boundedAutoLock(_ policy: AutoLockPolicy) -> AutoLockPolicy {681 switch policy {682 case .immediately: return .immediately683 case .never: return .after(seconds: 300)684 case .after(let seconds): return .after(seconds: seconds.isFinite ? min(max(seconds, 5), maximumAutoLockDelay) : 300)685 }686 }687688 /// Seconds an unlocked vault may stay idle under `policy` (0 for "immediately").689 static func autoLockDelay(_ policy: AutoLockPolicy) -> TimeInterval {690 switch policy {691 case .immediately: return 0692 case .after(let seconds): return seconds693 case .never: return .infinity694 }695 }696697 /// Sets when the vault locks by itself: `.immediately`, or `.after` a delay of 5 seconds to `maximumAutoLockDelay`698 /// (15 minutes). `.never` and longer delays are refused with `invalidInput` (QYV-APP-004). Making the policy more699 /// permissive with a full wallet needs a fresh authentication (`authenticationRequired`).700 public func setAutoLockPolicy(_ policy: AutoLockPolicy) async throws(WalletError) {701 try await run {702 if case .never = policy {703 throw WalletError.invalidInput("The auto-lock cannot be switched off: the longest delay is \(Int(Self.maximumAutoLockDelay / 60)) minutes.")704 }705 if case .after(let seconds) = policy {706 guard seconds.isFinite, seconds >= 5 else { throw WalletError.invalidInput("The auto-lock delay must be at least five seconds.") }707 guard seconds <= Self.maximumAutoLockDelay else {708 throw WalletError.invalidInput("The auto-lock delay cannot exceed \(Int(Self.maximumAutoLockDelay / 60)) minutes.")709 }710 }711 if Self.autoLockDelay(policy) > Self.autoLockDelay(profile.autoLock) { try await requireFreshAuthentication() }712 profile.autoLock = policy713 try saveProfile()714 }715 }716717 /// Cold mode: when on, the service performs no network call at all (every request fails with `.offline` before it718 /// leaves the device). Creation, import, address display and signing keep working.719 public func setColdMode(_ enabled: Bool) async throws(WalletError) {720 try await run {721 profile.coldMode = enabled722 gate.setOffline(enabled)723 try saveProfile()724 }725 }726727 /// Sets or clears (nil or empty) the label of an address.728 public func setAddressLabel(_ label: String?, for address: String) async throws(WalletError) {729 try await run {730 guard !address.isEmpty, address.utf8.count <= 100 else { throw WalletError.invalidInput("This is not an address a label can be attached to.") }731 let trimmed = label?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""732 profile.addressLabels[address] = trimmed.isEmpty ? nil : String(trimmed.prefix(80))733 // the snapshot carries the labels of its addresses and coins: keep it in step with the profile734 if let snapshot = bitcoinSnapshot { bitcoinSnapshot = snapshot.refreshed(profile: profile) }735 for (network, state) in utxoCoinStates { utxoCoinStates[network]?.snapshot = state.snapshot?.refreshed(profile: profile) }736 try saveProfile()737 }738 }739740 /// Coin control: a frozen output is never selected automatically.741 public func setFrozen(_ frozen: Bool, outPoint: BitcoinOutPoint) async throws(WalletError) {742 try await run {743 var set = Set(profile.frozenUTXOs)744 if frozen { set.insert(outPoint.description) } else { set.remove(outPoint.description) }745 profile.frozenUTXOs = set.sorted()746 if let snapshot = bitcoinSnapshot { bitcoinSnapshot = snapshot.refreshed(profile: profile) }747 for (network, state) in utxoCoinStates { utxoCoinStates[network]?.snapshot = state.snapshot?.refreshed(profile: profile) }748 try saveProfile()749 }750 }751752 /// Test support (`@testable import`): puts other account public data in the profile in memory, as a modified753 /// profile file would at the next launch.754 func replaceAccountDataForTesting(_ data: PublicData) {755 profile.bitcoinAccounts = data.accounts756 profile.ethereumAddress = data.ethereum757 if let solana = data.solana { profile.solanaAddress = solana }758 if let tron = data.tron { profile.tronAddress = tron }759 }760761 /// Number of times, in this session, the account public keys of the profile file were found different from the762 /// ones the vault holds and were restored from the vault (QYV-SVC-011). Zero on an untouched installation.763 public func accountBindingRepairCount() -> Int { accountBindingRepairs }764765 /// Requests sent to the network since the service was created (diagnostics; cold mode keeps it at its value).766 public func networkRequestCount() -> Int { gate.requestCount }767}768769/// How the recovery phrase is stored in a vault record: the words in lower case separated by single spaces, UTF-8.770/// The BIP-39 passphrase record holds the passphrase as NFKD UTF-8.771enum PhraseCodec {772 static func payload(_ words: [String]) -> Bytes { Bytes(words.joined(separator: " ").utf8) }773 static func words(_ payload: Bytes) -> [String] { BIP39.words(from: String(decoding: payload, as: UTF8.self)) }774775 /// True when the payload is exactly the stored form: words of lower-case ASCII letters separated by single spaces.776 /// Such bytes are what BIP-39 hashes (NFKD changes nothing in them), so the seed can be computed from them777 /// without building a `String`.778 static func isNormalized(_ payload: Bytes) -> Bool {779 guard let first = payload.first, let last = payload.last, first != 0x20, last != 0x20 else { return false }780 var previousWasSpace = false781 for b in payload {782 if b == 0x20 {783 if previousWasSpace { return false }784 previousWasSpace = true785 } else {786 guard b >= 0x61, b <= 0x7a else { return false }787 previousWasSpace = false788 }789 }790 return true791 }792}793794extension BitcoinSnapshot {795 /// The same snapshot with labels and frozen flags taken again from the profile.796 func refreshed(profile: WalletProfile) -> BitcoinSnapshot {797 let frozen = Set(profile.frozenUTXOs)798 func relabel(_ a: WalletAddress) -> WalletAddress {799 WalletAddress(address: a.address, chain: a.chain, index: a.index, path: a.path, isUsed: a.isUsed, transactionCount: a.transactionCount,800 balance: a.balance, isReused: a.isReused, exposure: a.exposure, label: profile.addressLabels[a.address])801 }802 return BitcoinSnapshot(803 network: network, tipHeight: tipHeight, synchronizedAt: synchronizedAt, balance: balance,804 utxos: utxos.map {805 WalletUTXO(utxo: $0.utxo, exposure: $0.exposure, exposureExplanation: $0.exposureExplanation,806 isFrozen: frozen.contains($0.utxo.outPoint.description), label: $0.utxo.address.flatMap { profile.addressLabels[$0] })807 },808 transactions: transactions, addresses: addresses.map(relabel), receiveAddress: relabel(receiveAddress),809 reusedAddresses: reusedAddresses.map(relabel), historyTruncated: historyTruncated, notes: notes, activity: activity,810 isFromPreviousSession: isFromPreviousSession)811 }812}813