Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Sources/QyvoraBitcoin/PSBT.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 PSBT format and of its roles (BIP-174).48public enum PSBTError: Swift.Error, Equatable, Sendable {49 // Format50 case invalidBase6451 case invalidMagic52 case duplicateKey53 case missingUnsignedTransaction54 /// The unsigned transaction carries a scriptSig or a witness.55 case unsignedTransactionNotEmpty56 case unsupportedVersion(UInt32)57 /// A known field has a key or a value of the wrong shape (the text names it).58 case invalidField(String)59 case serialization(BitcoinSerializationError)60 // Roles61 case inputIndexOutOfRange62 case outputIndexOutOfRange63 case missingUTXO64 /// The non-witness UTXO does not hash to the outpoint txid, or lacks the output index.65 case nonWitnessUTXOMismatch66 /// Witness UTXO, non-witness UTXO or the caller's expected UTXO disagree on amount or script.67 case utxoMismatch68 /// A legacy input cannot be signed from a witness UTXO alone.69 case witnessUTXOForNonWitnessInput70 case nonWitnessUTXORequired71 case missingRedeemScript72 case redeemScriptMismatch73 case missingWitnessScript74 case witnessScriptMismatch75 case unsupportedScript76 case sighashTypeNotAllowed77 case invalidPrivateKey78 case invalidSignature79 case notEnoughSignatures80 /// Combiner: the PSBTs do not describe the same unsigned transaction.81 case differentTransactions82 case notFinalized83 case nothingToCombine84}8586/// Partially Signed Bitcoin Transaction, version 0 (BIP-174).87///88/// The model types the fields QYVORA acts on; every other key-value pair (global xpubs, proprietary and Taproot89/// fields, future types) is kept verbatim in the `unknown` lists and written back unchanged.90public struct PSBT: Equatable, Sendable {91 /// A key-value pair kept verbatim. `key` is the full key: type (CompactSize) followed by the key data.92 public struct Record: Equatable, Hashable, Sendable {93 public let key: Bytes94 public let value: Bytes9596 public init(key: Bytes, value: Bytes) {97 self.key = key98 self.value = value99 }100101 /// Type of the record (first CompactSize of the key).102 public var type: UInt64 {103 var r = ByteReader(key)104 return (try? r.varInt()) ?? 0105 }106 }107108 /// BIP-32 derivation of a public key: master fingerprint and full path.109 public struct KeyDerivation: Equatable, Hashable, Sendable {110 public let publicKey: Bytes111 /// 4 bytes.112 public let fingerprint: Bytes113 public let path: DerivationPath114115 public init(publicKey: Bytes, fingerprint: Bytes, path: DerivationPath) {116 self.publicKey = publicKey117 self.fingerprint = fingerprint118 self.path = path119 }120 }121122 public struct Input: Equatable, Sendable {123 /// Full previous transaction (PSBT_IN_NON_WITNESS_UTXO).124 public var nonWitnessUTXO: BitcoinTransaction?125 /// The spent output alone (PSBT_IN_WITNESS_UTXO); enough for SegWit inputs.126 public var witnessUTXO: BitcoinTransaction.Output?127 public var partialSignatures: [BitcoinPartialSignature] = []128 public var sighashType: BitcoinSighashType?129 public var redeemScript: Bytes?130 public var witnessScript: Bytes?131 public var derivations: [KeyDerivation] = []132 public var finalScriptSig: Bytes?133 public var finalScriptWitness: [Bytes]?134 public var unknown: [Record] = []135136 public init() {}137138 public var isFinalized: Bool { finalScriptSig != nil || finalScriptWitness != nil }139 }140141 public struct Output: Equatable, Sendable {142 public var redeemScript: Bytes?143 public var witnessScript: Bytes?144 public var derivations: [KeyDerivation] = []145 public var unknown: [Record] = []146147 public init() {}148 }149150 /// The transaction being built; its scriptSigs and witnesses are always empty.151 public private(set) var unsignedTransaction: BitcoinTransaction152 public var inputs: [Input]153 public var outputs: [Output]154 /// PSBT_GLOBAL_VERSION when present (always 0 here).155 public private(set) var version: UInt32?156 /// Global records QYVORA does not interpret (PSBT_GLOBAL_XPUB, proprietary…).157 public var unknown: [Record] = []158 /// How input digests are computed (`BitcoinNetwork.sighashScheme`). It is not part of the BIP-174 serialization: a159 /// parsed PSBT starts with Bitcoin's scheme, and the party that knows the network sets it (`prepare(for:)`) before160 /// signing, finalizing or extracting. Under Dogecoin's and Bitcoin Cash's schemes only non-SegWit inputs exist, so161 /// every input needs its previous transaction; under Bitcoin Cash's, signatures carry SIGHASH_FORKID (0x41) and162 /// an input's PSBT_IN_SIGHASH_TYPE, when present, must carry it too.163 public var sighashScheme: UTXOSighashScheme = .bip143164 /// Monetary range used by the amount checks (`BitcoinNetwork.maximumMoney`); Bitcoin's by default.165 public var maximumMoney: UInt64 = BitcoinLimits.maxMoney166167 /// Sets the signature scheme and the monetary range of `network`.168 public mutating func prepare(for network: BitcoinNetwork) {169 sighashScheme = network.sighashScheme170 maximumMoney = network.maximumMoney171 }172173 static let magic: Bytes = [0x70, 0x73, 0x62, 0x74, 0xff]174175 // MARK: Creator176177 /// Creator role: a PSBT around an unsigned transaction, with one empty map per input and output.178 public init(unsignedTransaction tx: BitcoinTransaction) throws {179 guard tx.inputs.allSatisfy({ $0.scriptSig.isEmpty && $0.witness.isEmpty }) else { throw PSBTError.unsignedTransactionNotEmpty }180 unsignedTransaction = tx181 inputs = Array(repeating: Input(), count: tx.inputs.count)182 outputs = Array(repeating: Output(), count: tx.outputs.count)183 }184185 // MARK: Parsing186187 public init(base64 text: String) throws {188 guard let data = Data(base64Encoded: text) else { throw PSBTError.invalidBase64 }189 try self.init(parsing: Bytes(data))190 }191192 public init(hex: String) throws {193 guard let data = Hex.decode(hex) else { throw PSBTError.serialization(.malformed("hexadecimal")) }194 try self.init(parsing: data)195 }196197 /// Strict binary parser: magic, no duplicate key in a map, shapes of the known fields, an unsigned transaction without198 /// scriptSig or witness, one map per input and output, non-witness UTXOs matching their outpoints, no trailing byte.199 public init(parsing data: Bytes) throws {200 do {201 self = try PSBT(strict: data)202 } catch let e as PSBTError {203 throw e204 } catch let e as BitcoinSerializationError {205 throw PSBTError.serialization(e)206 } catch {207 throw PSBTError.serialization(.malformed("psbt"))208 }209 }210211 private static func readMap(_ r: inout ByteReader) throws -> [(type: UInt64, keyData: Bytes, record: Record)] {212 var out = [(type: UInt64, keyData: Bytes, record: Record)]()213 var seen = Set<Bytes>()214 while true {215 let keyLength = try r.varInt()216 if keyLength == 0 { return out }217 guard keyLength <= UInt64(r.remaining) else { throw BitcoinSerializationError.truncated }218 let key = try r.take(Int(keyLength))219 let value = try r.varBytes()220 guard seen.insert(key).inserted else { throw PSBTError.duplicateKey }221 var kr = ByteReader(key)222 let type = try kr.varInt()223 out.append((type, try kr.take(kr.remaining), Record(key: key, value: value)))224 }225 }226227 private static func derivation(keyData: Bytes, value: Bytes, _ name: String) throws -> KeyDerivation {228 guard keyData.count == 33 || keyData.count == 65, Secp256k1.isValidPublicKey(keyData) else { throw PSBTError.invalidField(name + " public key") }229 guard value.count >= 4, value.count % 4 == 0 else { throw PSBTError.invalidField(name + " value") }230 var indices = [ChildIndex]()231 var i = 4232 while i < value.count {233 indices.append(ChildIndex(raw: UInt32(value[i]) | UInt32(value[i + 1]) << 8 | UInt32(value[i + 2]) << 16 | UInt32(value[i + 3]) << 24))234 i += 4235 }236 return KeyDerivation(publicKey: keyData, fingerprint: Bytes(value[0..<4]), path: DerivationPath(indices))237 }238239 private static func witnessStack(_ value: Bytes) throws -> [Bytes] {240 var r = ByteReader(value)241 let n = try r.count(minimumItemSize: 1)242 var stack = [Bytes]()243 for _ in 0..<n { stack.append(try r.varBytes()) }244 guard r.isAtEnd else { throw PSBTError.invalidField("final script witness") }245 return stack246 }247248 private init(strict data: Bytes) throws {249 guard data.count >= 5, Bytes(data[0..<5]) == Self.magic else { throw PSBTError.invalidMagic }250 var r = ByteReader(Bytes(data[5...]))251 var tx: BitcoinTransaction?252 var version: UInt32?253 var globalUnknown = [Record]()254 for entry in try Self.readMap(&r) {255 switch entry.type {256 case 0x00:257 guard entry.keyData.isEmpty else { throw PSBTError.invalidField("global unsigned transaction key") }258 let parsed = try BitcoinTransaction(parsing: entry.record.value, allowWitness: false)259 guard parsed.inputs.allSatisfy({ $0.scriptSig.isEmpty }) else { throw PSBTError.unsignedTransactionNotEmpty }260 tx = parsed261 case 0xfb:262 guard entry.keyData.isEmpty, entry.record.value.count == 4 else { throw PSBTError.invalidField("global version") }263 var vr = ByteReader(entry.record.value)264 let v = try vr.u32()265 guard v == 0 else { throw PSBTError.unsupportedVersion(v) }266 version = v267 default:268 globalUnknown.append(entry.record)269 }270 }271 guard let tx else { throw PSBTError.missingUnsignedTransaction }272 var ins = [Input]()273 for txInput in tx.inputs {274 var input = Input()275 for entry in try Self.readMap(&r) {276 let value = entry.record.value277 func emptyKey(_ name: String) throws {278 guard entry.keyData.isEmpty else { throw PSBTError.invalidField(name + " key") }279 }280 switch entry.type {281 case 0x00:282 try emptyKey("non-witness UTXO")283 input.nonWitnessUTXO = try BitcoinTransaction(parsing: value)284 case 0x01:285 try emptyKey("witness UTXO")286 var vr = ByteReader(value)287 let amount = try vr.u64()288 let script = try vr.varBytes()289 guard vr.isAtEnd else { throw PSBTError.invalidField("witness UTXO value") }290 input.witnessUTXO = BitcoinTransaction.Output(value: amount, scriptPubKey: script)291 case 0x02:292 guard entry.keyData.count == 33 || entry.keyData.count == 65, Secp256k1.isValidPublicKey(entry.keyData) else {293 throw PSBTError.invalidField("partial signature public key")294 }295 input.partialSignatures.append(BitcoinPartialSignature(publicKey: entry.keyData, signature: value))296 case 0x03:297 try emptyKey("sighash type")298 guard value.count == 4 else { throw PSBTError.invalidField("sighash type value") }299 var vr = ByteReader(value)300 input.sighashType = BitcoinSighashType(rawValue: try vr.u32())301 case 0x04:302 try emptyKey("redeem script")303 input.redeemScript = value304 case 0x05:305 try emptyKey("witness script")306 input.witnessScript = value307 case 0x06:308 input.derivations.append(try Self.derivation(keyData: entry.keyData, value: value, "input BIP-32 derivation"))309 case 0x07:310 try emptyKey("final scriptSig")311 input.finalScriptSig = value312 case 0x08:313 try emptyKey("final script witness")314 input.finalScriptWitness = try Self.witnessStack(value)315 default:316 input.unknown.append(entry.record)317 }318 }319 if let previous = input.nonWitnessUTXO {320 guard previous.txidBytes == txInput.previousOutput.hash, Int(txInput.previousOutput.index) < previous.outputs.count else {321 throw PSBTError.nonWitnessUTXOMismatch322 }323 }324 ins.append(input)325 }326 var outs = [Output]()327 for _ in tx.outputs {328 var output = Output()329 for entry in try Self.readMap(&r) {330 switch entry.type {331 case 0x00:332 guard entry.keyData.isEmpty else { throw PSBTError.invalidField("output redeem script key") }333 output.redeemScript = entry.record.value334 case 0x01:335 guard entry.keyData.isEmpty else { throw PSBTError.invalidField("output witness script key") }336 output.witnessScript = entry.record.value337 case 0x02:338 output.derivations.append(try Self.derivation(keyData: entry.keyData, value: entry.record.value, "output BIP-32 derivation"))339 default:340 output.unknown.append(entry.record)341 }342 }343 outs.append(output)344 }345 guard r.isAtEnd else { throw BitcoinSerializationError.trailingBytes }346 unsignedTransaction = tx347 inputs = ins348 outputs = outs349 self.version = version350 unknown = globalUnknown351 }352353 // MARK: Serialization354355 private static func record(_ type: UInt8, _ keyData: Bytes = [], _ value: Bytes) -> Bytes {356 Wire.varBytes([type] + keyData) + Wire.varBytes(value)357 }358359 private static func derivationValue(_ d: KeyDerivation) -> Bytes {360 d.fingerprint + d.path.indices.flatMap { Wire.u32($0.raw) }361 }362363 /// Binary form. Known fields are written in type order, multi-valued fields and unknown records in stored order.364 public func serialized() -> Bytes {365 var out = Self.magic366 out += Self.record(0x00, [], unsignedTransaction.serialized(includeWitness: false))367 var versionWritten = version == nil368 for u in unknown {369 if !versionWritten, u.type >= 0xfb, let version {370 out += Self.record(0xfb, [], Wire.u32(version))371 versionWritten = true372 }373 out += Wire.varBytes(u.key) + Wire.varBytes(u.value)374 }375 if !versionWritten, let version { out += Self.record(0xfb, [], Wire.u32(version)) }376 out.append(0x00)377 for i in inputs {378 if let t = i.nonWitnessUTXO { out += Self.record(0x00, [], t.serialized()) }379 if let u = i.witnessUTXO { out += Self.record(0x01, [], u.serialized) }380 for s in i.partialSignatures { out += Self.record(0x02, s.publicKey, s.signature) }381 if let t = i.sighashType { out += Self.record(0x03, [], Wire.u32(t.rawValue)) }382 if let s = i.redeemScript { out += Self.record(0x04, [], s) }383 if let s = i.witnessScript { out += Self.record(0x05, [], s) }384 for d in i.derivations { out += Self.record(0x06, d.publicKey, Self.derivationValue(d)) }385 if let s = i.finalScriptSig { out += Self.record(0x07, [], s) }386 if let w = i.finalScriptWitness {387 out += Self.record(0x08, [], Wire.varInt(w.count) + w.flatMap { Wire.varBytes($0) })388 }389 for u in i.unknown { out += Wire.varBytes(u.key) + Wire.varBytes(u.value) }390 out.append(0x00)391 }392 for o in outputs {393 if let s = o.redeemScript { out += Self.record(0x00, [], s) }394 if let s = o.witnessScript { out += Self.record(0x01, [], s) }395 for d in o.derivations { out += Self.record(0x02, d.publicKey, Self.derivationValue(d)) }396 for u in o.unknown { out += Wire.varBytes(u.key) + Wire.varBytes(u.value) }397 out.append(0x00)398 }399 return out400 }401402 public var base64: String { Data(serialized()).base64EncodedString() }403 public var hex: String { Hex.encode(serialized()) }404405 /// The same PSBT with multi-valued fields in lexicographic key order (to compare PSBTs regardless of insertion order).406 public var normalized: PSBT {407 var copy = self408 copy.unknown.sort { lexicographicallyPrecedes($0.key, $1.key) }409 for i in copy.inputs.indices {410 copy.inputs[i].partialSignatures.sort { lexicographicallyPrecedes($0.publicKey, $1.publicKey) }411 copy.inputs[i].derivations.sort { lexicographicallyPrecedes($0.publicKey, $1.publicKey) }412 copy.inputs[i].unknown.sort { lexicographicallyPrecedes($0.key, $1.key) }413 }414 for i in copy.outputs.indices {415 copy.outputs[i].derivations.sort { lexicographicallyPrecedes($0.publicKey, $1.publicKey) }416 copy.outputs[i].unknown.sort { lexicographicallyPrecedes($0.key, $1.key) }417 }418 return copy419 }420421 // MARK: Updater422423 private func checkInput(_ index: Int) throws {424 guard inputs.indices.contains(index) else { throw PSBTError.inputIndexOutOfRange }425 }426427 /// Updater: attaches the spent output of a SegWit input. Must agree with a non-witness UTXO already present.428 public mutating func setWitnessUTXO(_ utxo: BitcoinTransaction.Output, inputIndex: Int) throws {429 try checkInput(inputIndex)430 if let previous = inputs[inputIndex].nonWitnessUTXO {431 let n = Int(unsignedTransaction.inputs[inputIndex].previousOutput.index)432 guard n < previous.outputs.count, previous.outputs[n] == utxo else { throw PSBTError.utxoMismatch }433 }434 inputs[inputIndex].witnessUTXO = utxo435 }436437 /// Updater: attaches the full previous transaction; it must hash to the outpoint txid and hold the output index.438 public mutating func setNonWitnessUTXO(_ transaction: BitcoinTransaction, inputIndex: Int) throws {439 try checkInput(inputIndex)440 let outPoint = unsignedTransaction.inputs[inputIndex].previousOutput441 guard transaction.txidBytes == outPoint.hash, Int(outPoint.index) < transaction.outputs.count else { throw PSBTError.nonWitnessUTXOMismatch }442 if let w = inputs[inputIndex].witnessUTXO, w != transaction.outputs[Int(outPoint.index)] { throw PSBTError.utxoMismatch }443 inputs[inputIndex].nonWitnessUTXO = transaction444 }445446 public mutating func setSighashType(_ type: BitcoinSighashType?, inputIndex: Int) throws {447 try checkInput(inputIndex)448 inputs[inputIndex].sighashType = type449 }450451 /// Updater: the P2SH redeem script. When the UTXO is known, the script must hash to it.452 public mutating func setRedeemScript(_ script: Bytes, inputIndex: Int) throws {453 try checkInput(inputIndex)454 if let utxo = spentOutput(inputIndex: inputIndex) {455 guard case .p2sh(let hash) = BitcoinScript.classify(utxo.scriptPubKey), Hash160.hash(script) == hash else {456 throw PSBTError.redeemScriptMismatch457 }458 }459 inputs[inputIndex].redeemScript = script460 }461462 /// Updater: the P2WSH witness script. When the UTXO (or the redeem script) is known, the script must hash to it.463 public mutating func setWitnessScript(_ script: Bytes, inputIndex: Int) throws {464 try checkInput(inputIndex)465 var program: Bytes?466 if let redeem = inputs[inputIndex].redeemScript {467 program = redeem468 } else if let utxo = spentOutput(inputIndex: inputIndex), BitcoinScript.classify(utxo.scriptPubKey).type != .p2sh {469 program = utxo.scriptPubKey470 }471 if let program {472 guard case .p2wsh(let hash) = BitcoinScript.classify(program), SHA256.hash(script) == hash else {473 throw PSBTError.witnessScriptMismatch474 }475 }476 inputs[inputIndex].witnessScript = script477 }478479 private static func insert(_ d: KeyDerivation, into list: inout [KeyDerivation]) throws {480 guard d.fingerprint.count == 4, Secp256k1.isValidPublicKey(d.publicKey) else { throw PSBTError.invalidField("BIP-32 derivation") }481 list.removeAll { $0.publicKey == d.publicKey }482 list.append(d)483 list.sort { lexicographicallyPrecedes($0.publicKey, $1.publicKey) }484 }485486 /// Updater: records where a key of the input comes from (kept sorted by public key).487 public mutating func addInputDerivation(_ derivation: KeyDerivation, inputIndex: Int) throws {488 try checkInput(inputIndex)489 try Self.insert(derivation, into: &inputs[inputIndex].derivations)490 }491492 /// Updater: records where a key of an output (typically the change) comes from.493 public mutating func addOutputDerivation(_ derivation: KeyDerivation, outputIndex: Int) throws {494 guard outputs.indices.contains(outputIndex) else { throw PSBTError.outputIndexOutOfRange }495 try Self.insert(derivation, into: &outputs[outputIndex].derivations)496 }497498 public mutating func setOutputScripts(redeemScript: Bytes? = nil, witnessScript: Bytes? = nil, outputIndex: Int) throws {499 guard outputs.indices.contains(outputIndex) else { throw PSBTError.outputIndexOutOfRange }500 if let redeemScript { outputs[outputIndex].redeemScript = redeemScript }501 if let witnessScript { outputs[outputIndex].witnessScript = witnessScript }502 }503504 // MARK: Inspection505506 /// The output spent by an input according to the PSBT (non-witness UTXO first), nil when the PSBT does not say.507 ///508 /// A previous transaction counts only when it hashes to the identifier of the outpoint: parsing and509 /// `setNonWitnessUTXO` already refuse any other, and `inputs` is a public property, so the check is made again510 /// here — an amount read from a transaction that is not the one spent is never reported (QYV-SVC-064).511 public func spentOutput(inputIndex: Int) -> BitcoinTransaction.Output? {512 guard inputs.indices.contains(inputIndex), unsignedTransaction.inputs.indices.contains(inputIndex) else { return nil }513 if let previous = inputs[inputIndex].nonWitnessUTXO {514 let outPoint = unsignedTransaction.inputs[inputIndex].previousOutput515 let n = Int(outPoint.index)516 return n < previous.outputs.count && previous.txidBytes == outPoint.hash ? previous.outputs[n] : nil517 }518 return inputs[inputIndex].witnessUTXO519 }520521 /// Throws `nonWitnessUTXOMismatch` unless every previous transaction an input carries is the one its outpoint names.522 func checkPreviousTransactions() throws {523 for i in inputs.indices where inputs[i].nonWitnessUTXO != nil && spentOutput(inputIndex: i) == nil { throw PSBTError.nonWitnessUTXOMismatch }524 }525526 /// Inputs minus outputs when every UTXO is known and the result is not negative.527 ///528 /// Under Dogecoin's and Bitcoin Cash's schemes every input needs its previous transaction: one that only carries529 /// a PSBT_IN_WITNESS_UTXO record states an amount nothing authenticates (Dogecoin's digest does not commit to530 /// it) and that no signer here accepts, so the fee is unknown (nil) rather than computed from it (QYV-SVC-064).531 public var fee: UInt64? {532 var total: UInt64 = 0533 for i in inputs.indices {534 if sighashScheme != .bip143, inputs[i].nonWitnessUTXO == nil { return nil }535 guard let utxo = spentOutput(inputIndex: i), utxo.value <= maximumMoney else { return nil }536 // checked at every step: thousands of inputs each claiming 21 million bitcoin must not overflow the sum537 let (sum, overflow) = total.addingReportingOverflow(utxo.value)538 guard !overflow, sum <= maximumMoney else { return nil }539 total = sum540 }541 guard let out = unsignedTransaction.outputValue(maximumMoney: maximumMoney), total >= out else { return nil }542 return total - out543 }544545 public var isFinalized: Bool { !inputs.isEmpty && inputs.allSatisfy(\.isFinalized) }546547 // MARK: Signer548549 public struct SigningOptions: Sendable {550 /// SIGHASH types the signer accepts; a PSBT asking for another one is refused. Default: ALL only.551 public var allowedSighashTypes: Set<BitcoinSighashType> = [.all]552 /// Refuse SegWit inputs that only carry a witness UTXO (defence against the BIP-143 fee attack when the wallet553 /// has no independent knowledge of the amounts).554 public var requireNonWitnessUTXO = false555 /// UTXOs the wallet knows by itself: an input spending one of these outpoints must show exactly this amount and script.556 public var expectedUTXOs: [BitcoinOutPoint: BitcoinTransaction.Output] = [:]557558 public init(allowedSighashTypes: Set<BitcoinSighashType> = [.all], requireNonWitnessUTXO: Bool = false,559 expectedUTXOs: [BitcoinOutPoint: BitcoinTransaction.Output] = [:]) {560 self.allowedSighashTypes = allowedSighashTypes561 self.requireNonWitnessUTXO = requireNonWitnessUTXO562 self.expectedUTXOs = expectedUTXOs563 }564 }565566 /// What an input needs to be signed and finalized, after all the BIP-174 signer checks.567 struct SigningContext {568 enum Kind {569 case p2wpkh(hash: Bytes)570 case p2wshMultisig(script: Bytes)571 case p2pkh(hash: Bytes)572 case legacyMultisig(script: Bytes)573 }574 let kind: Kind575 let utxo: BitcoinTransaction.Output576 /// Redeem script when the output is P2SH.577 let redeemScript: Bytes?578579 var isWitness: Bool {580 switch kind {581 case .p2wpkh, .p2wshMultisig: return true582 default: return false583 }584 }585 }586587 /// Runs the signer checks on an input and classifies it. nil when the PSBT carries no UTXO for it.588 func signingContext(inputIndex i: Int, options: SigningOptions = SigningOptions()) throws -> SigningContext? {589 try checkInput(i)590 let input = inputs[i]591 let outPoint = unsignedTransaction.inputs[i].previousOutput592 var utxo: BitcoinTransaction.Output?593 if let previous = input.nonWitnessUTXO {594 guard previous.txidBytes == outPoint.hash, Int(outPoint.index) < previous.outputs.count else { throw PSBTError.nonWitnessUTXOMismatch }595 utxo = previous.outputs[Int(outPoint.index)]596 if let w = input.witnessUTXO, w != utxo { throw PSBTError.utxoMismatch }597 } else {598 utxo = input.witnessUTXO599 }600 guard let utxo else { return nil }601 if let expected = options.expectedUTXOs[outPoint], expected != utxo { throw PSBTError.utxoMismatch }602 guard utxo.value <= maximumMoney else { throw PSBTError.utxoMismatch }603604 var script = utxo.scriptPubKey605 var redeem: Bytes?606 if case .p2sh(let hash) = BitcoinScript.classify(script) {607 guard let r = input.redeemScript else { throw PSBTError.missingRedeemScript }608 guard Hash160.hash(r) == hash else { throw PSBTError.redeemScriptMismatch }609 redeem = r610 script = r611 } else if input.redeemScript != nil {612 throw PSBTError.redeemScriptMismatch613 }614 let kind: SigningContext.Kind615 switch BitcoinScript.classify(script) {616 case .p2wpkh(let hash):617 guard input.witnessScript == nil else { throw PSBTError.witnessScriptMismatch }618 kind = .p2wpkh(hash: hash)619 case .p2wsh(let hash):620 guard let ws = input.witnessScript else { throw PSBTError.missingWitnessScript }621 guard SHA256.hash(ws) == hash else { throw PSBTError.witnessScriptMismatch }622 guard BitcoinScript.parseMultisig(ws) != nil else { throw PSBTError.unsupportedScript }623 kind = .p2wshMultisig(script: ws)624 case .p2pkh(let hash) where redeem == nil:625 guard input.witnessScript == nil else { throw PSBTError.witnessScriptMismatch }626 kind = .p2pkh(hash: hash)627 case .multisig:628 guard input.witnessScript == nil else { throw PSBTError.witnessScriptMismatch }629 kind = .legacyMultisig(script: script)630 default:631 throw PSBTError.unsupportedScript632 }633 let context = SigningContext(kind: kind, utxo: utxo, redeemScript: redeem)634 // SegWit does not exist under Dogecoin's and Bitcoin Cash's schemes: a witness program there is not a script635 // this wallet can sign for636 if context.isWitness && sighashScheme != .bip143 { throw PSBTError.unsupportedScript }637 if context.isWitness {638 if options.requireNonWitnessUTXO && input.nonWitnessUTXO == nil { throw PSBTError.nonWitnessUTXORequired }639 } else if input.nonWitnessUTXO == nil {640 throw PSBTError.witnessUTXOForNonWitnessInput641 }642 return context643 }644645 private func digest(inputIndex i: Int, context: SigningContext, type: BitcoinSighashType) throws -> Bytes {646 let tx = unsignedTransaction647 let code: Bytes648 switch context.kind {649 case .p2wpkh(let hash): code = try BitcoinSigner.p2wpkhScriptCode(publicKeyHash: hash)650 case .p2wshMultisig(let script): code = script651 case .p2pkh: code = context.utxo.scriptPubKey652 case .legacyMultisig(let script): code = script653 }654 return try BitcoinSighash.digest(scheme: sighashScheme, isWitness: context.isWitness, transaction: tx, inputIndex: i, scriptCode: code,655 value: context.utxo.value, type: type)656 }657658 /// The SIGHASH type an input is signed with: the one it declares, ALL otherwise, in the form of the scheme.659 /// `options.allowedSighashTypes` is expressed without the fork-id flag. Under Bitcoin Cash's scheme a declared type660 /// must carry the flag; under the others it must not.661 private func signingType(inputIndex i: Int, options: SigningOptions) throws -> BitcoinSighashType {662 let declared = inputs[i].sighashType663 if let declared, !declared.isStandard(for: sighashScheme) { throw PSBTError.sighashTypeNotAllowed }664 let base = (declared ?? .all).withoutForkID665 guard options.allowedSighashTypes.contains(base), base.isStandard else { throw PSBTError.sighashTypeNotAllowed }666 return base.adapted(to: sighashScheme)667 }668669 /// Signer role for one input and one key. Returns true when a partial signature was added, false when the key does not670 /// belong to the input, the input is already finalized or already signed by this key.671 /// Throws when a signer check fails: missing or inconsistent UTXO, scripts that do not hash to the output, a legacy672 /// input without its previous transaction, a SIGHASH type outside `options.allowedSighashTypes`, an unsupported script.673 @discardableResult674 public mutating func sign(inputIndex i: Int, privateKey: Bytes, options: SigningOptions = SigningOptions()) throws -> Bool {675 try checkInput(i)676 guard Secp256k1.isValidPrivateKey(privateKey) else { throw PSBTError.invalidPrivateKey }677 if inputs[i].isFinalized { return false }678 guard let context = try signingContext(inputIndex: i, options: options) else { throw PSBTError.missingUTXO }679 let type = try signingType(inputIndex: i, options: options)680 guard let compressed = try? Secp256k1.publicKey(privateKey: privateKey, compressed: true),681 let uncompressed = try? Secp256k1.publicKey(privateKey: privateKey, compressed: false) else { throw PSBTError.invalidPrivateKey }682 let publicKey: Bytes683 switch context.kind {684 case .p2wpkh(let hash):685 guard Hash160.hash(compressed) == hash else { return false }686 publicKey = compressed687 case .p2pkh(let hash):688 if Hash160.hash(compressed) == hash { publicKey = compressed }689 else if Hash160.hash(uncompressed) == hash { publicKey = uncompressed }690 else { return false }691 case .p2wshMultisig(let script):692 guard let m = BitcoinScript.parseMultisig(script), m.publicKeys.contains(compressed) else { return false }693 publicKey = compressed694 case .legacyMultisig(let script):695 guard let m = BitcoinScript.parseMultisig(script) else { return false }696 if m.publicKeys.contains(compressed) { publicKey = compressed }697 else if m.publicKeys.contains(uncompressed) { publicKey = uncompressed }698 else { return false }699 }700 if inputs[i].partialSignatures.contains(where: { $0.publicKey == publicKey }) { return false }701 let hash = try digest(inputIndex: i, context: context, type: type)702 guard let signature = try? BitcoinSigner.signature(digest: hash, privateKey: privateKey, sighashType: type) else {703 throw PSBTError.invalidPrivateKey704 }705 inputs[i].partialSignatures.append(BitcoinPartialSignature(publicKey: publicKey, signature: signature))706 inputs[i].partialSignatures.sort { lexicographicallyPrecedes($0.publicKey, $1.publicKey) }707 return true708 }709710 /// Signer role over the whole PSBT: every input is checked first (a failed check throws and nothing is signed), then711 /// each key signs the inputs it belongs to. Inputs without UTXO are left untouched. Returns the number of signatures added.712 @discardableResult713 public mutating func sign(privateKeys: [Bytes], options: SigningOptions = SigningOptions()) throws -> Int {714 var signable = [Int]()715 for i in inputs.indices where !inputs[i].isFinalized {716 if try signingContext(inputIndex: i, options: options) != nil { signable.append(i) }717 }718 var copy = self719 var added = 0720 for i in signable {721 for key in privateKeys where try copy.sign(inputIndex: i, privateKey: key, options: options) { added += 1 }722 }723 self = copy724 return added725 }726727 // MARK: Combiner728729 /// Combiner role: merges PSBTs of the same unsigned transaction. On a conflicting key the first PSBT wins.730 /// Multi-valued fields and unknown records of the result are in lexicographic key order.731 public static func combine(_ psbts: [PSBT]) throws -> PSBT {732 guard var result = psbts.first else { throw PSBTError.nothingToCombine }733 func merge(_ a: inout [Record], _ b: [Record]) {734 for r in b where !a.contains(where: { $0.key == r.key }) { a.append(r) }735 a.sort { lexicographicallyPrecedes($0.key, $1.key) }736 }737 func merge(_ a: inout [KeyDerivation], _ b: [KeyDerivation]) {738 for d in b where !a.contains(where: { $0.publicKey == d.publicKey }) { a.append(d) }739 a.sort { lexicographicallyPrecedes($0.publicKey, $1.publicKey) }740 }741 for other in psbts.dropFirst() {742 guard other.unsignedTransaction == result.unsignedTransaction else { throw PSBTError.differentTransactions }743 if result.version == nil { result.version = other.version }744 merge(&result.unknown, other.unknown)745 for i in result.inputs.indices {746 let o = other.inputs[i]747 if result.inputs[i].nonWitnessUTXO == nil { result.inputs[i].nonWitnessUTXO = o.nonWitnessUTXO }748 if result.inputs[i].witnessUTXO == nil { result.inputs[i].witnessUTXO = o.witnessUTXO }749 for s in o.partialSignatures where !result.inputs[i].partialSignatures.contains(where: { $0.publicKey == s.publicKey }) {750 result.inputs[i].partialSignatures.append(s)751 }752 result.inputs[i].partialSignatures.sort { lexicographicallyPrecedes($0.publicKey, $1.publicKey) }753 if result.inputs[i].sighashType == nil { result.inputs[i].sighashType = o.sighashType }754 if result.inputs[i].redeemScript == nil { result.inputs[i].redeemScript = o.redeemScript }755 if result.inputs[i].witnessScript == nil { result.inputs[i].witnessScript = o.witnessScript }756 merge(&result.inputs[i].derivations, o.derivations)757 if result.inputs[i].finalScriptSig == nil { result.inputs[i].finalScriptSig = o.finalScriptSig }758 if result.inputs[i].finalScriptWitness == nil { result.inputs[i].finalScriptWitness = o.finalScriptWitness }759 merge(&result.inputs[i].unknown, o.unknown)760 }761 for i in result.outputs.indices {762 let o = other.outputs[i]763 if result.outputs[i].redeemScript == nil { result.outputs[i].redeemScript = o.redeemScript }764 if result.outputs[i].witnessScript == nil { result.outputs[i].witnessScript = o.witnessScript }765 merge(&result.outputs[i].derivations, o.derivations)766 merge(&result.outputs[i].unknown, o.unknown)767 }768 }769 if psbts.count == 1 {770 // A single PSBT is returned in the same canonical order.771 result = result.normalized772 }773 return result774 }775776 // MARK: Finalizer777778 /// Input Finalizer role for one input: checks every partial signature (and its SIGHASH type against the input's),779 /// builds the final scriptSig / witness and clears the signing data. An already finalized input is left as is.780 /// Throws `notEnoughSignatures` when the input cannot be completed yet.781 public mutating func finalizeInput(_ i: Int) throws {782 try checkInput(i)783 if inputs[i].isFinalized { return }784 guard let context = try signingContext(inputIndex: i) else { throw PSBTError.missingUTXO }785 let input = inputs[i]786 for s in input.partialSignatures {787 guard let type = s.sighashType, type == (input.sighashType ?? type) else { throw PSBTError.sighashTypeNotAllowed }788 guard BitcoinVerifier.checkSignature(s.signature, publicKey: s.publicKey, requireLowS: true, scheme: sighashScheme,789 digest: { try digest(inputIndex: i, context: context, type: $0) }) else {790 throw PSBTError.invalidSignature791 }792 }793 var scriptSig = Bytes()794 var witness = [Bytes]()795 switch context.kind {796 case .p2wpkh(let hash):797 guard let s = input.partialSignatures.first(where: { Hash160.hash($0.publicKey) == hash }) else { throw PSBTError.notEnoughSignatures }798 witness = [s.signature, s.publicKey]799 case .p2pkh(let hash):800 guard let s = input.partialSignatures.first(where: { Hash160.hash($0.publicKey) == hash }) else { throw PSBTError.notEnoughSignatures }801 scriptSig = BitcoinScript.pushRaw(s.signature) + BitcoinScript.pushRaw(s.publicKey)802 case .p2wshMultisig(let script):803 guard let ordered = try? BitcoinSigner.orderedSignatures(script: script, signatures: input.partialSignatures) else {804 throw PSBTError.notEnoughSignatures805 }806 witness = [[]] + ordered + [script]807 case .legacyMultisig(let script):808 guard let ordered = try? BitcoinSigner.orderedSignatures(script: script, signatures: input.partialSignatures) else {809 throw PSBTError.notEnoughSignatures810 }811 scriptSig = [BitcoinOpcode.op0] + ordered.flatMap { BitcoinScript.pushRaw($0) }812 }813 if let redeem = context.redeemScript { scriptSig += BitcoinScript.pushRaw(redeem) }814 inputs[i].finalScriptSig = scriptSig.isEmpty ? nil : scriptSig815 inputs[i].finalScriptWitness = witness.isEmpty ? nil : witness816 inputs[i].partialSignatures = []817 inputs[i].sighashType = nil818 inputs[i].redeemScript = nil819 inputs[i].witnessScript = nil820 inputs[i].derivations = []821 }822823 /// Finalizes every input, or throws and leaves the PSBT unchanged.824 public mutating func finalize() throws {825 var copy = self826 for i in copy.inputs.indices { try copy.finalizeInput(i) }827 self = copy828 }829830 // MARK: Extractor831832 /// Transaction Extractor role: the network transaction of a fully finalized PSBT. With `verify` (the default), the833 /// signatures of every input whose UTXO is known and whose script QYVORA understands are checked first.834 public func extractTransaction(verify: Bool = true) throws -> BitcoinTransaction {835 guard isFinalized else { throw PSBTError.notFinalized }836 var tx = unsignedTransaction837 for i in inputs.indices {838 tx.inputs[i].scriptSig = inputs[i].finalScriptSig ?? []839 tx.inputs[i].witness = inputs[i].finalScriptWitness ?? []840 }841 if verify {842 for i in inputs.indices {843 guard let utxo = spentOutput(inputIndex: i) else { continue }844 do {845 try BitcoinVerifier.verifyInput(transaction: tx, inputIndex: i, spentOutput: utxo, scheme: sighashScheme)846 } catch BitcoinVerifier.Error.unsupportedScript {847 continue848 } catch {849 throw PSBTError.invalidSignature850 }851 }852 }853 return tx854 }855}856