SPB Git

Repository Public

WalletService+UTXOCoins.swift 65.3 KB 1,053 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraWallet/WalletService+UTXOCoins.swift8// Module           : Qyvora Wallet9// Repository       : https://git.spboucher.ai/qyvora10// Project Website  : Not specified11// Created          : 2026-12-0512// Last Modified    : 2026-12-0513//14// Author           : Simon-Pierre Boucher15// Position         : Professor of Finance16// Institution      : Université du Québec en Outaouais (UQO)17// Organization     : SP Boucher18// Website          : https://spboucher.ai19// Git              : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development      : dev@spboucher.ai23// Support          : support@spboucher.ai24// Security/Admin   : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License          : None specified (no license file in this repository)33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import Foundation42import QyvoraMath43import QyvoraCore44import QyvoraBitcoin45import QyvoraNetworking46import QyvoraStorage4748// Litecoin, Dogecoin and Bitcoin Cash. Bitcoin itself keeps its own path (WalletService+Bitcoin.swift: one primary49// network, Esplora, a persisted cache). The coins here go through the `UTXOIndexer` protocol (Esplora, Blockbook or50// Bitcore, whichever the configuration has for the network), each network with its own state, and produce the same51// public types: `BitcoinSnapshot`, `BitcoinSendPlan`, `BitcoinFeeOptions`.52//53// Not persisted between launches: after a restart a coin is `.notLoaded` until it is synchronized again.5455/// State of one UTXO coin network in this session.56struct UTXOCoinState: Sendable {57    var snapshot: BitcoinSnapshot?58    var error: String?59    /// Scripts this wallet paid (address-reuse and first-payment warnings).60    var paidScripts: Set<Bytes> = []61    /// Outputs spent by a transaction broadcast in this session, until the next synchronization.62    var locallySpent: Set<BitcoinOutPoint> = []63}6465/// What the indexer said about one address of the account.66private struct CoinScan: Sendable {67    let chain: UTXOAccount.Chain68    let index: UInt3269    let address: BitcoinAddress70    let stats: UTXOAddressStats71    var coins: [UTXOIndexerCoin] = []72    var transactions: [UTXOIndexerTransaction] = []73    /// The history has more pages than were read, or the indexer says its view of the address is partial.74    var truncated = false75}7677/// What the last synchronization of a coin network (Litecoin, Dogecoin, Bitcoin Cash) read from its indexer, kept78/// between launches like the other chains (public chain data only: see SyncPersistence.swift). One file per network.79///80/// It holds what the indexer said about each scanned address, not the snapshot: at the next launch the snapshot is81/// rebuilt from it through the same validation as after a synchronization, and flagged as coming from the previous82/// session. The next synchronization reads everything again (no incremental reuse of this record).83struct UTXOCoinSyncRecord: Codable, Equatable, Sendable {84    static let currentVersion = 185    /// A larger record is not written (the coin then shows nothing until its first synchronization of the launch).86    static let maximumBytes = 24 << 2087    static func fileName(_ network: BitcoinNetwork) -> String { "utxo-sync-\(network.rawValue).json" }8889    struct Coin: Codable, Equatable, Sendable {90        var txid: String91        var vout: UInt3292        var value: UInt6493        var height: Int?94        var isCoinbase: Bool?95    }9697    struct Output: Codable, Equatable, Sendable {98        var address: String?99        var scriptPubKey: String?100        var value: UInt64101    }102103    struct Input: Codable, Equatable, Sendable {104        var txid: String?105        var vout: UInt32?106        var previous: Output?107        var sequence: UInt32?108    }109110    struct Transaction: Codable, Equatable, Sendable {111        var txid: String112        var inputs: [Input]113        var outputs: [Output]114        var fee: UInt64?115        var virtualSize: Int?116        var height: Int?117        var time: Int?118    }119120    struct Entry: Codable, Equatable, Sendable {121        var chain: UInt32122        var index: UInt32123        /// The address the wallet derived for this position; checked again against the account when restored.124        var address: String125        var isUsed: Bool126        var hasSpent: Bool127        var transactionCount: Int?128        var confirmedBalance: UInt64?129        var isComplete: Bool130        var coins: [Coin]131        var transactions: [Transaction]132        var truncated: Bool133    }134135    var version = currentVersion136    /// `WalletService.utxoCoinIdentity`: network, account key and endpoint lists this data was read for.137    var identity: String138    var network: BitcoinNetwork139    var synchronizedAt: Date140    var tipHeight: UInt32141    var notes: [String]142    var entries: [Entry]143}144145extension WalletService {146    // MARK: Persistence between launches147148    /// What a persisted coin synchronization belongs to: the network, the account key and every indexer list.149    static func utxoCoinIdentity(_ profile: WalletProfile, network: BitcoinNetwork) -> String? {150        guard profile.kind != nil, !isPrimaryUTXO(network), let account = profile.bitcoinAccounts[accountKey(network)] else { return nil }151        let e = profile.endpoints, name = network.rawValue152        let lists = [e.esplora[name] ?? [], e.blockbook[name] ?? [], e.bitcore[name] ?? []].map { $0.joined(separator: ",") }.joined(separator: "|")153        return "utxo|v\(UTXOCoinSyncRecord.currentVersion)|\(name)|\(account.extendedPublicKey)|\(lists)"154    }155156    fileprivate static func coinRecord(identity: String, network: BitcoinNetwork, synchronizedAt: Date, tip: UInt32, notes: [String], scans: [CoinScan]) -> UTXOCoinSyncRecord {157        func output(_ c: UTXOIndexerTransaction.Coin) -> UTXOCoinSyncRecord.Output { .init(address: c.address, scriptPubKey: c.scriptPubKey, value: c.value) }158        let entries = scans.map { s in159            UTXOCoinSyncRecord.Entry(160                chain: s.chain.rawValue, index: s.index, address: s.address.string, isUsed: s.stats.isUsed, hasSpent: s.stats.hasSpent,161                transactionCount: s.stats.transactionCount, confirmedBalance: s.stats.confirmedBalance, isComplete: s.stats.isComplete,162                coins: s.coins.map { .init(txid: $0.txid, vout: $0.vout, value: $0.value, height: $0.height, isCoinbase: $0.isCoinbase) },163                transactions: s.transactions.map { t in164                    .init(txid: t.txid, inputs: t.inputs.map { .init(txid: $0.txid, vout: $0.vout, previous: $0.previous.map(output), sequence: $0.sequence) },165                          outputs: t.outputs.map(output), fee: t.fee, virtualSize: t.virtualSize, height: t.height, time: t.time)166                },167                truncated: s.truncated)168        }169        return UTXOCoinSyncRecord(identity: identity, network: network, synchronizedAt: synchronizedAt, tipHeight: tip, notes: notes, entries: entries)170    }171172    /// The scans a record holds, each address derived again from the account: a record whose addresses are not the173    /// account's is refused.174    fileprivate static func coinScans(_ record: UTXOCoinSyncRecord, account: UTXOAccount) throws -> [CoinScan] {175        func coin(_ o: UTXOCoinSyncRecord.Output) -> UTXOIndexerTransaction.Coin { .init(address: o.address, scriptPubKey: o.scriptPubKey, value: o.value) }176        guard record.entries.count <= 2 * Int(maximumScanIndex) else { throw WalletError.untrustedResponse("persisted scan too long") }177        return try record.entries.map { e in178            guard let chain = UTXOAccount.Chain(rawValue: e.chain), e.index < maximumScanIndex else { throw WalletError.untrustedResponse("persisted address position") }179            let address = try account.address(chain: chain, index: e.index)180            guard address.string == e.address else { throw WalletError.untrustedResponse("persisted address") }181            var scan = CoinScan(chain: chain, index: e.index, address: address,182                                stats: UTXOAddressStats(address: address.stringWithoutPrefix, isUsed: e.isUsed, hasSpent: e.hasSpent, transactionCount: e.transactionCount,183                                                        confirmedBalance: e.confirmedBalance, isComplete: e.isComplete))184            scan.coins = e.coins.map { UTXOIndexerCoin(txid: $0.txid, vout: $0.vout, value: $0.value, height: $0.height, isCoinbase: $0.isCoinbase) }185            scan.transactions = e.transactions.map { t in186                UTXOIndexerTransaction(txid: t.txid, inputs: t.inputs.map { .init(txid: $0.txid, vout: $0.vout, previous: $0.previous.map(coin), sequence: $0.sequence) },187                                       outputs: t.outputs.map(coin), fee: t.fee, virtualSize: t.virtualSize, height: t.height, time: t.time)188            }189            scan.truncated = e.truncated190            return scan191        }192    }193194    /// The state of a coin network as of the previous session, when a record exists for exactly this account, network195    /// and endpoints and still passes the validation of a synchronization. Anything else is removed.196    static func restoredUTXOCoin(fileStore: FileStore, profile: WalletProfile, network: BitcoinNetwork) -> UTXOCoinState? {197        let name = UTXOCoinSyncRecord.fileName(network)198        guard fileStore.exists(name) else { return nil }199        guard let identity = utxoCoinIdentity(profile, network: network), MainnetPolicy.mainnetEnabled || network.isTest,200              let record = SyncStore.load(UTXOCoinSyncRecord.self, from: fileStore, name: name, maximumBytes: UTXOCoinSyncRecord.maximumBytes),201              record.version >= 1, record.version <= UTXOCoinSyncRecord.currentVersion, record.identity == identity, record.network == network,202              record.tipHeight < 100_000_000, record.notes.count <= 50,203              let data = profile.bitcoinAccounts[accountKey(network)],204              let account = try? UTXOAccount(extendedKey: data.extendedPublicKey, network: network, masterFingerprint: data.masterFingerprint.flatMap { Hex.decode($0) }),205              let scans = try? coinScans(record, account: account),206              let assembled = try? assembleUTXOCoin(account: account, tip: record.tipHeight, scans: scans, profile: profile, synchronizedAt: record.synchronizedAt,207                                                    notes: record.notes, fromPreviousSession: true) else {208            SyncStore.remove(from: fileStore, name: name)209            return nil210        }211        var state = UTXOCoinState()212        state.snapshot = assembled.snapshot213        // the scripts the file says were paid are not carried into the session: a synchronization adds to that set,214        // so a forged file would keep an address "already paid" and silence the first-payment warning of a payment215        // signed later (QYV-SVC-100). Nothing reads the set before a synchronization of this session.216        return state217    }218219    /// Removes what was persisted for a coin network (another account, other endpoints, or no wallet).220    func forgetUTXOCoinSynchronization(_ network: BitcoinNetwork) {221        SyncStore.remove(from: fileStore, name: UTXOCoinSyncRecord.fileName(network))222    }223224    // MARK: Account and indexers225226    /// The watch-only account of a coin network from public profile data (BIP-84 on Litecoin, BIP-44 on Dogecoin and227    /// Bitcoin Cash).228    func coinAccount(_ network: BitcoinNetwork) throws -> UTXOAccount {229        _ = try requireWallet()230        try requireAllowed(network)231        guard let data = profile.bitcoinAccounts[Self.accountKey(network)] else {232            throw WalletError.featureUnavailable("This wallet has no \(network.mainCounterpart.displayName) account for \(network.displayName).")233        }234        do {235            return try UTXOAccount(extendedKey: data.extendedPublicKey, network: network, masterFingerprint: data.masterFingerprint.flatMap { Hex.decode($0) })236        } catch {237            throw WalletError.storage("the stored \(network.mainCounterpart.displayName) account key is invalid")238        }239    }240241    /// Why a network cannot be synchronized, when no indexer is configured for it.242    static func noIndexerText(_ network: BitcoinNetwork) -> String {243        network.indexerAvailable244            ? "No indexer is configured for \(network.displayName)."245            : "\(network.displayName) cannot be synchronized: no keyless public indexer exists for this network. Addresses can be shown; balances, history and payments are not available unless you enter an indexer of your own in the settings."246    }247248    /// The indexer clients of a network whose chain identity was verified (once per session and per endpoint list):249    /// each one must serve the network's identity block. One that serves another chain fails everything250    /// (`wrongChain`); one that does not answer is left out; at least one must answer.251    func verifiedIndexers(_ network: BitcoinNetwork) async throws -> [any UTXOIndexer] {252        try requireAllowed(network)253        if gate.isOffline { throw WalletError.offline }254        let clients = UTXOIndexers.clients(for: network, configuration: profile.endpoints, transport: gate)255        guard !clients.isEmpty else { throw WalletError.featureUnavailable(Self.noIndexerText(network)) }256        var verified = [any UTXOIndexer]()257        var failures = [String]()258        for client in clients {259            let key = "utxo|\(network.rawValue)|\(client.indexerProtocol.rawValue)|" + client.hosts.joined(separator: ",")260            if verifiedChains.contains(key) {261                verified.append(client)262                continue263            }264            do {265                try await client.verifyChain()266                verifiedChains.insert(key)267                verified.append(client)268            } catch NetworkError.disagreement(let text) {269                throw WalletError.wrongChain(text)270            } catch let e as NetworkError {271                if case .offline = e { throw e }272                failures.append(e.summary)273            }274        }275        guard !verified.isEmpty else { throw WalletError.network(failures.joined(separator: "; ")) }276        return verified277    }278279    /// The verified client to read from: the one with the highest tip. A client that trails the best one by more than280    /// the confirmation depth of the network is not used, and a note says so.281    private func readingIndexer(_ network: BitcoinNetwork, notes: inout [String]) async throws -> (client: any UTXOIndexer, tip: UTXOChainTip) {282        let clients = try await verifiedIndexers(network)283        let survey = await UTXOIndexers.survey(clients)284        guard let best = survey.first, let tip = best.tip else {285            if gate.isOffline { throw WalletError.offline }286            throw WalletError.network("No indexer of \(network.displayName) answered.")287        }288        for s in survey.dropFirst() where s.isStale {289            notes.append("An indexer (\(s.client.hosts.joined(separator: ", "))) is \(s.lag.map { "\($0) blocks" } ?? "far") behind the others and was not used.")290        }291        // QYV-APP-061. Everything displayed is read from `best`. The other sources that are current must follow the292        // same chain (same hash for a block under the confirmation depth): a disagreement refuses the reading. When293        // no second source answers, one party decides what is shown, and the snapshot says so.294        let corroboration: UTXOIndexers.Corroboration295        do {296            corroboration = try await UTXOIndexers.corroborate(survey)297        } catch NetworkError.disagreement(let text) {298            throw WalletError.untrustedResponse(text + ". Nothing was read; check the endpoints in the settings")299        }300        let host = best.client.hosts.joined(separator: ", ")301        if corroboration.agreeing == 0 {302            notes.append(Self.singleIndexerNotePrefix + " (\(host)) " + (survey.count == 1303                ? "is configured for \(network.displayName)"304                : "of \(survey.count) gave a current view of \(network.displayName)")305                + ": balances, history and confirmations are its word alone, not confirmed by a second source. A source that lies can show a payment that does not exist; it cannot make this wallet sign or spend. Add an indexer of another protocol or operator in the settings before relying on an incoming payment.")306        } else {307            notes.append("\(corroboration.agreeing + 1) indexer sources of \(network.displayName) agree on the chain up to block \(corroboration.height). Balances and history are read from one of them (\(host)): the others confirm the chain, not each payment.")308        }309        return (best.client, tip)310    }311312    /// Start of the note of a snapshot read from an indexer no second source confirmed (QYV-APP-061): the screens313    /// recognise it to label what they show.314    public static let singleIndexerNotePrefix = "One indexer source"315316    // MARK: Synchronization317318    /// Synchronizes one coin network; a concurrent call joins the running one.319    @discardableResult320    func syncUTXOCoin(_ network: BitcoinNetwork) async throws -> BitcoinSnapshot {321        let kind = ChainKind.utxo(network)322        guard Self.activeKinds(profile).contains(kind) else { throw WalletError.chainNotActive(network.displayName) }323        if let running = utxoCoinSyncTasks[network] { return try await running.value }324        let task = Task { try await self.performUTXOCoinSync(network) }325        utxoCoinSyncTasks[network] = task326        noteSyncStarted(kind)327        do {328            let snapshot = try await task.value329            utxoCoinSyncTasks[network] = nil330            utxoCoinStates[network, default: UTXOCoinState()].error = nil331            noteSyncFinished(kind)332            return snapshot333        } catch {334            utxoCoinSyncTasks[network] = nil335            let wrapped = WalletError.wrap(error, now: now())336            let reason = Self.describe(wrapped)337            utxoCoinStates[network, default: UTXOCoinState()].error = reason338            noteSyncFailed(kind, reason: reason)339            throw wrapped340        }341    }342343    private func performUTXOCoinSync(_ network: BitcoinNetwork) async throws -> BitcoinSnapshot {344        let kind = ChainKind.utxo(network)345        let account = try coinAccount(network)346        var notes = [String]()347        noteProgress(kind, stage: "Checking the endpoints", completed: 0, total: nil)348        let (client, tip) = try await readingIndexer(network, notes: &notes)349        guard tip.height >= 0, tip.height < 100_000_000 else { throw WalletError.untrustedResponse("chain tip out of range") }350        let pages = historyPagesPerAddress351352        var scans = [CoinScan]()353        for chain in UTXOAccount.Chain.allCases {354            var next: UInt32 = 0355            var lastUsed: UInt32?356            // gap limit 20: stop after twenty unused addresses in a row357            while next < Self.maximumScanIndex, next < (lastUsed.map { $0 + 1 } ?? 0) + UTXOAccount.gapLimit {358                let end = min((lastUsed.map { $0 + 1 } ?? 0) + UTXOAccount.gapLimit, Self.maximumScanIndex)359                let batch = try (next..<end).map { ($0, try account.address(chain: chain, index: $0)) }360                noteProgress(kind, stage: "Scanning \(chain == .receive ? "receive" : "change") addresses", completed: scans.count, total: nil)361                let found = try await boundedMap(batch, limit: 3) { item -> CoinScan in362                    let (index, address) = item363                    // indexers take the address without its CashAddr prefix364                    let query = address.stringWithoutPrefix365                    do {366                        let stats = try await client.stats(address: query)367                        var scan = CoinScan(chain: chain, index: index, address: address, stats: stats)368                        guard stats.isUsed else { return scan }369                        scan.truncated = !stats.isComplete370                        scan.coins = try await client.coins(address: query)371                        var cursor: UTXOHistoryCursor?372                        var read = 0373                        repeat {374                            let page = try await client.history(address: query, cursor: cursor)375                            scan.transactions += page.transactions376                            cursor = page.next377                            read += 1378                        } while cursor != nil && read < pages379                        if cursor != nil { scan.truncated = true }380                        return scan381                    } catch {382                        throw Self.staged(error, "reading \(AddressScan.label(chain: chain, index: index, address: address.string))")383                    }384                }385                scans += found386                for s in found where s.stats.isUsed { lastUsed = max(lastUsed ?? 0, s.index) }387                next = end388            }389        }390391        let state = utxoCoinStates[network] ?? UTXOCoinState()392        let readAt = now()393        let assembled = try Self.assembleUTXOCoin(account: account, tip: UInt32(tip.height), scans: scans, profile: profile, synchronizedAt: readAt, notes: notes)394        guard profile.kind != nil, Self.activeKinds(profile).contains(kind), (try? coinAccount(network).extendedPublicKey(slip132: false)) == account.extendedPublicKey(slip132: false) else {395            throw WalletError.stalePlan("the active network changed during synchronization")396        }397        var updated = state398        updated.snapshot = assembled.snapshot399        updated.paidScripts.formUnion(assembled.paidScripts)400        updated.locallySpent = []401        utxoCoinStates[network] = updated402        // kept for the next launch: what the indexer said, to be validated again when it is read back403        if let identity = Self.utxoCoinIdentity(profile, network: network) {404            SyncStore.save(Self.coinRecord(identity: identity, network: network, synchronizedAt: readAt, tip: UInt32(tip.height), notes: notes, scans: scans),405                           to: fileStore, name: UTXOCoinSyncRecord.fileName(network), maximumBytes: UTXOCoinSyncRecord.maximumBytes)406        }407        profile.usedReceiveIndices[network.rawValue] = assembled.usedReceive408        profile.usedChangeIndices[network.rawValue] = Array(Set(assembled.usedChange + (profile.usedChangeIndices[network.rawValue] ?? []))).sorted()409        try? saveProfile()410        return assembled.snapshot411    }412413    /// One transaction of the indexer after validation. A coin whose script the indexer did not give (and whose414    /// address does not parse) has an empty script: it is never taken for one of the wallet's.415    private static func checkCoinTransaction(_ t: UTXOIndexerTransaction, network: BitcoinNetwork) throws -> CheckedTransaction {416        func bad(_ what: String) -> WalletError { .untrustedResponse("transaction \(t.txid.prefix(12))…: \(what)") }417        guard t.txid.utf8.count == 64, Hex.decode(t.txid) != nil, t.txid == t.txid.lowercased() else { throw WalletError.untrustedResponse("transaction identifier") }418        guard !t.inputs.isEmpty, t.inputs.count <= 25_000, !t.outputs.isEmpty, t.outputs.count <= 25_000 else { throw bad("input or output count") }419        let maximum = network.maximumMoney420        func coin(_ c: UTXOIndexerTransaction.Coin) throws -> CheckedTransaction.Coin {421            guard c.value <= maximum else { throw bad("amount out of range") }422            if let hex = c.scriptPubKey {423                guard hex.utf8.count <= BitcoinLimits.maxScriptSize * 2, let script = Hex.decode(hex) else { throw bad("script") }424                return .init(script: script, value: c.value)425            }426            if let text = c.address, let address = try? BitcoinAddress(text, network: network) { return .init(script: address.scriptPubKey, value: c.value) }427            return .init(script: [], value: c.value)428        }429        var outputs = [CheckedTransaction.Coin]()430        var total: UInt64 = 0431        for o in t.outputs {432            let c = try coin(o)433            let (sum, overflow) = total.addingReportingOverflow(c.value)434            guard !overflow, sum <= maximum else { throw bad("output total out of range") }435            total = sum436            outputs.append(c)437        }438        var inputs = [(outPoint: BitcoinOutPoint?, coin: CheckedTransaction.Coin?)]()439        var seen = Set<BitcoinOutPoint>()440        var inTotal: UInt64 = 0441        for i in t.inputs {442            guard let txid = i.txid, let vout = i.vout else {443                inputs.append((nil, nil))444                continue445            }446            guard vout < 100_000, let op = BitcoinOutPoint(txid: txid, vout: vout), seen.insert(op).inserted else { throw bad("input reference") }447            let c = try i.previous.map(coin)448            if let c {449                let (sum, overflow) = inTotal.addingReportingOverflow(c.value)450                guard !overflow, sum <= maximum else { throw bad("input total out of range") }451                inTotal = sum452            }453            inputs.append((op, c))454        }455        var height: UInt32?456        var time: Date?457        if let h = t.height {458            guard h >= 0, h < 100_000_000 else { throw bad("block height") }459            height = UInt32(h)460            if let s = t.time, s > 1_230_000_000, s < 10_000_000_000 { time = Date(timeIntervalSince1970: TimeInterval(s)) }461        }462        return CheckedTransaction(txid: t.txid, inputs: inputs, outputs: outputs, height: height, time: time,463                                  isCoinbase: t.inputs.count == 1 && t.inputs[0].txid == nil && t.inputs[0].previous == nil)464    }465466    /// Builds the snapshot of a coin from its address scans: the same rules as for Bitcoin (every transaction must467    /// involve the address it was listed for, coins are cross-checked against the history, sums are bounded by the468    /// monetary range of the network).469    private static func assembleUTXOCoin(account: UTXOAccount, tip: UInt32, scans: [CoinScan], profile: WalletProfile, synchronizedAt: Date,470                                         notes initial: [String], fromPreviousSession: Bool = false) throws -> AssembledBitcoin {471        let network = account.network472        let maximum = network.maximumMoney473        var notes = initial474        var scriptIndex = [Bytes: CoinScan]()475        for s in scans { scriptIndex[s.address.scriptPubKey] = s }476477        var transactions = [String: CheckedTransaction]()478        var perAddressCount = [Bytes: Int]()479        for s in scans {480            var seen = Set<String>()481            let script = s.address.scriptPubKey482            for raw in s.transactions {483                let checked = try checkCoinTransaction(raw, network: network)484                guard checked.outputs.contains(where: { $0.script == script }) || checked.inputs.contains(where: { $0.coin?.script == script }) else {485                    throw WalletError.untrustedResponse("transaction \(checked.txid.prefix(12))… does not involve the address it was listed for")486                }487                if let existing = transactions[checked.txid] {488                    guard existing.outputs.map(\.value) == checked.outputs.map(\.value), existing.outputs.map(\.script) == checked.outputs.map(\.script) else {489                        throw WalletError.untrustedResponse("two versions of transaction \(checked.txid.prefix(12))…")490                    }491                } else {492                    transactions[checked.txid] = checked493                }494                seen.insert(checked.txid)495            }496            perAddressCount[script] = seen.count497        }498499        var spentOutPoints = Set<BitcoinOutPoint>()500        for t in transactions.values { for i in t.inputs { if let op = i.outPoint { spentOutPoints.insert(op) } } }501        var utxos = [BitcoinUTXO]()502        var seenOutPoints = Set<BitcoinOutPoint>()503        var unspentTotal: UInt64 = 0504        for scan in scans where scan.stats.isUsed {505            guard scan.coins.count <= 5_000 else { throw WalletError.untrustedResponse("unspent output list too long") }506            let script = scan.address.scriptPubKey507            for c in scan.coins {508                guard c.vout < 100_000, let outPoint = BitcoinOutPoint(txid: c.txid, vout: c.vout), c.value > 0, c.value <= maximum else {509                    throw WalletError.untrustedResponse("unspent output out of range")510                }511                guard seenOutPoints.insert(outPoint).inserted else { throw WalletError.untrustedResponse("duplicate unspent output") }512                var confirmations: UInt32 = 0513                var coinbase = c.isCoinbase ?? false514                if let tx = transactions[outPoint.txid] {515                    let n = Int(c.vout)516                    guard n < tx.outputs.count, tx.outputs[n].value == c.value, tx.outputs[n].script == script || tx.outputs[n].script.isEmpty else {517                        throw WalletError.untrustedResponse("unspent output \(outPoint.txid.prefix(12))…:\(c.vout) disagrees with its transaction")518                    }519                    if let h = tx.height { confirmations = h <= tip ? tip - h + 1 : 1 }520                    coinbase = coinbase || tx.isCoinbase521                } else if scan.truncated {522                    // the funding transaction lies beyond what was read: take the indexer's height523                    if let h = c.height, h >= 0, h <= Int(tip) { confirmations = tip - UInt32(h) + 1 }524                } else {525                    notes.append("An unspent output reported for \(scan.address.string) is not in its history yet; it is left out until the next synchronization.")526                    continue527                }528                if spentOutPoints.contains(outPoint) {529                    notes.append("An output of \(scan.address.string) is already spent by a pending transaction; it is not counted.")530                    continue531                }532                let (sum, overflow) = unspentTotal.addingReportingOverflow(c.value)533                guard !overflow, sum <= maximum else { throw WalletError.untrustedResponse("unspent outputs exceed the monetary range") }534                unspentTotal = sum535                utxos.append(BitcoinUTXO(outPoint: outPoint, value: c.value, scriptPubKey: script, confirmations: confirmations, address: scan.address.string,536                                         derivation: .init(chain: scan.chain.rawValue, index: scan.index), isCoinbase: coinbase))537            }538        }539        utxos.sort { $0.outPoint.description < $1.outPoint.description }540541        var activity = [ScriptActivity]()542        var entries = [BitcoinHistoryEntry]()543        var paid = Set<Bytes>()544        for t in transactions.values {545            var received: UInt64 = 0, spent: UInt64 = 0, toOthers: UInt64 = 0546            var others = [String](), mine = [String]()547            var inputTotal: UInt64 = 0, outputTotal: UInt64 = 0548            var allInputsMine = !t.inputs.isEmpty, allInputsKnown = true549            for i in t.inputs {550                guard let coin = i.coin else {551                    allInputsMine = false552                    allInputsKnown = false553                    continue554                }555                inputTotal += coin.value556                if !coin.script.isEmpty, scriptIndex[coin.script] != nil {557                    spent += coin.value558                    activity.append(ScriptActivity(scriptPubKey: coin.script, kind: .spent, txid: t.txid, height: t.height))559                } else {560                    allInputsMine = false561                }562            }563            var otherScripts = [Bytes]()564            for o in t.outputs {565                outputTotal += o.value566                if !o.script.isEmpty, let scan = scriptIndex[o.script] {567                    received += o.value568                    mine.append(scan.address.string)569                    activity.append(ScriptActivity(scriptPubKey: o.script, kind: .funded, txid: t.txid, height: t.height))570                } else {571                    toOthers += o.value572                    if !o.script.isEmpty {573                        otherScripts.append(o.script)574                        if let a = try? BitcoinAddress(scriptPubKey: o.script, network: network) { others.append(a.string) }575                    }576                }577            }578            let fee: UInt64? = allInputsMine && allInputsKnown && inputTotal >= outputTotal ? inputTotal - outputTotal : nil579            let direction: BitcoinHistoryEntry.Direction580            let amount: UInt64581            if spent == 0 {582                direction = .received583                amount = received584            } else if allInputsMine && toOthers == 0 {585                direction = .selfTransfer586                amount = 0587            } else {588                direction = .sent589                amount = allInputsMine ? toOthers : (spent > received ? spent - received : 0)590                paid.formUnion(otherScripts)591            }592            let confirmations: UInt32 = t.height.map { $0 <= tip ? tip - $0 + 1 : 1 } ?? 0593            // both totals are within the monetary range of the network, which fits a signed 64-bit integer594            entries.append(BitcoinHistoryEntry(txid: t.txid, direction: direction, netAmount: Int64(received) - Int64(spent), amount: amount, fee: fee,595                                               confirmations: confirmations, blockHeight: t.height, time: t.time,596                                               counterpartyAddresses: direction == .sent ? others : [], walletAddresses: mine))597        }598        entries.sort {599            switch ($0.blockHeight, $1.blockHeight) {600            case (nil, nil): return $0.txid < $1.txid601            case (nil, _): return true602            case (_, nil): return false603            case (let a?, let b?): return a != b ? a > b : $0.txid < $1.txid604            }605        }606        activity.sort { ($0.txid, $0.kind.rawValue, Hex.encode($0.scriptPubKey)) < ($1.txid, $1.kind.rawValue, Hex.encode($1.scriptPubKey)) }607        // an address whose history was not read to the end may have older spends: its statistics say so608        let alreadySpent = Set(activity.filter { $0.kind == .spent }.map(\.scriptPubKey))609        for s in scans where s.truncated && !alreadySpent.contains(s.address.scriptPubKey) && s.stats.hasSpent {610            activity.append(ScriptActivity(scriptPubKey: s.address.scriptPubKey, kind: .spent, txid: "older-history", height: nil))611        }612613        let exposure = BitcoinPrivacyAnalysis.publicKeyExposure(utxos: utxos, activity: activity)614        let reuse = Set(BitcoinPrivacyAnalysis.addressReuse(activity: activity).map(\.scriptPubKey))615        let spentScripts = Set(activity.filter { $0.kind == .spent }.map(\.scriptPubKey))616        let frozen = Set(profile.frozenUTXOs)617        var balanceByScript = [Bytes: UInt64]()618        for u in utxos { balanceByScript[u.scriptPubKey, default: 0] += u.value }619        func walletAddress(_ s: CoinScan) -> WalletAddress {620            let script = s.address.scriptPubKey621            return WalletAddress(address: s.address.string, chain: s.chain, index: s.index, path: account.path(chain: s.chain, index: s.index).description,622                                 isUsed: s.stats.isUsed, transactionCount: perAddressCount[script] ?? 0, balance: balanceByScript[script] ?? 0,623                                 isReused: reuse.contains(script),624                                 exposure: BitcoinPrivacyAnalysis.publicKeyExposure(scriptPubKey: script, hasSpend: spentScripts.contains(script)).exposure,625                                 label: profile.addressLabels[s.address.string])626        }627        let usedReceive = Set(scans.filter { $0.chain == .receive && $0.stats.isUsed }.map(\.index))628        let usedChange = Set(scans.filter { $0.chain == .change && $0.stats.isUsed }.map(\.index))629        let nextIndex = account.nextUnusedIndex(used: usedReceive)630        let addresses = scans.filter { $0.chain == .receive ? $0.index <= nextIndex || $0.stats.isUsed : $0.stats.isUsed }631            .sorted { ($0.chain.rawValue, $0.index) < ($1.chain.rawValue, $1.index) }.map(walletAddress)632        let receive: WalletAddress633        if let s = scans.first(where: { $0.chain == .receive && $0.index == nextIndex }), !s.stats.isUsed {634            receive = walletAddress(s)635        } else {636            let a = try account.address(chain: .receive, index: nextIndex)637            receive = WalletAddress(address: a.string, chain: .receive, index: nextIndex, path: account.path(chain: .receive, index: nextIndex).description,638                                    isUsed: false, transactionCount: 0, balance: 0, isReused: false, exposure: .hashedUnrevealed, label: profile.addressLabels[a.string])639        }640        let walletUTXOs = utxos.map { u -> WalletUTXO in641            let a = exposure[u.outPoint] ?? BitcoinPrivacyAnalysis.publicKeyExposure(scriptPubKey: u.scriptPubKey, hasSpend: false)642            return WalletUTXO(utxo: u, exposure: a.exposure, exposureExplanation: a.explanation, isFrozen: frozen.contains(u.outPoint.description),643                              label: u.address.flatMap { profile.addressLabels[$0] })644        }645        let truncated = scans.contains(where: \.truncated)646        if truncated { notes.append("Some addresses have more history than the wallet reads, or the indexer gave a partial view of them; older transactions are not listed.") }647        let snapshot = BitcoinSnapshot(648            network: network, tipHeight: tip, synchronizedAt: synchronizedAt,649            balance: BitcoinBalance(confirmed: utxos.filter { $0.confirmations > 0 }.reduce(0) { $0 + $1.value },650                                    pending: utxos.filter { $0.confirmations == 0 }.reduce(0) { $0 + $1.value }),651            utxos: walletUTXOs, transactions: entries, addresses: addresses, receiveAddress: receive,652            reusedAddresses: scans.filter { reuse.contains($0.address.scriptPubKey) }.map(walletAddress), historyTruncated: truncated, notes: notes,653            activity: activity, isFromPreviousSession: fromPreviousSession)654        return AssembledBitcoin(snapshot: snapshot, paidScripts: paid, usedReceive: usedReceive.sorted(), usedChange: usedChange.sorted())655    }656657    // MARK: Receiving658659    /// The next receive address of a coin: from the snapshot, else one past the highest index known to be used.660    func nextCoinReceiveAddress(_ network: BitcoinNetwork) throws -> WalletAddress {661        if let snapshot = utxoCoinStates[network]?.snapshot { return snapshot.receiveAddress }662        let account = try coinAccount(network)663        let next = try account.nextUnusedAddress(chain: .receive, used: Set(profile.usedReceiveIndices[network.rawValue] ?? []))664        return WalletAddress(address: next.address.string, chain: .receive, index: next.index, path: account.path(chain: .receive, index: next.index).description,665                             isUsed: false, transactionCount: 0, balance: 0, isReused: false, exposure: .hashedUnrevealed,666                             label: profile.addressLabels[next.address.string])667    }668669    // MARK: Fees670671    /// The highest fee rate the wallet accepts on a coin network now: the network's own ceiling, lowered to the672    /// ceiling of an unaudited build on a main network.673    static func coinFeeRateCeiling(_ network: BitcoinNetwork) -> FeeRate {674        var ceiling = FeeRate.maximum(for: network)675        if MainnetPolicy.unauditedMainnet, let limits = MainnetPolicy.utxoLimits(network) { ceiling = min(ceiling, FeeRate(satPerVByte: limits.feeRatePerVByte)) }676        return ceiling677    }678679    /// Slow / normal / fast fee rates of a UTXO chain. **Network.** For Bitcoin this is `bitcoinFeeOptions()`. For the680    /// other coins: the indexer's estimates, kept between the network's floor and ceiling (`BitcoinNetwork.feePolicy`,681    /// and the ceiling of an unaudited build on a main network), in order slow ≤ normal ≤ fast. Dogecoin has no fee682    /// market to speak of: only targets of six blocks or more are read. Without a usable estimate every tier is the683    /// network's floor and `source` says so.684    public func feeOptions(chain id: ChainID) async throws(WalletError) -> BitcoinFeeOptions {685        try await run {686            guard case .utxo(let network) = try activeKind(id) else { throw WalletError.invalidInput("Fee rates of this kind exist on UTXO chains only.") }687            if Self.isPrimaryUTXO(network) { return try await bitcoinFeeOptions() }688            return try await coinFeeOptions(network)689        }690    }691692    func coinFeeOptions(_ network: BitcoinNetwork) async throws -> BitcoinFeeOptions {693        let floor = FeeRate.minimum(for: network), cap = max(floor, Self.coinFeeRateCeiling(network))694        func floorOptions() -> BitcoinFeeOptions {695            func opt(_ t: BitcoinFeeOption.Tier) -> BitcoinFeeOption { .init(tier: t, rate: floor, targetBlocks: nil) }696            return BitcoinFeeOptions(slow: opt(.slow), normal: opt(.normal), fast: opt(.fast), source: .minimumRelayFloor)697        }698        let clients = try await verifiedIndexers(network)699        var estimates = [Int: Double]()700        for client in clients {701            if let found = try? await client.feeEstimates(), !found.isEmpty {702                estimates = found703                break704            }705        }706        func pick(_ targets: [Int]) -> (FeeRate, Int)? {707            for t in targets {708                if let v = estimates[t], let r = FeeRate.fromEstimate(satPerVByte: v) { return (min(r.clamped(to: network), cap), t) }709            }710            return nil711        }712        let doge = network.coin == .dogecoin713        guard let fast = pick(doge ? [6, 8, 10] : [1, 2, 3]), let normal = pick(doge ? [6, 8, 10, 12, 25] : [6, 5, 4, 8, 10, 3]),714              let slow = pick(doge ? [144, 72, 25, 12, 6] : [144, 504, 72, 25, 1008, 20]) else { return floorOptions() }715        let n = min(normal.0, fast.0), s = min(slow.0, n)716        return BitcoinFeeOptions(slow: .init(tier: .slow, rate: s, targetBlocks: slow.1), normal: .init(tier: .normal, rate: n, targetBlocks: normal.1),717                                 fast: .init(tier: .fast, rate: fast.0, targetBlocks: fast.1), source: .estimates)718    }719720    // MARK: Limits721722    static func coinAmount(_ base: UInt64, _ network: BitcoinNetwork) -> String {723        BaseUnits.format(UInt256(base), decimals: network.decimals) + " " + network.ticker724    }725726    /// Ceilings of an unaudited build on the main network of a coin (`MainnetPolicy.utxoLimits`), applied when a727    /// payment is prepared and again before it is signed: the value sent (Litecoin, Dogecoin, Bitcoin Cash: 150 USD at728    /// a fresh price — without one the payment is refused), the absolute fee and the fee rate.729    func enforceUnauditedCoinLimits(network: BitcoinNetwork, amount: UInt64, fee: UInt64, vsize: Int) async throws {730        guard MainnetPolicy.unauditedMainnet, let limits = MainnetPolicy.utxoLimits(network) else { return }731        switch limits.value {732        case .baseUnits(let ceiling):733            guard amount <= ceiling else { throw WalletError.exceedsUnauditedLimit(limit: Self.coinAmount(ceiling, network) + " per transaction") }734        case .usd(let usd):735            guard let priceID = network.priceID else { throw WalletError.unauditedLimitUnverifiable("\(network.displayName) has no price, so the amount cannot be checked against the limit.") }736            let price = try await limitUSDPrice(priceID)737            guard let ceiling = MainnetPolicy.nativeCeiling(usd: usd, priceUSD: price, decimals: network.decimals) else {738                throw WalletError.unauditedLimitUnverifiable("The \(network.ticker) amount cannot be valued, so it cannot be checked against the limit.")739            }740            guard amount <= ceiling else {741                throw WalletError.exceedsUnauditedLimit(limit: "\(Int(usd)) USD of \(network.ticker) per transaction (\(Self.coinAmount(ceiling, network)) at the current price)")742            }743        }744        guard fee <= limits.feePerTransaction else {745            throw WalletError.exceedsUnauditedLimit(limit: "a fee of \(Self.coinAmount(limits.feePerTransaction, network)) per transaction")746        }747        let (ceiling, overflow) = limits.feeRatePerVByte.multipliedReportingOverflow(by: UInt64(max(vsize, 1)))748        guard overflow || fee <= ceiling else {749            throw WalletError.exceedsUnauditedLimit(limit: "a fee rate of \(limits.feeRatePerVByte) \(network.baseUnitName) per virtual byte")750        }751    }752753    // MARK: Sending754755    private func freshCoinSnapshot(_ network: BitcoinNetwork) throws -> BitcoinSnapshot {756        guard let snapshot = utxoCoinStates[network]?.snapshot, snapshot.network == network else {757            throw WalletError.notSynchronized("Synchronize \(network.displayName) before preparing or sending a payment.")758        }759        // a snapshot restored from the previous session is shown, never spent from: its coins may be gone760        guard !snapshot.isFromPreviousSession else {761            throw WalletError.notSynchronized("The \(network.displayName) balance shown is the one of the previous session. Synchronize before preparing or sending a transaction.")762        }763        return snapshot764    }765766    /// Builds a reviewable payment of a coin from its last snapshot. No secret. **Network** only for the price behind767    /// the limit of an unaudited build on a main network.768    func prepareCoinSend(network: BitcoinNetwork, to: String, amount: UInt64, feeRate: FeeRate, sendMax: Bool,769                         coinControl: BitcoinCoinControl, purpose: BitcoinSendPlan.Purpose = .payment) async throws -> BitcoinSendPlan {770        let account = try coinAccount(network)771        guard Self.activeKinds(profile).contains(.utxo(network)) else { throw WalletError.chainNotActive(network.displayName) }772        let snapshot = try freshCoinSnapshot(network)773        let state = utxoCoinStates[network] ?? UTXOCoinState()774        let destination: BitcoinAddress775        do {776            destination = try BitcoinAddress(to.trimmingCharacters(in: .whitespacesAndNewlines), network: network)777        } catch let e as BitcoinAddress.Error {778            throw WalletError.invalidAddress(Self.describe(e, network: network))779        }780        guard destination.type != .witnessUnknown else {781            throw WalletError.invalidAddress("This address uses a witness version without assigned meaning; QYVORA does not send to it.")782        }783        guard sendMax || amount > 0 else { throw WalletError.invalidInput("The amount is zero.") }784        guard feeRate <= Self.coinFeeRateCeiling(network) || feeRate <= FeeRate.minimum(for: network) else { throw WalletError.bitcoinBuild(.feeRateOutOfRange) }785786        let usedChange = Set(profile.usedChangeIndices[network.rawValue] ?? [])787        let change = try account.nextUnusedAddress(chain: .change, used: usedChange)788        let candidates = snapshot.utxos.map(\.utxo).filter { !state.locallySpent.contains($0.outPoint) }789        var request = BitcoinSpendRequest(790            network: network, recipients: sendMax ? [] : [BitcoinTransaction.Output(value: amount, scriptPubKey: destination.scriptPubKey)],791            utxos: candidates, feeRate: feeRate, changeScript: change.address.scriptPubKey, sendMaxScript: sendMax ? destination.scriptPubKey : nil)792        var frozen = Set<BitcoinOutPoint>()793        for u in snapshot.utxos where u.isFrozen && !coinControl.required.contains(u.utxo.outPoint) { frozen.insert(u.utxo.outPoint) }794        request.coinControl = .init(required: coinControl.required, useOnlyRequired: coinControl.useOnlyRequired, excluded: frozen,795                                    minimumConfirmations: coinControl.includeUnconfirmed ? 0 : 1)796        request.currentHeight = snapshot.tipHeight797        request.seed = transactionSeed798        let plan = try BitcoinTransactionBuilder.build(request)799        let paidAmount = sendMax ? (plan.sendMaxIndex.map { plan.transaction.outputs[$0].value } ?? 0) : amount800        try await enforceUnauditedCoinLimits(network: network, amount: paidAmount, fee: plan.fee, vsize: plan.estimatedVSize)801802        let exposureByOutPoint = Dictionary(uniqueKeysWithValues: snapshot.utxos.map { ($0.utxo.outPoint, $0.exposure) })803        let inputs = plan.inputs.map {804            BitcoinSendPlan.Input(outPoint: $0.outPoint, address: $0.address, value: $0.value, confirmations: $0.confirmations,805                                  exposure: exposureByOutPoint[$0.outPoint] ?? .undetermined)806        }807        let own = Dictionary(uniqueKeysWithValues: snapshot.addresses.map { ($0.address, $0) })808        var outputs = [BitcoinSendPlan.Output]()809        for (i, o) in plan.transaction.outputs.enumerated() {810            let text = (try? BitcoinAddress(scriptPubKey: o.scriptPubKey, network: network))?.string811            let isChange = i == plan.changeIndex812            let mine = isChange || (text.map { own[$0] != nil } ?? false) || account.locate(scriptPubKey: o.scriptPubKey, searchLimit: 40) != nil813            outputs.append(.init(index: i, address: text, value: o.value, isChange: isChange, isMine: mine))814        }815        var warnings = [BitcoinSendWarning]()816        if !network.isTest, MainnetPolicy.unauditedMainnet { warnings.append(.unauditedMainnet) }817        // a sweep goes to a fresh address of this wallet and spends exposed coins on purpose: the warnings about the818        // destination, the exposed inputs and the fee share are those of a payment819        if purpose == .payment {820            if let mine = own[destination.string] {821                warnings.append(.destinationIsOwnAddress)822                if mine.isUsed { warnings.append(.destinationReused) }823            } else if account.locate(scriptPubKey: destination.scriptPubKey, searchLimit: 40) != nil {824                warnings.append(.destinationIsOwnAddress)825            }826            if state.paidScripts.contains(destination.scriptPubKey) {827                warnings.append(.destinationAlreadyPaid)828            } else if !warnings.contains(.destinationIsOwnAddress) {829                warnings.append(.firstPaymentToAddress)830            }831        }832        let exposed = inputs.filter { $0.exposure == .revealedBySpend || $0.exposure == .revealedByScript }.count833        if exposed > 0, purpose == .payment { warnings.append(.exposedInputs(count: exposed)) }834        if purpose == .payment, paidAmount > 0 {835            let (scaled, overflow) = plan.fee.multipliedReportingOverflow(by: 10_000)836            let basisPoints = overflow ? Int.max : Int(min(scaled / paidAmount, UInt64(Int32.max)))837            if basisPoints > 500 { warnings.append(.highFeeShare(basisPoints: basisPoints)) }838        }839        if plan.changeIndex == nil, plan.sendMaxIndex == nil {840            let required = feeRate.fee(weight: plan.estimatedWeight)841            if plan.fee > required { warnings.append(.dustAddedToFee(amount: plan.fee - required)) }842        }843        let unconfirmed = inputs.filter { $0.confirmations == 0 }.count844        if unconfirmed > 0 { warnings.append(.unconfirmedInputs(count: unconfirmed)) }845        let distinct = Set(plan.inputs.map(\.scriptPubKey)).count846        if distinct > 1 { warnings.append(.mergesAddresses(count: distinct)) }847        return BitcoinSendPlan(id: UUID(), purpose: purpose, network: network, createdAt: now(), plan: plan, recipient: destination.string, amount: paidAmount,848                               fee: plan.fee, virtualSize: plan.estimatedVSize, targetFeeRate: feeRate, effectiveFeeRate: plan.effectiveFeeRate, inputs: inputs,849                               outputs: outputs, changeAddress: plan.changeIndex == nil ? nil : change.address.string, changeValue: plan.changeValue,850                               isSendMax: sendMax, warnings: warnings)851    }852853    /// Moves every output whose public key is already on chain to one fresh address of this wallet, on any active854    /// UTXO chain, as a normal reviewable plan (`purpose == .sweepExposed`). No secret; **network** only for the price855    /// behind the limit of an unaudited build on a main network. Needs a synchronization of the chain in this session.856    ///857    /// Bitcoin: the same plan as `prepareSweepOfExposedBitcoin`. Litecoin, Dogecoin, Bitcoin Cash: built like any858    /// payment of the coin, restricted to the exposed outputs and paid to a never-used address of the internal chain;859    /// it is signed on this device with `signAndBroadcast` (these coins have no cold signing). The limits of an860    /// unaudited build apply to it as to a payment: a sweep above the per-transaction limit is refused on a main network.861    /// Throws `invalidInput` when nothing is exposed, `featureUnavailable` when the coin's rotation is not enabled.862    public func prepareSweepOfExposed(chain id: ChainID, feeRate: FeeRate) async throws(WalletError) -> BitcoinSendPlan {863        guard let kind = ChainRegistry.kind(id), case .utxo(let network) = kind else {864            throw WalletError.invalidInput("Sweeping exposed coins exists on UTXO chains only.")865        }866        if Self.isPrimaryUTXO(network) {867            // the active Bitcoin network only: the plan is built for it868            guard network == profile.bitcoinNetwork else { throw WalletError.chainNotActive(network.displayName) }869            return try await prepareSweepOfExposedBitcoin(feeRate: feeRate)870        }871        return try await run {872            guard Self.activeKinds(profile).contains(kind) else { throw WalletError.chainNotActive(network.displayName) }873            let capability = Self.migrationChain(network) == .litecoin ? "ltc.rotation" : (Self.migrationChain(network) == .dogecoin ? "doge.rotation" : "bch.rotation")874            guard Self.isMigrationEnabled(capability) else { throw WalletError.featureUnavailable("Sweeping to fresh addresses is not available.") }875            let account = try coinAccount(network)876            let snapshot = try freshCoinSnapshot(network)877            let state = utxoCoinStates[network] ?? UTXOCoinState()878            let exposed = snapshot.utxos.filter {879                ($0.exposure == .revealedBySpend || $0.exposure == .revealedByScript) && !$0.isFrozen && !state.locallySpent.contains($0.utxo.outPoint)880            }881            guard !exposed.isEmpty else { throw WalletError.invalidInput("No output of this wallet sits behind a published key.") }882            // a never-used address of the internal chain: it was never shown to anyone883            let usedChange = Set(profile.usedChangeIndices[network.rawValue] ?? [])884            let fresh = try account.nextUnusedAddress(chain: .change, used: usedChange)885            return try await prepareCoinSend(network: network, to: fresh.address.string, amount: 0, feeRate: feeRate, sendMax: true,886                                             coinControl: BitcoinCoinControl(required: exposed.map(\.utxo.outPoint), useOnlyRequired: true, includeUnconfirmed: true),887                                             purpose: .sweepExposed)888        }889    }890891    /// Checks that a coin plan still fits the wallet, and applies the limits again on what will be signed.892    private func validateCoinPlan(_ plan: BitcoinSendPlan) async throws {893        let network = plan.network894        guard Self.activeKinds(profile).contains(.utxo(network)), plan.plan.network == network else {895            throw WalletError.stalePlan("The plan was made for \(network.displayName).")896        }897        let snapshot = try freshCoinSnapshot(network)898        let state = utxoCoinStates[network] ?? UTXOCoinState()899        let known = Dictionary(uniqueKeysWithValues: snapshot.utxos.map { ($0.utxo.outPoint, $0.utxo) })900        var inputTotal: UInt64 = 0901        guard plan.plan.inputs.count == plan.plan.transaction.inputs.count else { throw WalletError.stalePlan("inconsistent plan") }902        for (i, u) in plan.plan.inputs.enumerated() {903            guard plan.plan.transaction.inputs[i].previousOutput == u.outPoint, let current = known[u.outPoint], current.value == u.value,904                  current.scriptPubKey == u.scriptPubKey, !state.locallySpent.contains(u.outPoint) else {905                throw WalletError.stalePlan("An input of the plan is no longer available. Prepare the payment again.")906            }907            let (sum, overflow) = inputTotal.addingReportingOverflow(u.value)908            guard !overflow else { throw WalletError.stalePlan("inconsistent amounts") }909            inputTotal = sum910        }911        // the monetary range is the network's: Bitcoin's 21 million would refuse a legitimate Dogecoin or Litecoin912        // payment above that many coins (QYV-SVC-062)913        guard let outputTotal = plan.plan.transaction.outputValue(maximumMoney: network.maximumMoney), inputTotal >= outputTotal,914              inputTotal - outputTotal == plan.fee else {915            throw WalletError.stalePlan("inconsistent amounts")916        }917        // The output left out of the value ceiling must really be change: a script of this account's change chain.918        // Otherwise a plan whose "change" pays someone else would move any amount under the ceiling (QYV-SVC-063).919        if let c = plan.plan.changeIndex {920            let account = try coinAccount(network)921            // the change index is one past the highest used one, which a scan bounds by `maximumScanIndex`922            let limit = Self.maximumScanIndex + UTXOAccount.gapLimit923            guard plan.plan.transaction.outputs.indices.contains(c),924                  case let script = plan.plan.transaction.outputs[c].scriptPubKey,925                  (0..<limit).contains(where: { (try? account.scriptPubKey(chain: .change, index: $0)) == script }) else {926                throw WalletError.stalePlan("The change of the plan does not return to this wallet. Prepare the payment again.")927            }928        }929        // A sweep is reviewed as a move inside the wallet: every output must pay a script of this account's change930        // chain, whatever the plan object says about its recipient (QYV-SVC-101).931        if plan.purpose == .sweepExposed {932            let account = try coinAccount(network)933            let limit = Self.maximumScanIndex + UTXOAccount.gapLimit934            for output in plan.plan.transaction.outputs {935                guard (0..<limit).contains(where: { (try? account.scriptPubKey(chain: .change, index: $0)) == output.scriptPubKey }) else {936                    throw WalletError.stalePlan("The sweep does not pay an address of this wallet. Prepare it again.")937                }938            }939        }940        let recipients = plan.plan.transaction.outputs.enumerated().filter { $0.offset != plan.plan.changeIndex }.reduce(UInt64(0)) { $0 &+ $1.element.value }941        try await enforceUnauditedCoinLimits(network: network, amount: recipients, fee: plan.fee, vsize: plan.plan.estimatedVSize)942    }943944    /// The transactions that created the coins a plan spends, read from an indexer that serves raw transactions and945    /// accepted only when their bytes hash to the identifier asked for. Needed where the signed digest does not commit946    /// to the amounts (Dogecoin): without them an indexer could understate a coin and turn the difference into fee.947    func previousTransactions(for plan: BitcoinTransactionPlan, network: BitcoinNetwork) async throws -> [String: BitcoinTransaction] {948        let clients = try await verifiedIndexers(network).filter(\.servesRawTransactions)949        guard !clients.isEmpty else {950            throw WalletError.featureUnavailable("\(network.displayName) payments must be checked against the transactions that created the coins, and no configured indexer of this network serves raw transactions. Add one (Esplora or Blockbook) in the settings.")951        }952        var out = [String: BitcoinTransaction]()953        for txid in Set(plan.inputs.map(\.outPoint.txid)) {954            var found: BitcoinTransaction?955            var last: (any Error)?956            for client in clients {957                do {958                    let hex = try await client.rawTransaction(txid: txid)959                    guard let tx = try? BitcoinTransaction(hex: hex, allowWitness: network.supportsSegWit), tx.txid == txid else {960                        throw WalletError.untrustedResponse("the raw transaction served for \(txid.prefix(12))… does not hash to that identifier")961                    }962                    found = tx963                    break964                } catch {965                    last = error966                }967            }968            guard let found else { throw last ?? WalletError.network("raw transaction unavailable") }969            out[txid] = found970        }971        return out972    }973974    /// Signs a coin plan locally and broadcasts it through the network's indexer. The account derived for the975    /// signature must be the one the profile holds and the one the vault vouches for; every signature is verified976    /// under the network's signature scheme; the transaction signed must pay exactly what was reviewed; the identifier977    /// is computed locally and compared with the indexer's.978    func signAndBroadcastCoin(_ plan: BitcoinSendPlan) async throws -> BitcoinBroadcastResult {979        let network = plan.network980        let kind = ChainKind.utxo(network)981        try await validateCoinPlan(plan)982        let account = try coinAccount(network)983        let expectedKey = account.extendedPublicKey(slip132: false)984        if let trusted = await trustedPublicData(), trusted.accounts[Self.accountKey(network)]?.extendedPublicKey != profile.bitcoinAccounts[Self.accountKey(network)]?.extendedPublicKey {985            throw WalletError.signingFailed("The account of the profile is not the one the vault holds. Lock and unlock the wallet, then try again.")986        }987        let clients = try await verifiedIndexers(network)988        let previous = account.requiresPreviousTransactions ? try await previousTransactions(for: plan.plan, network: network) : [:]989        let signed: BitcoinTransaction = try await withMasterKey { master in990            var signer = try UTXOAccount(master: master, network: network)991            defer { signer.wipe() }992            guard signer.extendedPublicKey(slip132: false) == expectedKey else {993                throw WalletError.signingFailed("The recovery phrase in the vault does not match this wallet's account.")994            }995            do {996                return try signer.sign(plan: plan.plan, previousTransactions: previous)997            } catch BitcoinAccountError.unauthenticatedInput {998                throw WalletError.untrustedResponse("a coin of this payment does not match the transaction that created it; nothing was signed")999            } catch let e as BitcoinAccountError {1000                throw WalletError.signingFailed(e == .foreignInput(index: 0) ? "A coin of the plan does not belong to this account." : "The transaction could not be signed.")1001            }1002        }1003        do {1004            try BitcoinVerifier.verify(transaction: signed, spentOutputs: plan.plan.inputs.map(\.output), scheme: network.sighashScheme)1005        } catch {1006            throw WalletError.signingFailed("A signature does not verify.")1007        }1008        let reviewed = plan.plan.transaction1009        guard signed.outputs == reviewed.outputs, signed.lockTime == reviewed.lockTime, signed.inputs.map(\.previousOutput) == reviewed.inputs.map(\.previousOutput),1010              signed.inputs.map(\.sequence) == reviewed.inputs.map(\.sequence), !network.supportsSegWit || signed.txid == plan.txid else {1011            throw WalletError.signingFailed("The signed transaction differs from the reviewed plan.")1012        }1013        let localID = signed.txid1014        let hex = signed.hex1015        var remote: String?1016        var failure: (any Error)?1017        for client in clients {1018            do {1019                remote = try await client.broadcast(rawHex: hex)1020                break1021            } catch {1022                failure = error1023            }1024        }1025        guard let remote else { throw failure ?? WalletError.network("the transaction could not be broadcast") }1026        guard remote.isEmpty || remote.lowercased() == localID else { throw WalletError.broadcastMismatch(local: localID, remote: remote) }10271028        var state = utxoCoinStates[network] ?? UTXOCoinState()1029        for i in signed.inputs { state.locallySpent.insert(i.previousOutput) }1030        for (i, o) in signed.outputs.enumerated() where i != plan.plan.changeIndex { state.paidScripts.insert(o.scriptPubKey) }1031        utxoCoinStates[network] = state1032        if let c = plan.plan.changeIndex, let p = account.locate(scriptPubKey: signed.outputs[c].scriptPubKey, searchLimit: 400), p.chain == .change {1033            var used = Set(profile.usedChangeIndices[network.rawValue] ?? [])1034            used.insert(p.index)1035            profile.usedChangeIndices[network.rawValue] = used.sorted()1036            try? saveProfile()1037        }1038        noteBroadcast(kind, id: localID)1039        return BitcoinBroadcastResult(txid: localID, rawHex: hex, fee: plan.fee, virtualSize: signed.vsize)1040    }10411042    /// Status of a coin transaction from the last snapshot (no network: synchronize to refresh it).1043    func trackCoin(_ transaction: String, network: BitcoinNetwork) throws -> TransactionStatus {1044        let snapshot = try freshCoinSnapshot(network)1045        guard let entry = snapshot.transactions.first(where: { $0.txid == transaction.lowercased() }) else { return .notFound }1046        guard entry.confirmations > 0 else { return .pending }1047        let fee = entry.fee.map { UInt256($0) }1048        return UInt64(entry.confirmations) >= UInt64(network.minimumConfirmationsHint)1049            ? .finalized(blockHeight: entry.blockHeight.map { UInt64($0) }, fee: fee)1050            : .confirmed(blockHeight: entry.blockHeight.map { UInt64($0) }, confirmations: UInt64(entry.confirmations), fee: fee)1051    }1052}1053
Files main
Menu

Theme