SPB Git

Repository Public

WalletService+Bitcoin.swift 69.0 KB 1,113 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraWallet/WalletService+Bitcoin.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 QyvoraNetworking46import QyvoraVault4748/// What one address scan returned.49struct AddressScan: Sendable {50    let chain: BIP84Account.Chain51    let index: UInt3252    let address: BitcoinAddress53    var transactions: [EsploraTransaction]54    var truncated: Bool55    /// Counters of the address, read before its history. nil only for data of an older cache.56    var stats: EsploraAddressStats?57    /// Unspent outputs listed for the address (read for used addresses only).58    var utxos: [EsploraUTXO] = []59    /// The history was taken from the previous synchronization: the counters of the address had not changed.60    var historyReused = false6162    /// The address appears in a transaction: by its history, or by its counters when the history could not show it.63    var isUsed: Bool { !transactions.isEmpty || (stats?.isUsed ?? false) }6465    init(chain: BIP84Account.Chain, index: UInt32, address: BitcoinAddress, transactions: [EsploraTransaction], truncated: Bool,66         stats: EsploraAddressStats?, historyReused: Bool = false) {67        self.chain = chain68        self.index = index69        self.address = address70        self.transactions = transactions71        self.truncated = truncated72        self.stats = stats73        self.historyReused = historyReused74    }7576    /// From the persisted form. Throws when the address text is not an address of the network.77    init(_ entry: BitcoinSyncCache.Entry, network: BitcoinNetwork) throws {78        self.init(chain: entry.chain, index: entry.index, address: try BitcoinAddress(entry.address, network: network),79                  transactions: entry.transactions, truncated: entry.truncated, stats: entry.stats)80        utxos = entry.utxos81    }8283    var cacheEntry: BitcoinSyncCache.Entry {84        .init(chain: chain, index: index, address: address.string, stats: stats, transactions: transactions, truncated: truncated, utxos: utxos)85    }8687    /// "receive address 12 (tb1q…9xyz)", for progress lines and error messages.88    var label: String { Self.label(chain: chain, index: index, address: address.string) }8990    static func label(chain: BIP84Account.Chain, index: UInt32, address: String) -> String {91        "\(chain == .receive ? "receive" : "change") address \(index) (\(address.prefix(8))…\(address.suffix(4)))"92    }93}9495/// A Bitcoin snapshot built from address scans, with what the service keeps next to it.96struct AssembledBitcoin: Sendable {97    let snapshot: BitcoinSnapshot98    /// Scripts this wallet paid (address-reuse warning).99    let paidScripts: Set<Bytes>100    let usedReceive: [UInt32]101    let usedChange: [UInt32]102}103104/// A transaction of the indexer after validation, with scripts decoded.105struct CheckedTransaction: Sendable {106    struct Coin: Sendable {107        let script: Bytes108        let value: UInt64109    }110    let txid: String111    /// nil for an input whose previous output the indexer did not give (coinbase).112    let inputs: [(outPoint: BitcoinOutPoint?, coin: Coin?)]113    let outputs: [Coin]114    let height: UInt32?115    let time: Date?116    let isCoinbase: Bool117}118119extension WalletService {120    // MARK: Synchronization121122    /// Synchronizes the Bitcoin account. **Network.** Works for full and watch-only wallets, locked or not.123    ///124    /// Chain identity check (genesis hash), gap-limit-20 discovery on the receive and change chains, UTXO set, balances,125    /// history, next unused receive address, address reuse and key exposure. A concurrent call joins the running one.126    /// Errors: `mainnetDisabled`, `offline` (cold mode), `wrongChain`, `untrustedResponse`, `network`.127    @discardableResult128    public func syncBitcoin() async throws(WalletError) -> BitcoinSnapshot {129        try await run {130            if let running = bitcoinSyncTask { return try await running.value }131            let task = Task { try await self.performBitcoinSync() }132            bitcoinSyncTask = task133            emit(.syncStarted(.bitcoin))134            do {135                let snapshot = try await task.value136                bitcoinSyncTask = nil137                bitcoinError = nil138                emit(.syncFinished(.bitcoin))139                return snapshot140            } catch {141                bitcoinSyncTask = nil142                let wrapped = WalletError.wrap(error, now: now())143                bitcoinError = Self.describe(wrapped)144                emit(.syncFailed(.bitcoin, reason: bitcoinError ?? ""))145                throw wrapped146            }147        }148    }149150    /// The last Bitcoin snapshot, nil before the first successful synchronization on the active network. After a151    /// restart it is the one of the previous session (`isFromPreviousSession`) until a synchronization completes.152    public func latestBitcoinSnapshot() -> BitcoinSnapshot? { bitcoinSnapshot }153154    /// Coins shown from a previous session may have been spent since: transactions are built from a fresh reading only.155    static func requireFresh(_ snapshot: BitcoinSnapshot) throws {156        guard !snapshot.isFromPreviousSession else {157            throw WalletError.notSynchronized("The Bitcoin balance shown is the one of the previous session. Synchronize before preparing or sending a transaction.")158        }159    }160161    /// The sentence kept in the snapshot for a failed synchronization or a value that could not be read.162    static func describe(_ error: WalletError) -> String { error.userMessage }163164    /// A cached history is reused only when every transaction in it has at least this many confirmations: a165    /// reorganisation of the chain cannot have moved it.166    static let historyReuseDepth = 6167168    /// The error of one stage of a synchronization, with the name of the stage in front of the reason (which already169    /// names the endpoints): "reading the history of receive address 12 (…): mempool.space: HTTP 429 (too many requests)".170    static func staged(_ error: any Error, _ stage: String) -> any Error {171        if error is CancellationError { return error }172        if let e = error as? WalletError {173            switch e {174            case .network(let text): return WalletError.network("\(stage): \(text)")175            case .untrustedResponse(let text): return WalletError.untrustedResponse("\(stage): \(text)")176            default: return e177            }178        }179        if let e = error as? NetworkError { return staged(WalletError.from(e), stage) }180        return WalletError.network("\(stage): \(NetworkError.transportSummary(error))")181    }182183    /// One more address scanned, or one more page of history read: progress with the real counts of the stage.184    func noteBitcoinProgress(addressDone: Bool = false, detail: String? = nil) {185        guard var current = bitcoinProgress else { return }186        if addressDone {187            current.completed += 1188            bitcoinProgress = current189        }190        emit(.syncProgress(.bitcoin, stage: detail.map { "\(current.stage) · \($0)" } ?? current.stage, completed: current.completed, total: current.total))191    }192193    private func beginBitcoinStage(_ stage: String, completed: Int, total: Int) {194        bitcoinProgress = (stage, completed, total)195        emit(.syncProgress(.bitcoin, stage: stage, completed: completed, total: total))196    }197198    private func performBitcoinSync() async throws -> BitcoinSnapshot {199        defer { bitcoinProgress = nil }200        let account = try bitcoinAccount()201        let network = account.network202        let identity = Self.bitcoinIdentity(profile)203        emit(.syncProgress(.bitcoin, stage: "Checking the endpoints", completed: 0, total: nil))204        let esplora: EsploraClient205        do {206            esplora = try await verifiedEsplora(network)207        } catch {208            throw Self.staged(error, "checking which chain the endpoints serve")209        }210        let tip: UInt32211        do {212            let tipValue = try await esplora.tipHeight()213            guard tipValue >= 0, tipValue < 100_000_000 else { throw WalletError.untrustedResponse("tip height") }214            tip = UInt32(tipValue)215        } catch {216            throw Self.staged(error, "reading the chain tip")217        }218219        // What the previous synchronization read, for exactly this account, network and endpoint list220        var known = [String: BitcoinSyncCache.Entry]()221        if let cache = bitcoinCache, cache.identity == identity { for e in cache.entries { known[e.address] = e } }222        let cached = known223224        // 1. Discovery: batches of 20 addresses until 20 unused in a row. Each address: its counters first (one small225        //    request), then its history only when it is used and the counters changed since the previous synchronization.226        var scans = [AddressScan]()227        for chain in BIP84Account.Chain.allCases {228            let stage = chain == .receive ? "Scanning receive addresses" : "Scanning change addresses"229            var index: UInt32 = 0230            var gap: UInt32 = 0231            while gap < BIP84Account.gapLimit, index < Self.maximumScanIndex {232                let batch = try (index..<(index + BIP84Account.gapLimit)).map { (i: UInt32) -> (UInt32, BitcoinAddress) in233                    (i, try account.address(chain: chain, index: i))234                }235                beginBitcoinStage(stage, completed: Int(index), total: Int(index + BIP84Account.gapLimit))236                let pages = historyPagesPerAddress237                let results = try await boundedMap(batch) { item -> AddressScan in238                    let scan = try await Self.scanAddress(esplora, chain: chain, index: item.0, address: item.1, cached: cached[item.1.string],239                                                          tip: tip, maximumPages: pages) { page in240                        await self.noteBitcoinProgress(detail: "history of address \(item.0), page \(page)")241                    }242                    await self.noteBitcoinProgress(addressDone: true)243                    return scan244                }245                for r in results {246                    // strict gap limit: what lies beyond 20 unused addresses in a row is not part of the wallet247                    if gap >= BIP84Account.gapLimit { break }248                    scans.append(r)249                    gap = r.isUsed ? 0 : gap + 1250                }251                index += BIP84Account.gapLimit252            }253        }254255        // 2. Unspent outputs of the used addresses, always read again: balances never come from the cache256        let used = scans.enumerated().filter { $0.element.isUsed }257        beginBitcoinStage("Reading unspent outputs", completed: 0, total: used.count)258        let lists = try await boundedMap(used.map(\.element)) { s -> [EsploraUTXO] in259            do {260                let list = try await esplora.utxos(s.address.string)261                await self.noteBitcoinProgress(addressDone: true)262                return list263            } catch {264                throw Self.staged(error, "reading the unspent outputs of \(s.label)")265            }266        }267        for (n, item) in used.enumerated() { scans[item.offset].utxos = lists[n] }268269        // 3. Validation, balances, history, exposure270        let assembled = try Self.assembleBitcoin(account: account, tip: tip, scans: scans, profile: profile, synchronizedAt: now(),271                                                 fromPreviousSession: false)272273        // the active network may have changed while the requests were running274        guard profile.kind != nil, profile.bitcoinNetwork == network else { throw WalletError.stalePlan("the active network changed during synchronization") }275        bitcoinSnapshot = assembled.snapshot276        paidScripts = assembled.paidScripts277        locallySpent = []278        profile.usedReceiveIndices[network.rawValue] = assembled.usedReceive279        profile.usedChangeIndices[network.rawValue] = assembled.usedChange280        try saveProfile()281        // kept for the next launch and the next synchronization, unless the account or the endpoints changed meanwhile282        if let identity, identity == Self.bitcoinIdentity(profile) {283            let cache = BitcoinSyncCache(identity: identity, synchronizedAt: assembled.snapshot.synchronizedAt, tipHeight: tip, entries: scans.map(\.cacheEntry))284            bitcoinCache = cache285            SyncStore.save(cache, to: fileStore, name: BitcoinSyncCache.fileName, maximumBytes: BitcoinSyncCache.maximumBytes)286        }287        return assembled.snapshot288    }289290    /// Reads one address: its counters, then its history unless the address is unused or `cached` is still exact.291    static func scanAddress(_ esplora: EsploraClient, chain: BIP84Account.Chain, index: UInt32, address: BitcoinAddress,292                            cached: BitcoinSyncCache.Entry?, tip: UInt32, maximumPages: Int,293                            page: @Sendable (Int) async -> Void) async throws -> AddressScan {294        let label = AddressScan.label(chain: chain, index: index, address: address.string)295        let stats: EsploraAddressStats296        do {297            stats = try await esplora.addressStats(address.string)298        } catch {299            throw staged(error, "reading the statistics of \(label)")300        }301        guard stats.address == address.string else { throw WalletError.untrustedResponse("statistics returned for another address than \(label)") }302        guard stats.isUsed else {303            return AddressScan(chain: chain, index: index, address: address, transactions: [], truncated: false, stats: stats)304        }305        if let cached, canReuseHistory(cached, stats: stats, tip: tip) {306            return AddressScan(chain: chain, index: index, address: address, transactions: cached.transactions, truncated: cached.truncated,307                               stats: stats, historyReused: true)308        }309        let (transactions, truncated) = try await fetchHistory(esplora, address: address.string, label: label, maximumPages: maximumPages, page: page)310        return AddressScan(chain: chain, index: index, address: address, transactions: transactions, truncated: truncated, stats: stats)311    }312313    /// The history read at the previous synchronization is still the history of the address: its counters (funded and314    /// spent outputs, transactions, confirmed and in the mempool) are the same, nothing is pending, and every cached315    /// transaction is buried deep enough that a reorganisation cannot have changed its block.316    static func canReuseHistory(_ cached: BitcoinSyncCache.Entry, stats: EsploraAddressStats, tip: UInt32) -> Bool {317        guard let previous = cached.stats, previous == stats, stats.mempool_stats.tx_count == 0, !cached.transactions.isEmpty else { return false }318        return cached.transactions.allSatisfy { t in319            guard t.status.confirmed, let height = t.status.block_height, height >= 0 else { return false }320            return Int(tip) - height + 1 >= historyReuseDepth321        }322    }323324    /// Pure: validates the scans and builds the snapshot. Used after a synchronization and to restore the state of the325    /// previous session from the persisted scans — the same checks apply to both.326    static func assembleBitcoin(account: BIP84Account, tip: UInt32, scans: [AddressScan], profile: WalletProfile, synchronizedAt: Date,327                                fromPreviousSession: Bool) throws -> AssembledBitcoin {328        let network = account.network329        var scriptIndex = [Bytes: AddressScan]()330        for s in scans { scriptIndex[s.address.scriptPubKey] = s }331332        // 2. Validation and de-duplication of the history333        var transactions = [String: CheckedTransaction]()334        var perAddressCount = [Bytes: Int]()335        for s in scans {336            var seen = Set<String>()337            for raw in s.transactions {338                let checked = try Self.check(raw, tip: tip)339                // a transaction listed under an address must touch that address340                let script = s.address.scriptPubKey341                guard checked.outputs.contains(where: { $0.script == script }) || checked.inputs.contains(where: { $0.coin?.script == script }) else {342                    throw WalletError.untrustedResponse("transaction \(checked.txid.prefix(12))… does not involve the address it was listed for")343                }344                if let existing = transactions[checked.txid] {345                    guard existing.outputs.map(\.value) == checked.outputs.map(\.value), existing.outputs.map(\.script) == checked.outputs.map(\.script) else {346                        throw WalletError.untrustedResponse("two versions of transaction \(checked.txid.prefix(12))…")347                    }348                } else {349                    transactions[checked.txid] = checked350                }351                seen.insert(checked.txid)352            }353            perAddressCount[s.address.scriptPubKey] = seen.count354        }355356        // 3. UTXO set of the used addresses, cross-checked against the history357        let listed = scans.filter(\.isUsed).map { ($0, $0.utxos) }358        var spentOutPoints = Set<BitcoinOutPoint>()359        for t in transactions.values { for i in t.inputs { if let op = i.outPoint { spentOutPoints.insert(op) } } }360        var notes = [String]()361        var utxos = [BitcoinUTXO]()362        var seenOutPoints = Set<BitcoinOutPoint>()363        var unspentTotal: UInt64 = 0364        for (scan, list) in listed {365            guard list.count <= 5_000 else { throw WalletError.untrustedResponse("unspent output list too long") }366            for u in list {367                guard u.vout >= 0, u.vout < 100_000, let outPoint = BitcoinOutPoint(txid: u.txid, vout: UInt32(u.vout)),368                      u.value > 0, u.value <= BitcoinLimits.maxMoney else {369                    throw WalletError.untrustedResponse("unspent output out of range")370                }371                guard seenOutPoints.insert(outPoint).inserted else { throw WalletError.untrustedResponse("duplicate unspent output") }372                let script = scan.address.scriptPubKey373                var confirmations: UInt32 = 0374                var coinbase = false375                if let tx = transactions[outPoint.txid] {376                    guard u.vout < tx.outputs.count, tx.outputs[u.vout].script == script, tx.outputs[u.vout].value == u.value else {377                        throw WalletError.untrustedResponse("unspent output \(outPoint.txid.prefix(12))…:\(u.vout) disagrees with its transaction")378                    }379                    if let h = tx.height { confirmations = h <= tip ? tip - h + 1 : 1 }380                    coinbase = tx.isCoinbase381                } else if scan.truncated {382                    // the funding transaction lies beyond the pages read: take the indexer's status383                    if u.status.confirmed, let h = u.status.block_height, h >= 0, h <= Int(tip) { confirmations = tip - UInt32(h) + 1 }384                } else {385                    notes.append("An unspent output reported for \(scan.address.string) is not in its history yet; it is left out until the next synchronization.")386                    continue387                }388                if spentOutPoints.contains(outPoint) {389                    notes.append("An output of \(scan.address.string) is already spent by a pending transaction; it is not counted.")390                    continue391                }392                // every later sum (balances, coin selection) runs over these values: their total is bounded here393                unspentTotal += u.value394                guard unspentTotal <= BitcoinLimits.maxMoney else { throw WalletError.untrustedResponse("unspent outputs exceed the monetary range") }395                utxos.append(BitcoinUTXO(outPoint: outPoint, value: u.value, scriptPubKey: script, confirmations: confirmations,396                                         address: scan.address.string, derivation: .init(chain: scan.chain.rawValue, index: scan.index),397                                         isCoinbase: coinbase))398            }399        }400        utxos.sort { $0.outPoint.description < $1.outPoint.description }401402        // 4. Activity, history entries403        var activity = [ScriptActivity]()404        var entries = [BitcoinHistoryEntry]()405        var paid = Set<Bytes>()406        for t in transactions.values {407            var received: UInt64 = 0, spent: UInt64 = 0, toOthers: UInt64 = 0408            var others = [String](), mine = [String]()409            var inputTotal: UInt64 = 0, outputTotal: UInt64 = 0410            var allInputsMine = !t.inputs.isEmpty, allInputsKnown = true411            for i in t.inputs {412                guard let coin = i.coin else {413                    allInputsMine = false414                    allInputsKnown = false415                    continue416                }417                inputTotal += coin.value418                if scriptIndex[coin.script] != nil {419                    spent += coin.value420                    activity.append(ScriptActivity(scriptPubKey: coin.script, kind: .spent, txid: t.txid, height: t.height))421                } else {422                    allInputsMine = false423                }424            }425            var otherScripts = [Bytes]()426            for o in t.outputs {427                outputTotal += o.value428                if let scan = scriptIndex[o.script] {429                    received += o.value430                    mine.append(scan.address.string)431                    activity.append(ScriptActivity(scriptPubKey: o.script, kind: .funded, txid: t.txid, height: t.height))432                } else {433                    toOthers += o.value434                    otherScripts.append(o.script)435                    if let a = try? BitcoinAddress(scriptPubKey: o.script, network: network) { others.append(a.string) }436                }437            }438            let fee: UInt64? = allInputsMine && allInputsKnown && inputTotal >= outputTotal ? inputTotal - outputTotal : nil439            let direction: BitcoinHistoryEntry.Direction440            let amount: UInt64441            if spent == 0 {442                direction = .received443                amount = received444            } else if allInputsMine && toOthers == 0 {445                direction = .selfTransfer446                amount = 0447            } else {448                direction = .sent449                // with foreign inputs alongside ours (a joint transaction) only the net outflow can be attributed450                amount = allInputsMine ? toOthers : (spent > received ? spent - received : 0)451                paid.formUnion(otherScripts)452            }453            let confirmations: UInt32 = t.height.map { $0 <= tip ? tip - $0 + 1 : 1 } ?? 0454            entries.append(BitcoinHistoryEntry(txid: t.txid, direction: direction, netAmount: Int64(received) - Int64(spent), amount: amount,455                                               fee: fee, confirmations: confirmations, blockHeight: t.height, time: t.time,456                                               counterpartyAddresses: direction == .sent ? others : [], walletAddresses: mine))457        }458        entries.sort {459            switch ($0.blockHeight, $1.blockHeight) {460            case (nil, nil): return $0.txid < $1.txid461            case (nil, _): return true462            case (_, nil): return false463            case (let a?, let b?): return a != b ? a > b : $0.txid < $1.txid464            }465        }466        activity.sort { ($0.txid, $0.kind.rawValue, Hex.encode($0.scriptPubKey)) < ($1.txid, $1.kind.rawValue, Hex.encode($1.scriptPubKey)) }467468        // An address whose history was not read to the end may have older spends: its statistics say whether an output469        // was ever spent, so that its key is not reported as hidden by mistake.470        let alreadySpent = Set(activity.filter { $0.kind == .spent }.map(\.scriptPubKey))471        for s in scans where s.truncated && !alreadySpent.contains(s.address.scriptPubKey) && s.stats?.hasSpent == true {472            activity.append(ScriptActivity(scriptPubKey: s.address.scriptPubKey, kind: .spent, txid: "older-history", height: nil))473        }474475        // 5. Exposure, reuse, addresses476        let exposure = BitcoinPrivacyAnalysis.publicKeyExposure(utxos: utxos, activity: activity)477        let reuse = Set(BitcoinPrivacyAnalysis.addressReuse(activity: activity).map(\.scriptPubKey))478        let spentScripts = Set(activity.filter { $0.kind == .spent }.map(\.scriptPubKey))479        let frozen = Set(profile.frozenUTXOs)480        var balanceByScript = [Bytes: UInt64]()481        for u in utxos { balanceByScript[u.scriptPubKey, default: 0] += u.value }482483        func walletAddress(_ s: AddressScan) -> WalletAddress {484            let script = s.address.scriptPubKey485            return WalletAddress(address: s.address.string, chain: s.chain, index: s.index, path: account.path(chain: s.chain, index: s.index).description,486                                 isUsed: s.isUsed, transactionCount: perAddressCount[script] ?? 0, balance: balanceByScript[script] ?? 0,487                                 isReused: reuse.contains(script),488                                 exposure: BitcoinPrivacyAnalysis.publicKeyExposure(scriptPubKey: script, hasSpend: spentScripts.contains(script)).exposure,489                                 label: profile.addressLabels[s.address.string])490        }491        let usedReceive = Set(scans.filter { $0.chain == .receive && $0.isUsed }.map(\.index))492        let usedChange = Set(scans.filter { $0.chain == .change && $0.isUsed }.map(\.index))493        let nextIndex = account.nextUnusedIndex(used: usedReceive)494        let addresses = scans.filter { $0.chain == .receive ? $0.index <= nextIndex || $0.isUsed : $0.isUsed }495            .sorted { ($0.chain.rawValue, $0.index) < ($1.chain.rawValue, $1.index) }.map(walletAddress)496        let receive: WalletAddress497        if let s = scans.first(where: { $0.chain == .receive && $0.index == nextIndex }), !s.isUsed {498            receive = walletAddress(s)499        } else {500            // beyond the scanned window (cannot happen with a 20-address gap, kept as a guard): never return a used address501            let a = try account.address(chain: .receive, index: nextIndex)502            receive = WalletAddress(address: a.string, chain: .receive, index: nextIndex, path: account.path(chain: .receive, index: nextIndex).description,503                                    isUsed: false, transactionCount: 0, balance: 0, isReused: false, exposure: .hashedUnrevealed,504                                    label: profile.addressLabels[a.string])505        }506507        let walletUTXOs = utxos.map { u -> WalletUTXO in508            let a = exposure[u.outPoint] ?? BitcoinPrivacyAnalysis.publicKeyExposure(scriptPubKey: u.scriptPubKey, hasSpend: false)509            return WalletUTXO(utxo: u, exposure: a.exposure, exposureExplanation: a.explanation, isFrozen: frozen.contains(u.outPoint.description),510                              label: u.address.flatMap { profile.addressLabels[$0] })511        }512        let truncated = scans.contains(where: \.truncated)513        if truncated { notes.append("Some addresses have more history than the wallet reads; older transactions are not listed.") }514        let snapshot = BitcoinSnapshot(515            network: network, tipHeight: tip, synchronizedAt: synchronizedAt,516            balance: BitcoinBalance(confirmed: utxos.filter { $0.confirmations > 0 }.reduce(0) { $0 + $1.value },517                                    pending: utxos.filter { $0.confirmations == 0 }.reduce(0) { $0 + $1.value }),518            utxos: walletUTXOs, transactions: entries, addresses: addresses, receiveAddress: receive,519            reusedAddresses: scans.filter { reuse.contains($0.address.scriptPubKey) }.map(walletAddress),520            historyTruncated: truncated, notes: notes, activity: activity, isFromPreviousSession: fromPreviousSession)521522        return AssembledBitcoin(snapshot: snapshot, paidScripts: paid, usedReceive: usedReceive.sorted(), usedChange: usedChange.sorted())523    }524525    /// Every page of an address history, newest first; `truncated` when the page budget ran out. `page` is told the526    /// number of each page read, and a failure names the address and the page.527    private static func fetchHistory(_ esplora: EsploraClient, address: String, label: String, maximumPages: Int,528                                     page: @Sendable (Int) async -> Void) async throws -> ([EsploraTransaction], Bool) {529        func read(_ number: Int, after: String?) async throws -> [EsploraTransaction] {530            do {531                let list = try await esplora.transactions(address, after: after)532                guard list.count <= 100 else { throw WalletError.untrustedResponse("history page too long") }533                await page(number)534                return list535            } catch {536                throw staged(error, "reading the history of \(label), page \(number)")537            }538        }539        var all = try await read(1, after: nil)540        var lastPage = all541        var pages = 1542        while lastPage.filter({ $0.status.confirmed }).count >= 25 {543            guard pages < maximumPages else { return (all, true) }544            guard let last = lastPage.last(where: { $0.status.confirmed })?.txid else { break }545            lastPage = try await read(pages + 1, after: last)546            let known = Set(all.map(\.txid))547            let fresh = lastPage.filter { !known.contains($0.txid) }548            if fresh.isEmpty { break }549            all += fresh550            pages += 1551        }552        return (all, false)553    }554555    /// Bounds and decodes one transaction of the indexer.556    static func check(_ t: EsploraTransaction, tip: UInt32) throws -> CheckedTransaction {557        func bad(_ what: String) -> WalletError { .untrustedResponse("transaction \(t.txid.prefix(12))…: \(what)") }558        guard t.txid.utf8.count == 64, Hex.decode(t.txid) != nil, t.txid == t.txid.lowercased() else { throw WalletError.untrustedResponse("transaction identifier") }559        guard !t.vin.isEmpty, t.vin.count <= 25_000, !t.vout.isEmpty, t.vout.count <= 25_000 else { throw bad("input or output count") }560        func coin(_ p: EsploraTransaction.Prevout) throws -> CheckedTransaction.Coin {561            guard p.value <= BitcoinLimits.maxMoney, p.scriptpubkey.utf8.count <= BitcoinLimits.maxScriptSize * 2,562                  let script = Hex.decode(p.scriptpubkey) else { throw bad("output out of range") }563            return .init(script: script, value: p.value)564        }565        var total: UInt64 = 0566        var outputs = [CheckedTransaction.Coin]()567        for o in t.vout {568            let c = try coin(o)569            total += c.value570            guard total <= BitcoinLimits.maxMoney else { throw bad("output total out of range") }571            outputs.append(c)572        }573        let zero = String(repeating: "0", count: 64)574        let coinbase = t.vin.count == 1 && t.vin[0].txid == zero575        var inputs = [(outPoint: BitcoinOutPoint?, coin: CheckedTransaction.Coin?)]()576        var inTotal: UInt64 = 0577        var seen = Set<BitcoinOutPoint>()578        for i in t.vin {579            if coinbase {580                inputs.append((nil, nil))581                continue582            }583            guard i.vout >= 0, i.vout < 100_000, let op = BitcoinOutPoint(txid: i.txid, vout: UInt32(i.vout)), seen.insert(op).inserted else { throw bad("input reference") }584            let c = try i.prevout.map(coin)585            if let c {586                inTotal += c.value587                guard inTotal <= BitcoinLimits.maxMoney else { throw bad("input total out of range") }588            }589            inputs.append((op, c))590        }591        var height: UInt32?592        var time: Date?593        if t.status.confirmed {594            guard let h = t.status.block_height, h >= 0, h < 100_000_000 else { throw bad("block height") }595            height = UInt32(h)596            if let s = t.status.block_time, s > 1_230_000_000, s < 10_000_000_000 { time = Date(timeIntervalSince1970: TimeInterval(s)) }597        }598        return CheckedTransaction(txid: t.txid, inputs: inputs, outputs: outputs, height: height, time: time, isCoinbase: coinbase)599    }600601    // MARK: Fees602603    /// Slow / normal / fast fee rates. **Network.** From the endpoint's estimates (targets ≈ 144, 6 and 1 blocks), floored at604    /// the minimum relay fee (1 sat/vB), capped at `bitcoinMaximumFeeRate`, and kept in order slow ≤ normal ≤ fast.605    /// When the endpoint has no usable estimate, every tier is the floor and `source` says so.606    public func bitcoinFeeOptions() async throws(WalletError) -> BitcoinFeeOptions {607        try await run {608            let network = try bitcoinAccount().network609            let esplora = try await verifiedEsplora(network)610            let estimates = try await esplora.feeEstimates()611            // on an unaudited mainnet build the tiers never exceed the fee-rate ceiling of `MainnetPolicy.limits`612            let floor = FeeRate.minimumRelay, cap = FeeRate(satPerVByte: Self.bitcoinFeeRateCeiling(network))613            func pick(_ targets: [Int]) -> (FeeRate, Int)? {614                for t in targets {615                    if let v = estimates[t], let r = FeeRate.fromEstimate(satPerVByte: v) { return (min(max(r, floor), cap), t) }616                }617                return nil618            }619            guard let fast = pick([1, 2, 3]), let normal = pick([6, 5, 4, 8, 10, 3]), let slow = pick([144, 504, 72, 25, 1008, 20]) else {620                func opt(_ t: BitcoinFeeOption.Tier) -> BitcoinFeeOption { .init(tier: t, rate: floor, targetBlocks: nil) }621                return BitcoinFeeOptions(slow: opt(.slow), normal: opt(.normal), fast: opt(.fast), source: .minimumRelayFloor)622            }623            let n = min(normal.0, fast.0), s = min(slow.0, n)624            return BitcoinFeeOptions(slow: .init(tier: .slow, rate: s, targetBlocks: slow.1), normal: .init(tier: .normal, rate: n, targetBlocks: normal.1),625                                     fast: .init(tier: .fast, rate: fast.0, targetBlocks: fast.1), source: .estimates)626        }627    }628629    // MARK: Sending630631    /// Builds a reviewable payment from the last snapshot. No secret, no network. Needs a prior `syncBitcoin()`.632    ///633    /// - `amount`: satoshis; ignored when `sendMax` is true (everything spendable goes to `to`, no change).634    /// - `coinControl`: forced inputs, or nil. Frozen outputs are always excluded; unconfirmed outputs are not selected635    ///   unless asked.636    /// Errors: `notSynchronized`, `invalidAddress`, `bitcoinBuild(…)` (insufficient funds, dust, fee out of range, fee cap…).637    public func prepareBitcoinSend(to: String, amount: UInt64, feeRate: FeeRate, sendMax: Bool = false,638                                   coinControl: BitcoinCoinControl? = nil) async throws(WalletError) -> BitcoinSendPlan {639        try await run {640            let account = try bitcoinAccount()641            guard let snapshot = bitcoinSnapshot, snapshot.network == account.network else {642                throw WalletError.notSynchronized("Synchronize the Bitcoin account before preparing a payment.")643            }644            try Self.requireFresh(snapshot)645            let destination: BitcoinAddress646            do {647                destination = try BitcoinAddress(to.trimmingCharacters(in: .whitespacesAndNewlines), network: account.network)648            } catch let e as BitcoinAddress.Error {649                throw WalletError.invalidAddress(Self.describe(e, network: account.network))650            }651            guard destination.type != .witnessUnknown else {652                throw WalletError.invalidAddress("This address uses a witness version without assigned meaning; QYVORA does not send to it.")653            }654            guard sendMax || amount > 0 else { throw WalletError.invalidInput("The amount is zero.") }655            return try buildBitcoinPlan(account: account, snapshot: snapshot, purpose: .payment, destination: destination, amount: amount,656                                        feeRate: feeRate, sendMax: sendMax, coinControl: coinControl ?? BitcoinCoinControl())657        }658    }659660    static func describe(_ error: BitcoinAddress.Error, network: BitcoinNetwork) -> String {661        switch error {662        case .invalidFormat: return "Not a \(network.mainCounterpart.displayName) address."663        case .mixedCase: return "The address mixes upper and lower case."664        case .invalidChecksum: return "The checksum of the address does not verify: a character is wrong."665        case .wrongNetwork: return "This address belongs to another network than \(network.displayName)."666        case .invalidWitnessProgram: return "The address encodes an invalid witness program."667        case .noAddressForScript: return "Not a \(network.mainCounterpart.displayName) address."668        case .ambiguousLegacyFormat:669            return "This is the former Litecoin script address format, which cannot be told from a Bitcoin address. Ask for the address in its current form (it starts with M, or Q on testnet)."670        case .unsupportedAddressType: return "This kind of Bitcoin Cash address (token-aware or 32-byte script) is not supported."671        }672    }673674    func buildBitcoinPlan(account: BIP84Account, snapshot: BitcoinSnapshot, purpose: BitcoinSendPlan.Purpose, destination: BitcoinAddress,675                          amount: UInt64, feeRate: FeeRate, sendMax: Bool, coinControl: BitcoinCoinControl,676                          enforceLimits: Bool = true) throws -> BitcoinSendPlan {677        let network = account.network678        if enforceLimits, !sendMax { try enforceUnauditedBitcoinLimit(network: network, amount: amount) }679        let usedChange = Set(profile.usedChangeIndices[network.rawValue] ?? [])680        let change = try account.nextUnusedAddress(chain: .change, used: usedChange)681        let candidates = snapshot.utxos.map(\.utxo).filter { !locallySpent.contains($0.outPoint) }682        var request = BitcoinSpendRequest(683            recipients: sendMax ? [] : [BitcoinTransaction.Output(value: amount, scriptPubKey: destination.scriptPubKey)],684            utxos: candidates, feeRate: feeRate, changeScript: change.address.scriptPubKey,685            sendMaxScript: sendMax ? destination.scriptPubKey : nil)686        var frozen = Set<BitcoinOutPoint>()687        for u in snapshot.utxos where u.isFrozen && !coinControl.required.contains(u.utxo.outPoint) { frozen.insert(u.utxo.outPoint) }688        request.coinControl = .init(required: coinControl.required, useOnlyRequired: coinControl.useOnlyRequired, excluded: frozen,689                                    minimumConfirmations: coinControl.includeUnconfirmed ? 0 : 1)690        request.currentHeight = snapshot.tipHeight691        request.maximumFee = Self.bitcoinMaximumFee692        request.maximumFeeRate = FeeRate(satPerVByte: Self.bitcoinMaximumFeeRate)693        request.seed = transactionSeed694        let plan = try BitcoinTransactionBuilder.build(request)695696        let exposureByOutPoint = Dictionary(uniqueKeysWithValues: snapshot.utxos.map { ($0.utxo.outPoint, $0.exposure) })697        let inputs = plan.inputs.map {698            BitcoinSendPlan.Input(outPoint: $0.outPoint, address: $0.address, value: $0.value, confirmations: $0.confirmations,699                                  exposure: exposureByOutPoint[$0.outPoint] ?? .undetermined)700        }701        let ownScripts = Dictionary(uniqueKeysWithValues: snapshot.addresses.map { ($0.address, $0) })702        var outputs = [BitcoinSendPlan.Output]()703        for (i, o) in plan.transaction.outputs.enumerated() {704            let text = (try? BitcoinAddress(scriptPubKey: o.scriptPubKey, network: network))?.string705            let isChange = i == plan.changeIndex706            let mine = isChange || (text.map { ownScripts[$0] != nil } ?? false) || account.locate(scriptPubKey: o.scriptPubKey, searchLimit: 40) != nil707            outputs.append(.init(index: i, address: text, value: o.value, isChange: isChange, isMine: mine))708        }709        let paidAmount = sendMax ? (plan.sendMaxIndex.map { plan.transaction.outputs[$0].value } ?? 0) : amount710        if enforceLimits {711            try enforceUnauditedBitcoinLimit(network: network, amount: paidAmount, sendMax: sendMax)712            try enforceUnauditedBitcoinFeeLimit(network: network, fee: plan.fee, vsize: plan.estimatedVSize)713        }714715        var warnings = [BitcoinSendWarning]()716        if network == .mainnet, MainnetPolicy.unauditedMainnet { warnings.append(.unauditedMainnet) }717        if purpose == .payment {718            if let own = ownScripts[destination.string] {719                warnings.append(.destinationIsOwnAddress)720                if own.isUsed { warnings.append(.destinationReused) }721            } else if account.locate(scriptPubKey: destination.scriptPubKey, searchLimit: 40) != nil {722                warnings.append(.destinationIsOwnAddress)723            }724            if paidScripts.contains(destination.scriptPubKey) {725                warnings.append(.destinationAlreadyPaid)726            } else if !warnings.contains(.destinationIsOwnAddress) {727                // an address this wallet never paid, as far as its history shows: address poisoning and clipboard728                // substitution are caught here or nowhere729                warnings.append(.firstPaymentToAddress)730            }731        }732        let exposed = inputs.filter { $0.exposure == .revealedBySpend || $0.exposure == .revealedByScript }.count733        if exposed > 0, purpose == .payment { warnings.append(.exposedInputs(count: exposed)) }734        if purpose == .payment, paidAmount > 0 {735            let (scaled, overflow) = plan.fee.multipliedReportingOverflow(by: 10_000)736            let basisPoints = overflow ? Int.max : Int(min(scaled / paidAmount, UInt64(Int32.max)))737            if basisPoints > 500 { warnings.append(.highFeeShare(basisPoints: basisPoints)) }738        }739        if plan.fee > Self.bitcoinFeeWarningThreshold { warnings.append(.highAbsoluteFee(fee: plan.fee, threshold: Self.bitcoinFeeWarningThreshold)) }740        if plan.changeIndex == nil, plan.sendMaxIndex == nil {741            let required = feeRate.fee(weight: plan.estimatedWeight)742            if plan.fee > required { warnings.append(.dustAddedToFee(amount: plan.fee - required)) }743        }744        let unconfirmed = inputs.filter { $0.confirmations == 0 }.count745        if unconfirmed > 0 { warnings.append(.unconfirmedInputs(count: unconfirmed)) }746        let distinct = Set(plan.inputs.map(\.scriptPubKey)).count747        if distinct > 1 { warnings.append(.mergesAddresses(count: distinct)) }748749        return BitcoinSendPlan(id: UUID(), purpose: purpose, network: network, createdAt: now(), plan: plan, recipient: destination.string,750                               amount: paidAmount, fee: plan.fee, virtualSize: plan.estimatedVSize, targetFeeRate: feeRate,751                               effectiveFeeRate: plan.effectiveFeeRate, inputs: inputs, outputs: outputs,752                               changeAddress: plan.changeIndex == nil ? nil : change.address.string, changeValue: plan.changeValue,753                               isSendMax: sendMax, warnings: warnings)754    }755756    /// Checks that a plan still fits the wallet: same network, inputs still unspent with the same amounts, sane fee.757    func validate(_ plan: BitcoinSendPlan) throws -> BitcoinSnapshot {758        let network = try bitcoinAccount().network759        guard plan.network == network else { throw WalletError.stalePlan("The plan was made for \(plan.network.displayName).") }760        guard let snapshot = bitcoinSnapshot, snapshot.network == network else {761            throw WalletError.notSynchronized("Synchronize the Bitcoin account before sending.")762        }763        try Self.requireFresh(snapshot)764        let known = Dictionary(uniqueKeysWithValues: snapshot.utxos.map { ($0.utxo.outPoint, $0.utxo) })765        var inputTotal: UInt64 = 0766        guard plan.plan.inputs.count == plan.plan.transaction.inputs.count else { throw WalletError.stalePlan("inconsistent plan") }767        for (i, u) in plan.plan.inputs.enumerated() {768            guard plan.plan.transaction.inputs[i].previousOutput == u.outPoint, let current = known[u.outPoint], current.value == u.value,769                  current.scriptPubKey == u.scriptPubKey, !locallySpent.contains(u.outPoint) else {770                throw WalletError.stalePlan("An input of the plan is no longer available. Prepare the payment again.")771            }772            inputTotal += u.value773        }774        guard let outputTotal = plan.plan.transaction.outputValue, inputTotal >= outputTotal, inputTotal - outputTotal == plan.fee,775              plan.fee <= Self.bitcoinMaximumFee else { throw WalletError.stalePlan("inconsistent amounts") }776        // The output left out of the value ceiling must really be change: a script of this account's change chain.777        // Otherwise a plan whose "change" pays someone else would move any amount under the ceiling (QYV-SVC-066,778        // the Bitcoin form of QYV-SVC-063). The change index is one past the highest used one, bounded by the scan.779        if let c = plan.plan.changeIndex {780            let account = try bitcoinAccount()781            guard plan.plan.transaction.outputs.indices.contains(c),782                  account.locate(scriptPubKey: plan.plan.transaction.outputs[c].scriptPubKey,783                                 searchLimit: Self.maximumScanIndex + BIP84Account.gapLimit)?.chain == .change else {784                throw WalletError.stalePlan("The change of the plan does not return to this wallet. Prepare the payment again.")785            }786        }787        // the ceiling of an unaudited build is checked again on what will actually be signed788        let recipients = plan.plan.transaction.outputs.enumerated().filter { $0.offset != plan.plan.changeIndex }.reduce(UInt64(0)) { $0 + $1.element.value }789        try enforceUnauditedBitcoinLimit(network: network, amount: recipients, sendMax: plan.isSendMax)790        try enforceUnauditedBitcoinFeeLimit(network: network, fee: plan.fee, vsize: plan.plan.estimatedVSize)791        return snapshot792    }793794    /// Signs the plan locally and broadcasts it. **Needs an unlocked vault (full wallet). Network.**795    ///796    /// The phrase is read from the vault for the signature only. Every signature is verified, the txid is computed locally797    /// and compared with the plan and with the identifier returned by the endpoint (`broadcastMismatch` when they differ).798    /// Spent outputs are set aside until the next `syncBitcoin()`.799    public func signAndBroadcastBitcoin(_ plan: BitcoinSendPlan) async throws(WalletError) -> BitcoinBroadcastResult {800        try await run {801            _ = try validate(plan)802            let network = plan.network803            let esplora = try await verifiedEsplora(network)804            let expectedKey = try bitcoinAccount().extendedPublicKey(slip132: false)805            let signed: BitcoinTransaction = try await withMasterKey { master in806                var signer = try BIP84Account(master: master, network: network)807                defer { signer.wipe() }808                guard signer.extendedPublicKey(slip132: false) == expectedKey else {809                    throw WalletError.signingFailed("The recovery phrase in the vault does not match this wallet's account.")810                }811                return try signer.sign(plan: plan.plan)812            }813            // independent checks on what will leave the device814            do {815                try BitcoinVerifier.verify(transaction: signed, spentOutputs: plan.plan.inputs.map(\.output))816            } catch {817                throw WalletError.signingFailed("A signature does not verify.")818            }819            guard signed.txid == plan.txid, signed.outputs == plan.plan.transaction.outputs, signed.lockTime == plan.plan.transaction.lockTime else {820                throw WalletError.signingFailed("The signed transaction differs from the reviewed plan.")821            }822            let result = try await broadcastBitcoin(signed, fee: plan.fee, esplora: esplora, changeScript: plan.plan.changeIndex.map { signed.outputs[$0].scriptPubKey })823            // paid now: the next plan for the same address says so, without waiting for the synchronization824            if plan.purpose == .payment {825                for (i, o) in signed.outputs.enumerated() where i != plan.plan.changeIndex { paidScripts.insert(o.scriptPubKey) }826            }827            return result828        }829    }830831    func broadcastBitcoin(_ tx: BitcoinTransaction, fee: UInt64, esplora: EsploraClient, changeScript: Bytes?) async throws -> BitcoinBroadcastResult {832        let localID = tx.txid833        let hex = tx.hex834        let remote = try await esplora.broadcast(rawHex: hex)835        // an empty answer means "already known"; anything else must be our identifier836        guard remote.isEmpty || remote.lowercased() == localID else { throw WalletError.broadcastMismatch(local: localID, remote: remote) }837        for i in tx.inputs { locallySpent.insert(i.previousOutput) }838        if let changeScript, let account = try? bitcoinAccount(), let p = account.locate(scriptPubKey: changeScript, searchLimit: 400), p.chain == .change {839            var used = Set(profile.usedChangeIndices[account.network.rawValue] ?? [])840            used.insert(p.index)841            profile.usedChangeIndices[account.network.rawValue] = used.sorted()842            try? saveProfile()843        }844        emit(.transactionBroadcast(.bitcoin, id: localID))845        return BitcoinBroadcastResult(txid: localID, rawHex: hex, fee: fee, virtualSize: tx.vsize)846    }847848    /// Moves every output whose public key is already on chain to one fresh address of this wallet, as a normal849    /// reviewable plan (`purpose == .sweepExposed`). No secret, no network. Needs a prior `syncBitcoin()`.850    /// Throws `invalidInput` when nothing is exposed.851    public func prepareSweepOfExposedBitcoin(feeRate: FeeRate) async throws(WalletError) -> BitcoinSendPlan {852        try await run {853            guard Self.isMigrationEnabled("btc.rotation") else { throw WalletError.featureUnavailable("Sweeping to fresh addresses is not available.") }854            let account = try bitcoinAccount()855            guard let snapshot = bitcoinSnapshot, snapshot.network == account.network else {856                throw WalletError.notSynchronized("Synchronize the Bitcoin account first.")857            }858            try Self.requireFresh(snapshot)859            let exposed = snapshot.utxos.filter {860                ($0.exposure == .revealedBySpend || $0.exposure == .revealedByScript) && !$0.isFrozen && !locallySpent.contains($0.utxo.outPoint)861            }862            guard !exposed.isEmpty else { throw WalletError.invalidInput("No output of this wallet sits behind a published key.") }863            // a never-used address of the internal chain: it was never shown to anyone864            let usedChange = Set(profile.usedChangeIndices[account.network.rawValue] ?? [])865            let fresh = try account.nextUnusedAddress(chain: .change, used: usedChange)866            return try buildBitcoinPlan(account: account, snapshot: snapshot, purpose: .sweepExposed, destination: fresh.address, amount: 0,867                                        feeRate: feeRate, sendMax: true,868                                        coinControl: BitcoinCoinControl(required: exposed.map(\.utxo.outPoint), useOnlyRequired: true, includeUnconfirmed: true))869        }870    }871872    // MARK: PSBT (cold signing)873874    /// Largest previous transaction attached to an exported PSBT, in bytes; a larger one is left out (the cold device875    /// then reports the amounts as unverified).876    static let maximumAttachedPreviousTransaction = 50_000877878    /// The plan as a PSBT (BIP-174) with witness UTXOs and BIP-32 key origins, as base64 text and QR frames879    /// for a cold device to sign. No secret.880    ///881    /// **Network (best effort).** The previous transaction of every input is read from the endpoint and attached882    /// (PSBT_IN_NON_WITNESS_UTXO) after checking that it hashes to the outpoint and holds the same output: the cold883    /// device, which never synchronizes, can then verify the amounts and therefore the fee by itself (QYV-SVC-008).884    /// An input whose previous transaction cannot be read keeps its witness UTXO only.885    public func exportPSBT(_ plan: BitcoinSendPlan) async throws(WalletError) -> QRExport {886        try await run {887            _ = try validate(plan)888            var psbt = try bitcoinAccount().psbt(for: plan.plan)889            if !gate.isOffline, let esplora = try? await verifiedEsplora(plan.network) {890                var fetched = [String: BitcoinTransaction]()891                for (i, input) in plan.plan.transaction.inputs.enumerated() {892                    let txid = input.previousOutput.txid893                    if fetched[txid] == nil, let hex = try? await esplora.transactionHex(txid).trimmingCharacters(in: .whitespacesAndNewlines),894                       hex.utf8.count <= Self.maximumAttachedPreviousTransaction * 2, let previous = try? BitcoinTransaction(hex: hex) {895                        fetched[txid] = previous896                    }897                    // refused (and left out) unless it hashes to the outpoint and agrees with the witness UTXO898                    if let previous = fetched[txid] { try? psbt.setNonWitnessUTXO(previous, inputIndex: i) }899                }900            }901            return try QRExport.make(text: psbt.base64)902        }903    }904905    private func parsePSBT(_ input: [String]) throws -> PSBT {906        let text = try QRExport.text(from: input)907        guard text.utf8.count <= 2_000_000 else { throw WalletError.invalidPSBT("too large") }908        do {909            return try PSBT(base64: text)910        } catch {911            throw WalletError.invalidPSBT((error as? PSBTError).map(WalletMessages.psbt) ?? "It cannot be read.")912        }913    }914915    /// Reviews a PSBT (base64 text or QR frames) without signing. No secret, no network.916    ///917    /// Which inputs and outputs belong to this wallet is established by deriving the wallet's own keys; the PSBT's918    /// derivation fields are only used as hints of where to look.919    public func reviewPSBT(_ input: [String]) async throws(WalletError) -> PSBTReview {920        try await run { try review(try parsePSBT(input), account: try bitcoinAccount()) }921    }922923    func review(_ psbt: PSBT, account: BIP84Account) throws -> PSBTReview {924        let network = account.network925        let tx = psbt.unsignedTransaction926        guard !tx.inputs.isEmpty, !tx.outputs.isEmpty, tx.inputs.count <= 1_000, tx.outputs.count <= 1_000 else { throw WalletError.invalidPSBT("empty or oversized transaction") }927        let prefix = account.accountPath.indices928        let window = max(100, (Set(profile.usedReceiveIndices[network.rawValue] ?? []).union(profile.usedChangeIndices[network.rawValue] ?? []).max() ?? 0) + 40)929        // derived eagerly (a few hundred keys): a lazily filled capture would be shared mutable state930        let table = try account.scriptIndex(receiveCount: window, changeCount: window)931932        /// Position of a script in this wallet, verified by derivation.933        func locate(_ script: Bytes, hints: [PSBT.KeyDerivation]) throws -> (chain: BIP84Account.Chain, index: UInt32)? {934            guard case .p2wpkh = BitcoinScript.classify(script) else { return nil }935            for h in hints where h.path.indices.count == prefix.count + 2 && Array(h.path.indices.prefix(prefix.count)) == prefix {936                let tail = Array(h.path.indices.suffix(2))937                if !tail[0].isHardened, !tail[1].isHardened, let chain = BIP84Account.Chain(rawValue: tail[0].index),938                   (try? account.scriptPubKey(chain: chain, index: tail[1].index)) == script {939                    return (chain, tail[1].index)940                }941            }942            return table.locate(script)943        }944945        var warnings = [String]()946        var inputs = [PSBTReview.Input]()947        for (i, input) in tx.inputs.enumerated() {948            let spent = psbt.spentOutput(inputIndex: i)949            let position = try spent.flatMap { try locate($0.scriptPubKey, hints: psbt.inputs[i].derivations) }950            inputs.append(.init(outPoint: input.previousOutput,951                                address: spent.flatMap { (try? BitcoinAddress(scriptPubKey: $0.scriptPubKey, network: network))?.string },952                                value: spent?.value, isMine: position != nil,953                                derivationPath: position.map { account.path(chain: $0.chain, index: $0.index).description },954                                isSigned: psbt.inputs[i].isFinalized || !psbt.inputs[i].partialSignatures.isEmpty))955        }956        var outputs = [PSBTReview.Output]()957        var toOthers: UInt64 = 0, returning: UInt64 = 0958        guard tx.outputValue != nil else { throw WalletError.invalidPSBT("output amounts out of range") }959        for (i, o) in tx.outputs.enumerated() {960            let position = try locate(o.scriptPubKey, hints: psbt.outputs[i].derivations)961            if position != nil { returning += o.value } else { toOthers += o.value }962            outputs.append(.init(index: i, address: (try? BitcoinAddress(scriptPubKey: o.scriptPubKey, network: network))?.string, value: o.value,963                                 isMine: position != nil, isChange: position?.chain == .change,964                                 derivationPath: position.map { account.path(chain: $0.chain, index: $0.index).description }))965        }966        let fee = psbt.fee967        let weights = tx.inputs.indices.map { i in psbt.spentOutput(inputIndex: i).flatMap { BitcoinSizeEstimator.inputWeight(scriptPubKey: $0.scriptPubKey) } ?? 272 }968        let vsize = (BitcoinSizeEstimator.transactionWeight(inputWeights: weights, outputScripts: tx.outputs.map(\.scriptPubKey)) + 3) / 4969970        let foreign = inputs.filter { !$0.isMine }.count971        if foreign == inputs.count {972            warnings.append("None of the inputs belongs to this wallet.")973        } else if foreign > 0 {974            warnings.append("\(foreign) input(s) do not belong to this wallet.")975        }976        // QYV-SVC-008. A SegWit signature commits to the amount of the input it signs and to nothing else: with two977        // inputs or more, amounts taken from the PSBT's word can hide a fee. An input is verified when it carries its978        // previous transaction (the parser checked that it hashes to the outpoint) or is an output this wallet read.979        var known = [BitcoinOutPoint: BitcoinTransaction.Output]()980        if let snapshot = bitcoinSnapshot, snapshot.network == network { for u in snapshot.utxos { known[u.utxo.outPoint] = u.utxo.output } }981        let unverified = tx.inputs.indices.filter { i in982            guard let spent = psbt.spentOutput(inputIndex: i) else { return true }983            return psbt.inputs[i].nonWitnessUTXO == nil && known[tx.inputs[i].previousOutput] != spent984        }985        let amountsVerified = fee != nil && (tx.inputs.count == 1 || unverified.isEmpty)986        if fee == nil { warnings.append("The fee cannot be computed: the amount of an input is missing.") }987        if fee != nil, !amountsVerified { warnings.append(Self.unverifiedAmountsText(count: unverified.count)) }988        if let fee {989            if fee > Self.bitcoinFeeWarningThreshold { warnings.append("The fee (\(fee) sat) is unusually high.") }990            if toOthers > 0, fee.multipliedReportingOverflow(by: 20).partialValue > toOthers { warnings.append("The fee exceeds 5 % of the amount sent.") }991        }992        if outputs.contains(where: { $0.address == nil && $0.value > 0 }) { warnings.append("An output pays a script without address form.") }993        if psbt.inputs.contains(where: { $0.sighashType != nil && $0.sighashType != .all }) { warnings.append("An input asks for a signature that does not cover the whole transaction.") }994        if network == .mainnet, MainnetPolicy.unauditedMainnet { warnings.append(WalletError.unauditedText) }995996        func btc(_ sats: UInt64) -> String { BaseUnits.format(UInt256(sats), decimals: 8) + " BTC" }997        var summary = ["Network: \(network.displayName)", "Transaction: \(tx.txid)"]998        for o in outputs where !o.isMine { summary.append("Pay \(btc(o.value)) to \(o.address ?? "a script without address")") }999        for o in outputs where o.isMine { summary.append((o.isChange ? "Change " : "To this wallet ") + "\(btc(o.value)) → \(o.address ?? "?") (\(o.derivationPath ?? "?"))") }1000        summary.append(fee.map { "Fee: \(btc($0)) (\($0) sat, about \(vsize) vB)" + (amountsVerified ? "" : " — NOT VERIFIED") } ?? "Fee: unknown")1001        summary += warnings.map { "Warning: \($0)" }10021003        return PSBTReview(network: network, txid: tx.txid, inputs: inputs, outputs: outputs, fee: fee, sentToOthers: toOthers,1004                          returningToWallet: returning, virtualSizeEstimate: vsize, warnings: warnings, summary: summary,1005                          isFullySigned: psbt.isFinalized || psbt.inputs.allSatisfy { !$0.partialSignatures.isEmpty || $0.isFinalized },1006                          inputAmountsVerified: amountsVerified)1007    }10081009    static func unverifiedAmountsText(count: Int) -> String {1010        "The fee is not verified: \(count) input amount(s) are only stated by the PSBT, without the previous transaction. "1011            + "A dishonest online device could hide a much larger fee. Export the PSBT again from an up-to-date QYVORA, or sign only if you trust the device that prepared it."1012    }10131014    /// Signs the wallet's inputs of a PSBT on the cold device. **Needs an unlocked vault (full wallet). No network.**1015    ///1016    /// Show `reviewPSBT` first and call this only after the user confirmed. Refused (`invalidPSBT`) when no input belongs1017    /// to this wallet, when the fee is unknown, or when the fee exceeds `bitcoinMaximumFee` or `bitcoinMaximumFeeRate`.1018    /// Only SIGHASH_ALL is signed. Returns the review that was signed and the signed PSBT to carry back.1019    ///1020    /// Input amounts (QYV-SVC-008): when `PSBTReview.inputAmountsVerified` is false the fee shown is the PSBT's word.1021    /// Signing is then refused unless `acceptUnverifiedAmounts` is true (an explicit, separate confirmation of the1022    /// user), and always refused on mainnet with an unaudited engine, where no ceiling can bound a hidden fee.1023    public func signPSBT(_ input: [String], acceptUnverifiedAmounts: Bool = false) async throws(WalletError) -> SignedPSBT {1024        try await run {1025            var psbt = try parsePSBT(input)1026            let account = try bitcoinAccount()1027            let before = try review(psbt, account: account)1028            guard before.inputs.contains(where: \.isMine) else { throw WalletError.invalidPSBT("No input of this transaction belongs to this wallet.") }1029            guard let fee = before.fee else { throw WalletError.invalidPSBT("The fee cannot be computed: the amount of an input is missing.") }1030            if !before.inputAmountsVerified {1031                if account.network == .mainnet, MainnetPolicy.unauditedMainnet {1032                    throw WalletError.invalidPSBT("The input amounts cannot be verified (no previous transactions in the PSBT), so the fee could be forged. On mainnet this build does not sign such a PSBT: export it again from an up-to-date QYVORA.")1033                }1034                guard acceptUnverifiedAmounts else {1035                    throw WalletError.invalidPSBT("The input amounts cannot be verified (no previous transactions in the PSBT), so the fee could be forged. Signing it needs an explicit confirmation.")1036                }1037            }1038            try enforceUnauditedBitcoinLimit(network: account.network, amount: before.sentToOthers)1039            try enforceUnauditedBitcoinFeeLimit(network: account.network, fee: fee, vsize: before.virtualSizeEstimate)1040            guard fee <= Self.bitcoinMaximumFee, fee <= FeeRate(satPerVByte: Self.bitcoinMaximumFeeRate).fee(vsize: before.virtualSizeEstimate) else {1041                throw WalletError.invalidPSBT("The fee (\(fee) sat) is beyond what QYVORA signs.")1042            }1043            var options = PSBT.SigningOptions()1044            if let snapshot = bitcoinSnapshot, snapshot.network == account.network {1045                for u in snapshot.utxos { options.expectedUTXOs[u.utxo.outPoint] = u.utxo.output }1046            }1047            let network = account.network1048            let expectedKey = account.extendedPublicKey(slip132: false)1049            let window = UInt32(max(100, (Set(profile.usedReceiveIndices[network.rawValue] ?? []).union(profile.usedChangeIndices[network.rawValue] ?? []).max() ?? 0) + 40))1050            let unsigned = psbt1051            let (signed, added): (PSBT, Int) = try await withMasterKey { master in1052                var signer = try BIP84Account(master: master, network: network)1053                defer { signer.wipe() }1054                guard signer.extendedPublicKey(slip132: false) == expectedKey else {1055                    throw WalletError.signingFailed("The recovery phrase in the vault does not match this wallet's account.")1056                }1057                var copy = unsigned1058                let n = try signer.sign(psbt: &copy, options: options, searchLimit: window)1059                return (copy, n)1060            }1061            guard added > 0 else { throw WalletError.invalidPSBT("Nothing was signed: the wallet's inputs are already signed or could not be located.") }1062            guard signed.unsignedTransaction == unsigned.unsignedTransaction else { throw WalletError.signingFailed("The transaction changed during signing.") }1063            psbt = signed1064            let after = try review(psbt, account: account)1065            return SignedPSBT(review: after, signaturesAdded: added, export: try QRExport.make(text: psbt.base64))1066        }1067    }10681069    /// Finalizes a signed PSBT (base64 text or QR frames) and broadcasts it from the online device. **Network.**1070    /// Needs a prior `syncBitcoin()`: every input must be a known unspent output of this wallet with the same amount.1071    /// Signatures are verified, the txid is computed locally and compared with the endpoint's answer.1072    public func finalizeAndBroadcastPSBT(_ input: [String]) async throws(WalletError) -> BitcoinBroadcastResult {1073        try await run {1074            var psbt = try parsePSBT(input)1075            let account = try bitcoinAccount()1076            guard let snapshot = bitcoinSnapshot, snapshot.network == account.network else {1077                throw WalletError.notSynchronized("Synchronize the Bitcoin account before broadcasting.")1078            }1079            try Self.requireFresh(snapshot)1080            let known = Dictionary(uniqueKeysWithValues: snapshot.utxos.map { ($0.utxo.outPoint, $0.utxo) })1081            var inputTotal: UInt64 = 01082            for (i, txInput) in psbt.unsignedTransaction.inputs.enumerated() {1083                guard let mine = known[txInput.previousOutput], !locallySpent.contains(txInput.previousOutput) else {1084                    throw WalletError.stalePlan("An input of the transaction is not an unspent output of this wallet.")1085                }1086                guard let claimed = psbt.spentOutput(inputIndex: i), claimed == mine.output else {1087                    throw WalletError.invalidPSBT("An input amount in the PSBT differs from what the wallet knows.")1088                }1089                inputTotal += mine.value1090            }1091            guard let outputTotal = psbt.unsignedTransaction.outputValue, inputTotal >= outputTotal else { throw WalletError.invalidPSBT("outputs exceed inputs") }1092            let fee = inputTotal - outputTotal1093            guard fee <= Self.bitcoinMaximumFee else { throw WalletError.invalidPSBT("The fee (\(fee) sat) is beyond what QYVORA broadcasts.") }1094            let reviewed = try review(psbt, account: account)1095            try enforceUnauditedBitcoinLimit(network: account.network, amount: reviewed.sentToOthers)1096            try enforceUnauditedBitcoinFeeLimit(network: account.network, fee: fee, vsize: reviewed.virtualSizeEstimate)1097            let tx: BitcoinTransaction1098            do {1099                if !psbt.isFinalized { try psbt.finalize() }1100                tx = try psbt.extractTransaction(verify: true)1101                try BitcoinVerifier.verify(transaction: tx, spentOutputs: psbt.unsignedTransaction.inputs.compactMap { known[$0.previousOutput]?.output })1102            } catch let e as PSBTError {1103                throw WalletError.invalidPSBT(WalletMessages.psbt(e))1104            } catch {1105                throw WalletError.invalidPSBT("A signature does not verify.")1106            }1107            let esplora = try await verifiedEsplora(account.network)1108            let change = tx.outputs.first { o in account.locate(scriptPubKey: o.scriptPubKey, searchLimit: 60)?.chain == .change }1109            return try await broadcastBitcoin(tx, fee: fee, esplora: esplora, changeScript: change?.scriptPubKey)1110        }1111    }1112}1113
Files main
Menu

Theme