Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Sources/QyvoraBitcoin/Account.swift8// Module : Qyvora Bitcoin9// Repository : https://git.spboucher.ai/qyvora10// Project Website : Not specified11// Created : 2026-12-0412// 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 QyvoraSymmetric44import QyvoraSecp256k145import QyvoraCore4647/// Errors of the account layer.48public enum BitcoinAccountError: Swift.Error, Equatable, Sendable {49 case invalidAccountKey50 /// The extended key prefix (xpub / zpub vs tpub / vpub) does not fit the network.51 case networkMismatch52 case indexOutOfRange53 case derivationFailed54 /// The operation needs private keys and the account is watch-only.55 case watchOnly56 /// Twenty addresses have been handed out beyond the last used one: a new one could be missed by a restore.57 case gapLimitReached58 /// The input does not spend a script of this account.59 case foreignInput(index: Int)60 case inputCountMismatch61 case signingFailed62 case unsupportedDescriptor63 /// The account purpose does not exist on the network (BIP-84 on Dogecoin or Bitcoin Cash, which have no SegWit),64 /// or the extended key prefix announces another purpose (zpub / vpub for a BIP-44 account).65 case purposeNotSupported66 /// The input is signed with the original digest, which does not commit to the amount spent, and the previous67 /// transaction proving that amount was not supplied or does not match the coin.68 case unauthenticatedInput(index: Int)69}7071/// The account type of QYVORA 1.0, kept as a name: a `UTXOAccount` whose purpose defaults to the network's72/// (BIP-84 on Bitcoin and Litecoin).73public typealias BIP84Account = UTXOAccount7475/// A single-key HD account of a UTXO network: m/purpose'/coin'/account'/chain/index, with purpose 84 (native SegWit,76/// P2WPKH: Bitcoin, Litecoin) or 44 (legacy P2PKH: Dogecoin, Bitcoin Cash, and available everywhere). Pure logic, no77/// networking. Built from a private account key it can sign; built from a public one it is watch-only.78///79/// Signatures follow the network's scheme (`BitcoinNetwork.sighashScheme`): BIP-143 for P2WPKH, the original digest80/// for P2PKH, Bitcoin Cash's fork-id digest there. Every transaction is verified with `BitcoinVerifier` under the81/// same scheme before it is returned.82public struct UTXOAccount: Sendable {83 public enum Chain: UInt32, Sendable, CaseIterable, Codable {84 /// External chain (addresses given to payers).85 case receive = 086 /// Internal chain (change).87 case change = 188 }8990 /// BIP-44 address gap limit.91 public static let gapLimit: UInt32 = 209293 public let network: BitcoinNetwork94 /// BIP-44 (P2PKH) or BIP-84 (P2WPKH).95 public let purpose: UTXOAccountPurpose96 public let accountIndex: UInt3297 /// Fingerprint of the master key, when known (key origins in descriptors and PSBTs).98 public let masterFingerprint: Bytes?99 private var accountKey: ExtendedKey100 /// Public keys of the two chains (account/0 and account/1), derived once.101 private let chainKeys: [ExtendedKey]102103 /// Script type of every address of the account.104 public var scriptType: BitcoinScriptType { purpose == .bip84 ? .p2wpkh : .p2pkh }105106 /// `accountKey` is the extended key at m/purpose'/coin'/account' (depth 3 when it comes from a standard derivation).107 /// `purpose` defaults to the network's (`BitcoinNetwork.defaultPurpose`).108 public init(accountKey: ExtendedKey, network: BitcoinNetwork, accountIndex: UInt32 = 0, masterFingerprint: Bytes? = nil,109 purpose: UTXOAccountPurpose? = nil) throws {110 guard accountIndex < ChildIndex.hardenedBit, masterFingerprint == nil || masterFingerprint?.count == 4 else {111 throw BitcoinAccountError.invalidAccountKey112 }113 let purpose = purpose ?? network.defaultPurpose114 guard network.supports(purpose) else { throw BitcoinAccountError.purposeNotSupported }115 self.purpose = purpose116 let pub = accountKey.neutered117 guard let c0 = try? pub.derive(.normal(0)), let c1 = try? pub.derive(.normal(1)) else { throw BitcoinAccountError.derivationFailed }118 self.accountKey = accountKey119 self.network = network120 self.accountIndex = accountIndex121 self.masterFingerprint = masterFingerprint122 chainKeys = [c0, c1]123 }124125 /// From the master key of a wallet: derives m/purpose'/coin'/account' and records the master fingerprint.126 public init(master: ExtendedKey, network: BitcoinNetwork, accountIndex: UInt32 = 0, purpose: UTXOAccountPurpose? = nil) throws {127 let purpose = purpose ?? network.defaultPurpose128 guard network.supports(purpose) else { throw BitcoinAccountError.purposeNotSupported }129 guard master.isPrivate, accountIndex < ChildIndex.hardenedBit,130 let key = try? master.derive(StandardPaths.account(purpose, network, account: accountIndex)) else {131 throw BitcoinAccountError.invalidAccountKey132 }133 try self.init(accountKey: key, network: network, accountIndex: accountIndex, masterFingerprint: master.fingerprint, purpose: purpose)134 }135136 /// Watch-only (or signing, with a private key) account from serialized text: xpub / tpub or SLIP-132 zpub / vpub137 /// (and the matching private prefixes). The prefix must fit the network (main or test) on every coin: QYVORA138 /// writes and reads Bitcoin's version bytes, not the coin-specific ones some wallets use (Ltub, dgub). A zpub /139 /// vpub announces BIP-84 and is refused for a BIP-44 account (`purposeNotSupported`).140 public init(extendedKey text: String, network: BitcoinNetwork, accountIndex: UInt32 = 0, masterFingerprint: Bytes? = nil,141 purpose: UTXOAccountPurpose? = nil) throws {142 guard let parsed = try? ExtendedKey.parse(text) else { throw BitcoinAccountError.invalidAccountKey }143 let test: Bool, segwitPrefix: Bool144 switch parsed.version {145 case .xpub, .xprv: (test, segwitPrefix) = (false, false)146 case .zpub, .zprv: (test, segwitPrefix) = (false, true)147 case .tpub, .tprv: (test, segwitPrefix) = (true, false)148 case .vpub, .vprv: (test, segwitPrefix) = (true, true)149 }150 guard test == network.isTest else { throw BitcoinAccountError.networkMismatch }151 if segwitPrefix, (purpose ?? network.defaultPurpose) != .bip84 { throw BitcoinAccountError.purposeNotSupported }152 try self.init(accountKey: parsed.key, network: network, accountIndex: accountIndex, masterFingerprint: masterFingerprint, purpose: purpose)153 }154155 public var isWatchOnly: Bool { !accountKey.isPrivate }156 /// m/purpose'/coin'/account'157 public var accountPath: DerivationPath { StandardPaths.account(purpose, network, account: accountIndex) }158159 /// Account public key: SLIP-132 `zpub…` / `vpub…` (what BIP-84 wallets display) or plain `xpub…` / `tpub…`160 /// (descriptors). A BIP-44 account only has the plain form.161 public func extendedPublicKey(slip132: Bool = true) -> String {162 let segwit = slip132 && purpose == .bip84163 let version: ExtendedKey.Version = network.isTest ? (segwit ? .vpub : .tpub) : (segwit ? .zpub : .xpub)164 return (try? accountKey.neutered.serialized(version)) ?? ""165 }166167 /// Receive, change and combined (multipath) descriptors, with key origin when the master fingerprint is known:168 /// `wpkh(…)` for a BIP-84 account, `pkh(…)` for a BIP-44 one.169 public func descriptors() throws -> OutputDescriptor.AccountDescriptors {170 try OutputDescriptor.account(purpose, accountKey: accountKey, network: network, account: accountIndex, masterFingerprint: masterFingerprint)171 }172173 // MARK: Derivation174175 public func path(chain: Chain, index: UInt32) -> DerivationPath {176 accountPath.appending(.normal(chain.rawValue)).appending(.normal(index))177 }178179 /// 33-byte compressed public key at chain/index.180 public func publicKey(chain: Chain, index: UInt32) throws -> Bytes {181 guard index < ChildIndex.hardenedBit else { throw BitcoinAccountError.indexOutOfRange }182 guard let key = try? chainKeys[Int(chain.rawValue)].derive(.normal(index)) else { throw BitcoinAccountError.derivationFailed }183 return key.publicKey184 }185186 public func scriptPubKey(chain: Chain, index: UInt32) throws -> Bytes {187 let key = try publicKey(chain: chain, index: index)188 guard let script = purpose == .bip84 ? try? BitcoinScript.p2wpkh(publicKey: key) : try? BitcoinScript.p2pkh(publicKey: key) else {189 throw BitcoinAccountError.derivationFailed190 }191 return script192 }193194 /// True when `scriptPubKey` has the script type of this account (which says nothing about the key).195 func hasAccountScriptType(_ scriptPubKey: Bytes) -> Bool {196 switch BitcoinScript.classify(scriptPubKey) {197 case .p2wpkh: return purpose == .bip84198 case .p2pkh: return purpose == .bip44199 default: return false200 }201 }202203 /// True when inputs of this account are signed with the original digest, which does not commit to the amounts:204 /// P2PKH everywhere except on Bitcoin Cash.205 public var requiresPreviousTransactions: Bool { purpose == .bip44 && network.sighashScheme != .bip143ForkID }206207 public func address(chain: Chain, index: UInt32) throws -> BitcoinAddress {208 guard let address = try? BitcoinAddress(scriptPubKey: try scriptPubKey(chain: chain, index: index), network: network) else {209 throw BitcoinAccountError.derivationFailed210 }211 return address212 }213214 public func addresses(chain: Chain, range: Range<UInt32>) throws -> [BitcoinAddress] {215 try range.map { try address(chain: chain, index: $0) }216 }217218 /// Private key at chain/index; the caller wipes it after use. The two extended keys of the walk (chain, then219 /// index) are erased here (QYV-CRY-003).220 func privateKey(chain: Chain, index: UInt32) throws -> Bytes {221 guard accountKey.isPrivate else { throw BitcoinAccountError.watchOnly }222 guard index < ChildIndex.hardenedBit else { throw BitcoinAccountError.indexOutOfRange }223 guard var chainKey = try? accountKey.derive(.normal(chain.rawValue)) else { throw BitcoinAccountError.derivationFailed }224 defer { chainKey.wipe() }225 guard var key = try? chainKey.derive(.normal(index)) else { throw BitcoinAccountError.derivationFailed }226 // the result shares its buffer with `key`: erasing `key` then works on a copy and leaves the result intact227 defer { key.wipe() }228 guard let k = key.privateKey else { throw BitcoinAccountError.derivationFailed }229 return k230 }231232 /// Erases the account private key held by this value; it then signs nothing (QYV-CRY-003). Call it when the233 /// signature is done: see `ExtendedKey.wipe` for what copy-on-write allows.234 public mutating func wipe() {235 accountKey.wipe()236 }237238 // MARK: Gap limit239240 /// The index to hand out next: one past the highest used index (0 for a fresh chain). Indices below it that were241 /// never used are not offered again, since they may already have been given to someone.242 /// (Saturating: the set may come from an unauthenticated file; an index beyond the non-hardened range then makes243 /// the derivation throw `indexOutOfRange` instead of trapping here. QYV-SVC-104.)244 public func nextUnusedIndex(used: Set<UInt32>) -> UInt32 { used.max().map { $0 == .max ? .max : $0 + 1 } ?? 0 }245246 /// The next address of a chain given the indices known to be used. `skipping` asks for a later one (addresses already247 /// handed out but not yet paid); beyond `gapLimit` unused addresses in a row the call throws `gapLimitReached`.248 public func nextUnusedAddress(chain: Chain, used: Set<UInt32>, skipping: UInt32 = 0) throws -> (index: UInt32, address: BitcoinAddress) {249 guard skipping < Self.gapLimit else { throw BitcoinAccountError.gapLimitReached }250 let (index, overflow) = nextUnusedIndex(used: used).addingReportingOverflow(skipping)251 guard !overflow else { throw BitcoinAccountError.indexOutOfRange }252 return (index, try address(chain: chain, index: index))253 }254255 /// The indices a scan must cover so that no payment is missed: everything up to `gapLimit` past the highest used index.256 public func scanRange(used: Set<UInt32>) -> Range<UInt32> {257 let (end, overflow) = nextUnusedIndex(used: used).addingReportingOverflow(Self.gapLimit)258 return 0..<(overflow ? .max : end)259 }260261 /// Gap-limit discovery against a set of scriptPubKeys known to have history (any chain, any wallet): walks the chain262 /// until `gapLimit` consecutive scripts are absent from the set. Returns the used indices and the next index to hand out.263 public func discover(chain: Chain, usedScripts: Set<Bytes>) throws -> (used: Set<UInt32>, nextUnused: UInt32) {264 var used = Set<UInt32>()265 var index: UInt32 = 0266 var gap: UInt32 = 0267 while gap < Self.gapLimit, index < ChildIndex.hardenedBit {268 if usedScripts.contains(try scriptPubKey(chain: chain, index: index)) {269 used.insert(index)270 gap = 0271 } else {272 gap += 1273 }274 index += 1275 }276 return (used, nextUnusedIndex(used: used))277 }278279 // MARK: Lookup280281 /// Precomputed scriptPubKey → (chain, index) table.282 public struct ScriptIndex: Sendable {283 let table: [Bytes: BitcoinUTXO.Derivation]284285 public func locate(_ scriptPubKey: Bytes) -> (chain: Chain, index: UInt32)? {286 guard let d = table[scriptPubKey], let chain = Chain(rawValue: d.chain) else { return nil }287 return (chain, d.index)288 }289290 public var count: Int { table.count }291 }292293 /// Table of the first `receiveCount` receive scripts and `changeCount` change scripts.294 public func scriptIndex(receiveCount: UInt32, changeCount: UInt32) throws -> ScriptIndex {295 var table = [Bytes: BitcoinUTXO.Derivation]()296 for i in 0..<receiveCount { table[try scriptPubKey(chain: .receive, index: i)] = .init(chain: 0, index: i) }297 for i in 0..<changeCount { table[try scriptPubKey(chain: .change, index: i)] = .init(chain: 1, index: i) }298 return ScriptIndex(table: table)299 }300301 /// Linear search of a script in the first `searchLimit` indices of both chains. For repeated lookups build a `ScriptIndex`.302 public func locate(scriptPubKey: Bytes, searchLimit: UInt32 = 100) -> (chain: Chain, index: UInt32)? {303 guard hasAccountScriptType(scriptPubKey) else { return nil }304 for i in 0..<searchLimit {305 for chain in Chain.allCases where (try? self.scriptPubKey(chain: chain, index: i)) == scriptPubKey { return (chain, i) }306 }307 return nil308 }309310 private func position(of utxo: BitcoinUTXO, searchLimit: UInt32) -> (chain: Chain, index: UInt32)? {311 if let d = utxo.derivation, let chain = Chain(rawValue: d.chain),312 (try? scriptPubKey(chain: chain, index: d.index)) == utxo.scriptPubKey {313 return (chain, d.index)314 }315 return locate(scriptPubKey: utxo.scriptPubKey, searchLimit: searchLimit)316 }317318 // MARK: Signing319320 /// Signs every input of `transaction` (SIGHASH_ALL); `utxos[i]` is the output spent by input i and must belong to this321 /// account (its `derivation` is used when present and correct, otherwise the script is searched). The result is322 /// verified before it is returned; on any error the transaction is left untouched.323 ///324 /// `previousTransactions` maps a txid (display hexadecimal) to the transaction that created a coin. It is required325 /// when `requiresPreviousTransactions` is true (P2PKH outside Bitcoin Cash: the digest does not commit to the326 /// amounts): each coin is then checked against its previous transaction — txid recomputed, amount and script327 /// compared — and the call throws `unauthenticatedInput` otherwise, so that an indexer cannot understate a coin328 /// and turn the difference into fee. Elsewhere it is optional, and checked when given.329 public func sign(transaction: inout BitcoinTransaction, spending utxos: [BitcoinUTXO], searchLimit: UInt32 = 100,330 previousTransactions: [String: BitcoinTransaction] = [:]) throws {331 guard !isWatchOnly else { throw BitcoinAccountError.watchOnly }332 guard utxos.count == transaction.inputs.count else { throw BitcoinAccountError.inputCountMismatch }333 let scheme = network.sighashScheme334 var signed = transaction335 for (i, utxo) in utxos.enumerated() {336 guard utxo.outPoint == signed.inputs[i].previousOutput, let p = position(of: utxo, searchLimit: searchLimit) else {337 throw BitcoinAccountError.foreignInput(index: i)338 }339 if let previous = previousTransactions[utxo.outPoint.txid] {340 guard utxo.isAuthenticated(by: previous) else { throw BitcoinAccountError.unauthenticatedInput(index: i) }341 } else if requiresPreviousTransactions {342 throw BitcoinAccountError.unauthenticatedInput(index: i)343 }344 var key = try privateKey(chain: p.chain, index: p.index)345 defer { SecureMemory.zero(&key) }346 do {347 switch purpose {348 case .bip84:349 try BitcoinSigner.signP2WPKH(transaction: &signed, inputIndex: i, privateKey: key, value: utxo.value, spentScriptPubKey: utxo.scriptPubKey)350 case .bip44:351 try BitcoinSigner.signP2PKH(transaction: &signed, inputIndex: i, privateKey: key, value: utxo.value,352 spentScriptPubKey: utxo.scriptPubKey, scheme: scheme)353 }354 } catch {355 throw BitcoinAccountError.signingFailed356 }357 }358 guard BitcoinVerifier.isValid(transaction: signed, spentOutputs: utxos.map(\.output), scheme: scheme) else {359 throw BitcoinAccountError.signingFailed360 }361 transaction = signed362 }363364 /// Signs a plan produced by `BitcoinTransactionBuilder` and returns the transaction ready to broadcast.365 /// A plan built for another network is refused (`networkMismatch`). See `sign(transaction:…)` for `previousTransactions`.366 public func sign(plan: BitcoinTransactionPlan, searchLimit: UInt32 = 100,367 previousTransactions: [String: BitcoinTransaction] = [:]) throws -> BitcoinTransaction {368 if let planned = plan.network, planned != network { throw BitcoinAccountError.networkMismatch }369 var tx = plan.transaction370 try sign(transaction: &tx, spending: plan.inputs, searchLimit: searchLimit, previousTransactions: previousTransactions)371 return tx372 }373374 /// The PSBT of a plan with, for the inputs and the change output that belong to the account, their BIP-32 derivations375 /// (when the master fingerprint is known). A BIP-44 account needs the previous transaction of every input376 /// (`PSBTError.nonWitnessUTXORequired` otherwise): without it no signer can sign a P2PKH input.377 public func psbt(for plan: BitcoinTransactionPlan, searchLimit: UInt32 = 100,378 previousTransactions: [String: BitcoinTransaction] = [:]) throws -> PSBT {379 if let planned = plan.network, planned != network { throw BitcoinAccountError.networkMismatch }380 var psbt = try plan.psbt(previousTransactions: previousTransactions)381 psbt.prepare(for: network)382 guard let fingerprint = masterFingerprint else { return psbt }383 for (i, utxo) in plan.inputs.enumerated() {384 guard let p = position(of: utxo, searchLimit: searchLimit) else { continue }385 try psbt.addInputDerivation(.init(publicKey: try publicKey(chain: p.chain, index: p.index), fingerprint: fingerprint,386 path: path(chain: p.chain, index: p.index)), inputIndex: i)387 }388 if let c = plan.changeIndex, let p = locate(scriptPubKey: plan.transaction.outputs[c].scriptPubKey, searchLimit: searchLimit) {389 try psbt.addOutputDerivation(.init(publicKey: try publicKey(chain: p.chain, index: p.index), fingerprint: fingerprint,390 path: path(chain: p.chain, index: p.index)), outputIndex: c)391 }392 return psbt393 }394395 /// Signer role with the account's keys: signs the inputs (P2WPKH or P2PKH, according to the purpose) that spend396 /// scripts of this account, located through the PSBT's BIP-32 derivations (matching master fingerprint and account397 /// path) or by searching the first `searchLimit` indices. All the signer checks of `PSBT.sign` apply, under the398 /// signature scheme of the account's network (the PSBT is prepared for it). Returns the number of signatures added.399 ///400 /// A previous transaction that is not the one its outpoint names fails the whole call (`nonWitnessUTXOMismatch`).401 /// Where the account's signatures do not commit to the amounts, or the network has no SegWit (Dogecoin, Bitcoin402 /// Cash, BIP-44 accounts), nothing is signed unless the fee of the whole transaction is known from authenticated403 /// previous outputs (`missingUTXO` otherwise): signing one input of a transaction whose other amounts are unknown404 /// is how a fee is burned in two rounds (QYV-SVC-064).405 @discardableResult406 public func sign(psbt: inout PSBT, options: PSBT.SigningOptions = PSBT.SigningOptions(), searchLimit: UInt32 = 100) throws -> Int {407 guard !isWatchOnly else { throw BitcoinAccountError.watchOnly }408 var copy = psbt409 copy.prepare(for: network)410 try copy.checkPreviousTransactions()411 if requiresPreviousTransactions || network.sighashScheme != .bip143 {412 // every amount must come from a previous transaction (a witness-UTXO record authenticates nothing here)413 guard copy.inputs.allSatisfy({ $0.nonWitnessUTXO != nil }) else { throw PSBTError.nonWitnessUTXORequired }414 guard copy.fee != nil else { throw PSBTError.missingUTXO }415 }416 var added = 0417 let prefix = accountPath.indices418 for i in copy.inputs.indices where !copy.inputs[i].isFinalized {419 guard let utxo = copy.spentOutput(inputIndex: i), hasAccountScriptType(utxo.scriptPubKey) else { continue }420 var found: (chain: Chain, index: UInt32)?421 for d in copy.inputs[i].derivations where d.fingerprint == masterFingerprint && d.path.indices.count == prefix.count + 2422 && Array(d.path.indices.prefix(prefix.count)) == prefix {423 let tail = d.path.indices.suffix(2).map { $0 }424 if !tail[0].isHardened, !tail[1].isHardened, let chain = Chain(rawValue: tail[0].index),425 (try? scriptPubKey(chain: chain, index: tail[1].index)) == utxo.scriptPubKey {426 found = (chain, tail[1].index)427 }428 }429 if found == nil { found = locate(scriptPubKey: utxo.scriptPubKey, searchLimit: searchLimit) }430 guard let p = found else { continue }431 var key = try privateKey(chain: p.chain, index: p.index)432 defer { SecureMemory.zero(&key) }433 if try copy.sign(inputIndex: i, privateKey: key, options: options) { added += 1 }434 }435 psbt = copy436 return added437 }438}439440/// A P2WSH multisig wallet described by a descriptor: `wsh(multi(k,…))` or `wsh(sortedmulti(k,…))` with ranged keys.441/// Receive and change chains come from a multipath descriptor (`/<0;1>/*`) or from two descriptors.442public struct MultisigAccount: Sendable {443 public let network: BitcoinNetwork444 public let receiveDescriptor: OutputDescriptor445 /// nil when the wallet description has no separate change chain.446 public let changeDescriptor: OutputDescriptor?447448 public init(descriptor: OutputDescriptor, changeDescriptor: OutputDescriptor? = nil, network: BitcoinNetwork) throws {449 // P2WSH needs SegWit: no multisig wallet of this kind on Dogecoin or Bitcoin Cash450 guard network.supportsSegWit else { throw BitcoinAccountError.unsupportedDescriptor }451 var receive = descriptor452 var change = changeDescriptor453 if descriptor.multipathCount > 1 {454 guard descriptor.multipathCount == 2, changeDescriptor == nil else { throw BitcoinAccountError.unsupportedDescriptor }455 guard let r = try? descriptor.singlePath(0), let c = try? descriptor.singlePath(1) else { throw BitcoinAccountError.unsupportedDescriptor }456 receive = r457 change = c458 }459 for d in [receive] + (change.map { [$0] } ?? []) {460 switch d.kind {461 case .wshMulti, .wshSortedMulti: break462 case .wpkh, .pkh: throw BitcoinAccountError.unsupportedDescriptor463 }464 guard d.multipathCount == 1 else { throw BitcoinAccountError.unsupportedDescriptor }465 if let test = d.isTestNetwork, test != network.isTest { throw BitcoinAccountError.networkMismatch }466 }467 if let c = change, c.kind != receive.kind || c.keys.count != receive.keys.count { throw BitcoinAccountError.unsupportedDescriptor }468 self.network = network469 self.receiveDescriptor = receive470 self.changeDescriptor = change471 }472473 /// Parses the descriptor text (checksum verified when present).474 public init(descriptor text: String, changeDescriptor changeText: String? = nil, network: BitcoinNetwork) throws {475 guard let d = try? OutputDescriptor(parsing: text) else { throw BitcoinAccountError.unsupportedDescriptor }476 var c: OutputDescriptor?477 if let changeText {478 guard let parsed = try? OutputDescriptor(parsing: changeText) else { throw BitcoinAccountError.unsupportedDescriptor }479 c = parsed480 }481 try self.init(descriptor: d, changeDescriptor: c, network: network)482 }483484 /// Signatures needed to spend.485 public var required: Int {486 switch receiveDescriptor.kind {487 case .wshMulti(let k), .wshSortedMulti(let k): return k488 case .wpkh, .pkh: return 1489 }490 }491 /// Number of cosigner keys.492 public var total: Int { receiveDescriptor.keys.count }493494 private func descriptor(_ chain: BIP84Account.Chain) throws -> OutputDescriptor {495 if chain == .receive { return receiveDescriptor }496 guard let c = changeDescriptor else { throw BitcoinAccountError.unsupportedDescriptor }497 return c498 }499500 public func witnessScript(chain: BIP84Account.Chain, index: UInt32) throws -> Bytes {501 let d = try descriptor(chain)502 guard let s = try? d.witnessScript(index: index) else { throw BitcoinAccountError.derivationFailed }503 return s504 }505506 public func scriptPubKey(chain: BIP84Account.Chain, index: UInt32) throws -> Bytes {507 let script = try witnessScript(chain: chain, index: index)508 guard let s = try? BitcoinScript.p2wsh(witnessScript: script) else { throw BitcoinAccountError.derivationFailed }509 return s510 }511512 public func address(chain: BIP84Account.Chain, index: UInt32) throws -> BitcoinAddress {513 let script = try scriptPubKey(chain: chain, index: index)514 guard let a = try? BitcoinAddress(scriptPubKey: script, network: network) else { throw BitcoinAccountError.derivationFailed }515 return a516 }517518 /// Linear search of a script in the first `searchLimit` indices of the chains.519 public func locate(scriptPubKey: Bytes, searchLimit: UInt32 = 50) -> (chain: BIP84Account.Chain, index: UInt32)? {520 guard case .p2wsh = BitcoinScript.classify(scriptPubKey) else { return nil }521 let chains: [BIP84Account.Chain] = changeDescriptor == nil ? [.receive] : [.receive, .change]522 for i in 0..<searchLimit {523 for chain in chains where (try? self.scriptPubKey(chain: chain, index: i)) == scriptPubKey { return (chain, i) }524 }525 return nil526 }527528 /// Updater role: for every input and output paying to a script of this wallet, adds the witness script and the BIP-32529 /// derivations of the cosigner keys that have an origin. Returns the number of inputs recognised.530 @discardableResult531 public func update(psbt: inout PSBT, searchLimit: UInt32 = 50) throws -> Int {532 var recognised = 0533 func derivations(_ chain: BIP84Account.Chain, _ index: UInt32) throws -> [PSBT.KeyDerivation] {534 try descriptor(chain).keys.compactMap { key in535 guard let origin = key.origin, let path = key.fullPath(index: index),536 let publicKey = try? key.publicKey(index: index) else { return nil }537 return PSBT.KeyDerivation(publicKey: publicKey, fingerprint: origin.fingerprint, path: path)538 }539 }540 for i in psbt.inputs.indices where !psbt.inputs[i].isFinalized {541 guard let utxo = psbt.spentOutput(inputIndex: i), let p = locate(scriptPubKey: utxo.scriptPubKey, searchLimit: searchLimit) else { continue }542 try psbt.setWitnessScript(try witnessScript(chain: p.chain, index: p.index), inputIndex: i)543 for d in try derivations(p.chain, p.index) { try psbt.addInputDerivation(d, inputIndex: i) }544 recognised += 1545 }546 for i in psbt.outputs.indices {547 guard let p = locate(scriptPubKey: psbt.unsignedTransaction.outputs[i].scriptPubKey, searchLimit: searchLimit) else { continue }548 try psbt.setOutputScripts(witnessScript: try witnessScript(chain: p.chain, index: p.index), outputIndex: i)549 for d in try derivations(p.chain, p.index) { try psbt.addOutputDerivation(d, outputIndex: i) }550 }551 return recognised552 }553554 /// Signer role for one cosigner: `cosignerKey` is the private extended key whose public part is one of the descriptor's555 /// extended keys. Inputs of this wallet are located, given their witness script if they lack it, and signed.556 /// Returns the number of signatures added.557 @discardableResult558 public func sign(psbt: inout PSBT, cosignerKey: ExtendedKey, options: PSBT.SigningOptions = PSBT.SigningOptions(),559 searchLimit: UInt32 = 50) throws -> Int {560 guard cosignerKey.isPrivate else { throw BitcoinAccountError.watchOnly }561 guard let position = receiveDescriptor.keys.firstIndex(where: {562 $0.extendedKey?.publicKey == cosignerKey.publicKey && $0.extendedKey?.chainCode == cosignerKey.chainCode563 }) else { throw BitcoinAccountError.invalidAccountKey }564 var copy = psbt565 var added = 0566 for i in copy.inputs.indices where !copy.inputs[i].isFinalized {567 guard let utxo = copy.spentOutput(inputIndex: i), let p = locate(scriptPubKey: utxo.scriptPubKey, searchLimit: searchLimit) else { continue }568 if copy.inputs[i].witnessScript == nil { try copy.setWitnessScript(try witnessScript(chain: p.chain, index: p.index), inputIndex: i) }569 let key = try descriptor(p.chain).keys[position]570 var child = cosignerKey571 do {572 for step in key.steps {573 guard case .index(let n) = step else { throw BitcoinAccountError.unsupportedDescriptor }574 child = try child.derive(.normal(n))575 }576 if key.wildcard { child = try child.derive(.normal(p.index)) }577 } catch {578 throw BitcoinAccountError.derivationFailed579 }580 guard var secret = child.privateKey else { throw BitcoinAccountError.derivationFailed }581 defer { SecureMemory.zero(&secret) }582 if try copy.sign(inputIndex: i, privateKey: secret, options: options) { added += 1 }583 }584 psbt = copy585 return added586 }587}588