Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Tests/QyvoraBitcoinTests/PSBTTests.swift8// Module : Tests9// 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 Testing42import Foundation43import QyvoraMath44import QyvoraSymmetric45import QyvoraSecp256k146import QyvoraCore47@testable import QyvoraBitcoin4849/// Official test vectors of BIP-174.50@Suite struct BIP174Tests {51 @Test func vectorInventory() {52 #expect(BIP174Vectors.invalid.count == 20)53 #expect(BIP174Vectors.valid.count == 10)54 #expect(BIP174Vectors.signerFailures.count == 4)55 #expect(BIP174Vectors.workflowHex.count == 14 && BIP174Vectors.workflowBase64.count == 13)56 #expect(BIP174Vectors.previousTransactions.count == 2)57 }5859 @Test(arguments: BIP174Vectors.invalid.indices)60 func invalidPSBTIsRejected(_ i: Int) {61 let v = BIP174Vectors.invalid[i]62 #expect((try? PSBT(hex: v.hex)) == nil, "accepted (hex): \(v.name)")63 #expect((try? PSBT(base64: v.base64)) == nil, "accepted (base64): \(v.name)")64 }6566 @Test(arguments: BIP174Vectors.valid.indices)67 func validPSBTParsesAndRoundTrips(_ i: Int) throws {68 let v = BIP174Vectors.valid[i]69 let fromHex = try PSBT(hex: v.hex)70 let fromBase64 = try PSBT(base64: v.base64)71 #expect(fromHex == fromBase64, "\(v.name)")72 #expect(fromHex.hex == v.hex, "\(v.name)")73 #expect(fromHex.base64 == v.base64, "\(v.name)")74 #expect(fromHex.inputs.count == fromHex.unsignedTransaction.inputs.count)75 #expect(fromHex.outputs.count == fromHex.unsignedTransaction.outputs.count)76 }7778 @Test func validVectorContents() throws {79 // one P2PKH input and one P2SH-P2WPKH input, the first one finalized80 let finalized = try PSBT(hex: BIP174Vectors.valid[1].hex)81 #expect(finalized.inputs[0].finalScriptSig != nil && finalized.inputs[0].isFinalized)82 #expect(finalized.inputs[1].witnessUTXO != nil && finalized.inputs[1].redeemScript != nil && !finalized.inputs[1].isFinalized)83 #expect(!finalized.isFinalized)84 // sighash type specified85 #expect(try PSBT(hex: BIP174Vectors.valid[2].hex).inputs[0].sighashType == .all)86 // P2SH-P2WSH 2-of-2 with one signature87 let multisig = try PSBT(hex: BIP174Vectors.valid[4].hex)88 #expect(multisig.inputs[0].partialSignatures.count == 1 && multisig.inputs[0].derivations.count == 2)89 #expect(BitcoinScript.parseMultisig(try #require(multisig.inputs[0].witnessScript))?.required == 2)90 // global xpubs are kept as unknown records and written back (checked by the byte-exact round trip)91 let xpubs = try PSBT(hex: BIP174Vectors.valid[5].hex)92 #expect(xpubs.unknown.count == 2 && xpubs.unknown.allSatisfy { $0.type == 0x01 })93 // unknown input type 0xf0 (key f0 01…09, 15-byte value)94 let unknown = try PSBT(hex: BIP174Vectors.valid[6].hex)95 #expect(unknown.inputs[0].unknown.count == 1 && unknown.inputs[0].unknown[0].type == 0xf0)96 // empty transaction97 let empty = try PSBT(hex: BIP174Vectors.valid[8].hex)98 #expect(empty.unsignedTransaction.inputs.isEmpty && empty.unsignedTransaction.outputs.isEmpty && !empty.isFinalized)99 }100101 @Test(arguments: BIP174Vectors.signerFailures.indices)102 func signerChecksFail(_ i: Int) throws {103 let v = BIP174Vectors.signerFailures[i]104 var psbt = try PSBT(base64: v.base64)105 let before = psbt106 #expect(throws: PSBTError.self, "\(v.name)") { try psbt.sign(privateKeys: [testKey(1)]) }107 #expect(psbt == before)108 }109110 @Test func signerFailureReasons() throws {111 func reason(_ i: Int) -> PSBTError? {112 guard var psbt = try? PSBT(hex: BIP174Vectors.signerFailures[i].hex) else { return nil }113 do {114 try psbt.sign(privateKeys: [])115 return nil116 } catch {117 return error as? PSBTError118 }119 }120 #expect(reason(0) == .witnessUTXOForNonWitnessInput)121 #expect(reason(1) == .redeemScriptMismatch)122 #expect(reason(2) == .redeemScriptMismatch)123 #expect(reason(3) == .witnessScriptMismatch)124 }125126 static let masterKey = "tprv8ZgxMBicQKsPd9TeAdPADNnSyH9SSUUbTVeFszDE23Ki6TBB5nCefAdHkK8Fm3qMQR6sHwA56zqRmKmxnHk37JkiFzvncDqoKmPWubu7hDF"127 static let wifs = ["cP53pDbR5WtAD8dYAW9hhTjuvvTVaEiQBdrz9XPrgLBeRFiyCbQr", "cT7J9YpCwY3AVRFSjN6ukeEeWY6mhpbJPxRaDaP5QTdygQRxP9Au",128 "cR6SXDoyfQrcp4piaiHE97Rsgta9mNhGTen9XeonVgwsh4iSgw6d", "cNBc3SWUip9PPm1GjRoLEJT6T41iNzCYtD7qro84FMnM5zEqeJsE"]129130 /// Creator → Updater → Signer (×2) → Combiner → Input Finalizer → Transaction Extractor, byte for byte.131 @Test func fullWorkflow() throws {132 let w = BIP174Vectors.workflowHex133 // Creator134 let tx = BitcoinTransaction(135 inputs: [.init(previousOutput: BitcoinOutPoint(txid: "75ddabb27b8845f5247975c8a5ba7c6f336c4570708ebe230caf6db5217ae858", vout: 0)!),136 .init(previousOutput: BitcoinOutPoint(txid: "1dea7cd05979072a3578cab271c02244ea8a090bbb46aa680a65ecd027048d83", vout: 1)!)],137 outputs: [.init(value: 149_990_000, scriptPubKey: unhex("0014d85c2b71d0060b09c9886aeb815e50991dda124d")),138 .init(value: 100_000_000, scriptPubKey: unhex("001400aea9a2e5f0f876a588df5546e8742d1d87008f"))])139 var psbt = try PSBT(unsignedTransaction: tx)140 #expect(psbt.hex == w[0])141 #expect(psbt.base64 == BIP174Vectors.workflowBase64[0])142143 // Updater: derive the six keys m/0'/0'/i' from the master key of the BIP144 let master = try ExtendedKey.parse(Self.masterKey).key145 let account = try master.derive(DerivationPath("m/0'/0'")!)146 let keys = try (0..<6).map { try account.derive(.hardened(UInt32($0))) }147 #expect(keys.map(\.publicKey.hex) == [148 "029583bf39ae0a609747ad199addd634fa6108559d6c5cd39b4c2183f1ab96e07f", "02dab61ff49a14db6a7d02b0cd1fbb78fc4b18312b5b4e54dae4dba2fbfef536d7",149 "03089dc10c7ac6db54f91329af617333db388cead0c231f723379d1b99030b02dc", "023add904f3d6dcf59ddb906b0dee23529b7ffb9ed50e5e86151926860221f0e73",150 "03a9a4c37f5996d3aa25dbac6b570af0650394492942460b354753ed9eeca58771", "027f6399757d2eff55a136ad02c684b1838b6556e5f1b6b34282a94b6b50051096"])151 for (i, wif) in Self.wifs.enumerated() {152 let decoded = try BitcoinWIF.decode(wif, network: .testnet)153 #expect(decoded.compressed && decoded.privateKey == keys[i].privateKey)154 }155 func derivation(_ i: Int) -> PSBT.KeyDerivation {156 .init(publicKey: keys[i].publicKey, fingerprint: master.fingerprint, path: DerivationPath("m/0'/0'/\(i)'")!)157 }158 let previous = try BIP174Vectors.previousTransactions.map { try BitcoinTransaction(hex: $0) }159 for (i, input) in tx.inputs.enumerated() {160 let funding = try #require(previous.first { $0.txidBytes == input.previousOutput.hash })161 if i == 0 {162 try psbt.setNonWitnessUTXO(funding, inputIndex: 0)163 } else {164 // the BIP's updater gives the SegWit input its spent output only165 try psbt.setWitnessUTXO(funding.outputs[Int(input.previousOutput.index)], inputIndex: 1)166 }167 }168 let redeem0 = unhex("5221029583bf39ae0a609747ad199addd634fa6108559d6c5cd39b4c2183f1ab96e07f2102dab61ff49a14db6a7d02b0cd1fbb78fc4b18312b5b4e54dae4dba2fbfef536d752ae")169 let redeem1 = unhex("00208c2353173743b595dfb4a07b72ba8e42e3797da74e87fe7d9d7497e3b2028903")170 let witness1 = unhex("522103089dc10c7ac6db54f91329af617333db388cead0c231f723379d1b99030b02dc21023add904f3d6dcf59ddb906b0dee23529b7ffb9ed50e5e86151926860221f0e7352ae")171 try psbt.setRedeemScript(redeem0, inputIndex: 0)172 try psbt.setRedeemScript(redeem1, inputIndex: 1)173 try psbt.setWitnessScript(witness1, inputIndex: 1)174 #expect(throws: PSBTError.redeemScriptMismatch) { try psbt.setRedeemScript(redeem1, inputIndex: 0) }175 #expect(throws: PSBTError.witnessScriptMismatch) { try psbt.setWitnessScript(redeem0, inputIndex: 1) }176 for i in [0, 1] { try psbt.addInputDerivation(derivation(i), inputIndex: 0) }177 for i in [2, 3] { try psbt.addInputDerivation(derivation(i), inputIndex: 1) }178 for (o, output) in tx.outputs.enumerated() {179 let i = try #require((4..<6).first { (try? BitcoinScript.p2wpkh(publicKey: keys[$0].publicKey)) == output.scriptPubKey })180 try psbt.addOutputDerivation(derivation(i), outputIndex: o)181 }182 let expectedUpdated = try PSBT(hex: w[1])183 #expect(psbt.normalized == expectedUpdated.normalized)184 #expect(psbt.hex == w[1])185186 // Updater: SIGHASH_ALL on both inputs187 try psbt.setSighashType(.all, inputIndex: 0)188 try psbt.setSighashType(.all, inputIndex: 1)189 #expect(psbt.hex == w[2])190 #expect(psbt.fee == 10_000)191192 // Signers: keys 0 and 2, then keys 1 and 3193 var signerA = psbt, signerB = psbt194 #expect(try signerA.sign(privateKeys: [keys[0].privateKey!, keys[2].privateKey!]) == 2)195 #expect(try signerB.sign(privateKeys: [keys[1].privateKey!, keys[3].privateKey!]) == 2)196 #expect(signerA.normalized == (try PSBT(hex: w[3])).normalized)197 #expect(signerB.normalized == (try PSBT(hex: w[4])).normalized)198 #expect(signerA.hex == w[3])199 #expect(signerB.hex == w[4])200 // signing again adds nothing; a foreign key adds nothing201 #expect(try signerA.sign(privateKeys: [keys[0].privateKey!, keys[5].privateKey!]) == 0)202 #expect(signerA.hex == w[3])203204 // Combiner, in both orders205 let expectedCombined = try PSBT(hex: w[5])206 let combined = try PSBT.combine([signerA, signerB])207 #expect(combined.normalized == expectedCombined.normalized)208 #expect(try PSBT.combine([signerB, signerA]) == combined)209 #expect(try PSBT.combine([try PSBT(hex: w[3]), try PSBT(hex: w[4])]).normalized == expectedCombined.normalized)210 #expect(throws: PSBTError.notEnoughSignatures) {211 var early = signerA212 try early.finalize()213 }214 #expect(throws: PSBTError.notFinalized) { try combined.extractTransaction() }215216 // Input Finalizer217 var finalized = combined218 try finalized.finalize()219 #expect(finalized.hex == w[6])220 #expect(finalized.isFinalized)221 var fromVector = expectedCombined222 try fromVector.finalize()223 #expect(fromVector.hex == w[6])224225 // Transaction Extractor (signatures verified on the way)226 let extracted = try finalized.extractTransaction()227 #expect(extracted.hex == w[7])228 #expect(try PSBT(hex: w[6]).extractTransaction().hex == w[7])229 try BitcoinVerifier.verify(transaction: extracted, spentOutputs: [previous.first { $0.txidBytes == tx.inputs[0].previousOutput.hash }!.outputs[0],230 previous.first { $0.txidBytes == tx.inputs[1].previousOutput.hash }!.outputs[1]])231 // a corrupted signature is caught by the extractor232 var corrupted = finalized233 corrupted.inputs[1].finalScriptWitness![1][10] ^= 0x01234 #expect(throws: PSBTError.invalidSignature) { try corrupted.extractTransaction() }235 #expect((try? corrupted.extractTransaction(verify: false)) != nil)236 }237238 @Test func combinerVectors() throws {239 let w = BIP174Vectors.workflowHex240 // unknown key-value pairs, lexicographic order241 let a = try PSBT(hex: w[8]), b = try PSBT(hex: w[9])242 #expect(try PSBT.combine([a, b]).hex == w[10])243 #expect(try PSBT.combine([b, a]).hex == w[10])244 // two PSBTs of the workflow245 let c = try PSBT(hex: w[11]), d = try PSBT(hex: w[12])246 let expected = try PSBT(hex: w[13])247 #expect(try PSBT.combine([c, d]).normalized == expected.normalized)248 #expect(try PSBT.combine([d, c]).normalized == expected.normalized)249 #expect(throws: PSBTError.differentTransactions) { try PSBT.combine([a, c]) }250 #expect(throws: PSBTError.nothingToCombine) { try PSBT.combine([]) }251 #expect(try PSBT.combine([c]).normalized == c.normalized)252 }253}254255@Suite struct PSBTTests {256 struct Fixture {257 let account: BIP84Account258 let utxos: [BitcoinUTXO]259 let plan: BitcoinTransactionPlan260 }261262 static func fixture(network: BitcoinNetwork = .testnet) throws -> Fixture {263 let account = try BIP84Account(master: try abandonMaster(), network: network)264 var utxos = [BitcoinUTXO]()265 for i in 0..<3 as Range<UInt32> {266 utxos.append(BitcoinUTXO(outPoint: BitcoinOutPoint(hash: Bytes(repeating: UInt8(i + 1), count: 32), index: i)!, value: 40_000 + UInt64(i) * 7_000,267 scriptPubKey: try account.scriptPubKey(chain: i == 2 ? .change : .receive, index: i), confirmations: 6,268 address: try account.address(chain: i == 2 ? .change : .receive, index: i).string,269 derivation: .init(chain: i == 2 ? 1 : 0, index: i)))270 }271 var request = BitcoinSpendRequest(recipients: [.init(value: 90_000, scriptPubKey: try BitcoinScript.p2wsh(scriptHash: Bytes(repeating: 5, count: 32)))],272 utxos: utxos, feeRate: FeeRate(satPerVByte: 4), changeScript: try account.scriptPubKey(chain: .change, index: 9))273 request.seed = 42274 return Fixture(account: account, utxos: utxos, plan: try BitcoinTransactionBuilder.build(request))275 }276277 @Test func accountPSBTFlow() throws {278 let f = try Self.fixture()279 var psbt = try f.account.psbt(for: f.plan)280 #expect(psbt.inputs.allSatisfy { $0.witnessUTXO != nil && $0.derivations.count == 1 })281 #expect(psbt.inputs[0].derivations[0].fingerprint == [0x73, 0xc5, 0xda, 0x0a])282 #expect(psbt.inputs[0].derivations[0].path.description.hasPrefix("m/84'/1'/0'/"))283 let change = try #require(f.plan.changeIndex)284 #expect(psbt.outputs[change].derivations.first?.path.description == "m/84'/1'/0'/1/9")285 #expect(psbt.fee == f.plan.fee)286 // binary and base64 round trips287 #expect(try PSBT(parsing: psbt.serialized()) == psbt)288 #expect(try PSBT(base64: psbt.base64) == psbt)289290 // a watch-only account prepares, the full account signs291 let watch = try BIP84Account(extendedKey: f.account.extendedPublicKey(), network: .testnet, masterFingerprint: f.account.masterFingerprint)292 #expect(try watch.psbt(for: f.plan) == psbt)293 #expect(throws: BitcoinAccountError.watchOnly) { try watch.sign(psbt: &psbt) }294 let expected = Dictionary(uniqueKeysWithValues: f.plan.inputs.map { ($0.outPoint, $0.output) })295 #expect(try f.account.sign(psbt: &psbt, options: .init(expectedUTXOs: expected)) == f.plan.inputs.count)296 #expect(try f.account.sign(psbt: &psbt) == 0)297 try psbt.finalize()298 #expect(psbt.inputs.allSatisfy { $0.finalScriptWitness?.count == 2 && $0.finalScriptSig == nil && $0.partialSignatures.isEmpty && $0.derivations.isEmpty })299 let tx = try psbt.extractTransaction()300 try BitcoinVerifier.verify(transaction: tx, spentOutputs: f.plan.inputs.map(\.output))301 // direct signing gives the very same transaction (deterministic signatures)302 #expect(try f.account.sign(plan: f.plan) == tx)303 #expect(tx.weight <= f.plan.estimatedWeight && f.plan.estimatedWeight - tx.weight <= 2 * tx.inputs.count)304 #expect(tx.txid == f.plan.transaction.txid)305 // without derivation records the account still finds its scripts306 var bare = try f.plan.psbt()307 #expect(try f.account.sign(psbt: &bare) == f.plan.inputs.count)308 // an account of another wallet signs nothing309 let other = try BIP84Account(master: try ExtendedKey.master(seed: Bytes(repeating: 9, count: 32)), network: .testnet)310 var foreign = try f.plan.psbt()311 #expect(try other.sign(psbt: &foreign, searchLimit: 12) == 0)312 #expect(throws: BitcoinAccountError.foreignInput(index: 0)) { try other.sign(plan: f.plan, searchLimit: 12) }313 }314315 @Test func signerRefusals() throws {316 let f = try Self.fixture()317 let base = try f.account.psbt(for: f.plan)318 let key = try f.account.privateKey(chain: BIP84Account.Chain(rawValue: f.plan.inputs[0].derivation!.chain)!, index: f.plan.inputs[0].derivation!.index)319320 // SIGHASH types other than ALL are refused unless explicitly allowed321 for type in [BitcoinSighashType.none, .single, .allAnyoneCanPay, .noneAnyoneCanPay, .singleAnyoneCanPay, .init(rawValue: 0), .init(rawValue: 4)] {322 var p = base323 try p.setSighashType(type, inputIndex: 0)324 #expect(throws: PSBTError.sighashTypeNotAllowed) { try p.sign(inputIndex: 0, privateKey: key) }325 #expect(throws: PSBTError.sighashTypeNotAllowed) { try f.account.sign(psbt: &p) }326 #expect(p.inputs[0].partialSignatures.isEmpty)327 }328 var allowed = base329 try allowed.setSighashType(.singleAnyoneCanPay, inputIndex: 0)330 #expect(try allowed.sign(inputIndex: 0, privateKey: key, options: .init(allowedSighashTypes: [.all, .singleAnyoneCanPay])))331 #expect(allowed.inputs[0].partialSignatures[0].sighashType == .singleAnyoneCanPay)332 try allowed.finalizeInput(0)333 // the finalizer refuses a signature whose type differs from the input's334 var mismatch = base335 #expect(try mismatch.sign(inputIndex: 0, privateKey: key))336 mismatch.inputs[0].sighashType = BitcoinSighashType.none337 #expect(throws: PSBTError.sighashTypeNotAllowed) { try mismatch.finalizeInput(0) }338339 // the amount shown by the PSBT differs from what the wallet knows340 var lied = base341 lied.inputs[0].witnessUTXO?.value += 1342 let known = [f.plan.inputs[0].outPoint: f.plan.inputs[0].output]343 #expect(throws: PSBTError.utxoMismatch) { try lied.sign(inputIndex: 0, privateKey: key, options: .init(expectedUTXOs: known)) }344 // and the script345 var otherScript = base346 otherScript.inputs[0].witnessUTXO?.scriptPubKey = f.plan.inputs[1].scriptPubKey347 #expect(throws: PSBTError.utxoMismatch) { try otherScript.sign(inputIndex: 0, privateKey: key, options: .init(expectedUTXOs: known)) }348 // without that knowledge a lie on the amount yields a signature that does not verify349 #expect(try lied.sign(inputIndex: 0, privateKey: key))350 var honest = base351 honest.inputs[0].partialSignatures = lied.inputs[0].partialSignatures352 #expect(throws: PSBTError.invalidSignature) { try honest.finalizeInput(0) }353354 // no UTXO at all355 var missing = base356 missing.inputs[0].witnessUTXO = nil357 #expect(throws: PSBTError.missingUTXO) { try missing.sign(inputIndex: 0, privateKey: key) }358 #expect(throws: PSBTError.missingUTXO) { try missing.finalizeInput(0) }359 #expect(missing.fee == nil)360 // strict mode wants the previous transaction361 var strict = base362 #expect(throws: PSBTError.nonWitnessUTXORequired) { try strict.sign(inputIndex: 0, privateKey: key, options: .init(requireNonWitnessUTXO: true)) }363 // foreign key, bad key, bad index364 var p = base365 #expect(try !p.sign(inputIndex: 0, privateKey: testKey(5)))366 #expect(throws: PSBTError.invalidPrivateKey) { try p.sign(inputIndex: 0, privateKey: Bytes(repeating: 0, count: 32)) }367 #expect(throws: PSBTError.inputIndexOutOfRange) { try p.sign(inputIndex: 99, privateKey: key) }368 #expect(throws: PSBTError.inputIndexOutOfRange) { try p.finalizeInput(-1) }369 #expect(throws: PSBTError.outputIndexOutOfRange) { try p.setOutputScripts(witnessScript: [0x51], outputIndex: 9) }370 // unsupported script: a Taproot input is left alone by the bulk signer and refused individually371 var taproot = base372 taproot.inputs[0].witnessUTXO?.scriptPubKey = try BitcoinScript.p2tr(outputKey: Bytes(repeating: 3, count: 32))373 #expect(throws: PSBTError.unsupportedScript) { try taproot.sign(inputIndex: 0, privateKey: key) }374 }375376 @Test func nonWitnessUTXOChecks() throws {377 let key = testKey(11)378 let script = try BitcoinScript.p2wpkh(publicKey: testPublicKey(11))379 let funding = BitcoinTransaction(inputs: [.init(previousOutput: BitcoinOutPoint(hash: Bytes(repeating: 8, count: 32), index: 0)!)],380 outputs: [.init(value: 1_000, scriptPubKey: [0x51]), .init(value: 70_000, scriptPubKey: script)])381 let spend = BitcoinTransaction(inputs: [.init(previousOutput: BitcoinOutPoint(hash: funding.txidBytes, index: 1)!)],382 outputs: [.init(value: 69_000, scriptPubKey: script)])383 var psbt = try PSBT(unsignedTransaction: spend)384 // a previous transaction that does not hash to the outpoint385 var forged = funding386 forged.outputs[1].value = 700_000387 #expect(throws: PSBTError.nonWitnessUTXOMismatch) { try psbt.setNonWitnessUTXO(forged, inputIndex: 0) }388 var injected = psbt389 injected.inputs[0].nonWitnessUTXO = forged390 #expect(throws: PSBTError.nonWitnessUTXOMismatch) { try injected.sign(inputIndex: 0, privateKey: key) }391 #expect(throws: PSBTError.nonWitnessUTXOMismatch) { try PSBT(parsing: injected.serialized()) }392 // output index beyond the previous transaction393 let beyond = BitcoinTransaction(inputs: [.init(previousOutput: BitcoinOutPoint(hash: funding.txidBytes, index: 2)!)], outputs: spend.outputs)394 var short = try PSBT(unsignedTransaction: beyond)395 #expect(throws: PSBTError.nonWitnessUTXOMismatch) { try short.setNonWitnessUTXO(funding, inputIndex: 0) }396 // witness UTXO disagreeing with the previous transaction397 try psbt.setNonWitnessUTXO(funding, inputIndex: 0)398 #expect(throws: PSBTError.utxoMismatch) { try psbt.setWitnessUTXO(.init(value: 70_001, scriptPubKey: script), inputIndex: 0) }399 var conflicting = psbt400 conflicting.inputs[0].witnessUTXO = .init(value: 70_001, scriptPubKey: script)401 #expect(throws: PSBTError.utxoMismatch) { try conflicting.sign(inputIndex: 0, privateKey: key) }402 // the consistent case signs, also in strict mode, and extracts403 try psbt.setWitnessUTXO(funding.outputs[1], inputIndex: 0)404 #expect(try psbt.sign(inputIndex: 0, privateKey: key, options: .init(requireNonWitnessUTXO: true)))405 #expect(psbt.fee == 1_000)406 try psbt.finalize()407 let tx = try psbt.extractTransaction()408 try BitcoinVerifier.verify(transaction: tx, spentOutputs: [funding.outputs[1]])409 // finalizing twice changes nothing; signing a finalized input adds nothing410 let again = psbt411 try psbt.finalize()412 #expect(psbt == again)413 #expect(try !psbt.sign(inputIndex: 0, privateKey: key))414 }415416 @Test func creatorRejectsSignedTransaction() throws {417 let op = BitcoinOutPoint(hash: Bytes(repeating: 1, count: 32), index: 0)!418 #expect(throws: PSBTError.unsignedTransactionNotEmpty) {419 try PSBT(unsignedTransaction: BitcoinTransaction(inputs: [.init(previousOutput: op, scriptSig: [0x51])], outputs: []))420 }421 #expect(throws: PSBTError.unsignedTransactionNotEmpty) {422 try PSBT(unsignedTransaction: BitcoinTransaction(inputs: [.init(previousOutput: op, witness: [[1]])], outputs: []))423 }424 }425426 @Test func parserNegatives() throws {427 let f = try Self.fixture()428 var psbt = try f.account.psbt(for: f.plan)429 psbt.unknown = [.init(key: [0xfc, 0x01, 0x02], value: [9, 9])]430 psbt.inputs[1].unknown = [.init(key: [0x30], value: [])]431 psbt.outputs[0].unknown = [.init(key: [0x40, 0x41], value: [1])]432 let bytes = psbt.serialized()433 let reparsed = try PSBT(parsing: bytes)434 #expect(reparsed == psbt && reparsed.serialized() == bytes)435 #expect(reparsed.unknown[0].type == 0xfc && reparsed.inputs[1].unknown[0].type == 0x30)436437 // every strict prefix fails438 for n in 0..<bytes.count {439 #expect((try? PSBT(parsing: Array(bytes.prefix(n)))) == nil, "prefix \(n) parsed")440 }441 #expect(throws: PSBTError.serialization(.trailingBytes)) { try PSBT(parsing: bytes + [0]) }442 #expect(throws: PSBTError.invalidMagic) { try PSBT(parsing: [0x70, 0x73, 0x62, 0x74, 0xfe] + Array(bytes.dropFirst(5))) }443 #expect(throws: PSBTError.invalidMagic) { try PSBT(parsing: []) }444 #expect(throws: PSBTError.invalidBase64) { try PSBT(base64: "not base64 !!") }445 #expect(throws: PSBTError.invalidBase64) { try PSBT(base64: psbt.base64 + "*") }446 #expect((try? PSBT(base64: "")) == nil)447 #expect((try? PSBT(hex: "zz")) == nil)448 // a network transaction is not a PSBT449 #expect(throws: PSBTError.invalidMagic) { try PSBT(parsing: f.plan.transaction.serialized()) }450451 func raw(_ global: [(Bytes, Bytes)], _ maps: [[(Bytes, Bytes)]] = []) -> Bytes {452 var out = PSBT.magic453 for m in [global] + maps {454 for (k, v) in m { out += Wire.varBytes(k) + Wire.varBytes(v) }455 out.append(0)456 }457 return out458 }459 let op = BitcoinOutPoint(hash: Bytes(repeating: 1, count: 32), index: 0)!460 let tx = BitcoinTransaction(inputs: [.init(previousOutput: op)], outputs: [.init(value: 1, scriptPubKey: [0x51])])461 let txBytes = tx.serialized()462 #expect(try PSBT(parsing: raw([([0], txBytes)], [[], []])).unsignedTransaction == tx)463 #expect(throws: PSBTError.missingUnsignedTransaction) { try PSBT(parsing: raw([], [[], []])) }464 #expect(throws: PSBTError.duplicateKey) { try PSBT(parsing: raw([([0], txBytes), ([0], txBytes)], [[], []])) }465 #expect(throws: PSBTError.duplicateKey) { try PSBT(parsing: raw([([0], txBytes)], [[([0x0f, 1], [1]), ([0x0f, 1], [2])], []])) }466 #expect(throws: PSBTError.duplicateKey) { try PSBT(parsing: raw([([0], txBytes)], [[], [([0x00], [0x51]), ([0x00], [0x52])]])) }467 #expect(throws: PSBTError.invalidField("global unsigned transaction key")) { try PSBT(parsing: raw([([0, 1], txBytes)], [[], []])) }468 #expect(throws: PSBTError.unsupportedVersion(2)) { try PSBT(parsing: raw([([0], txBytes), ([0xfb], [2, 0, 0, 0])], [[], []])) }469 #expect(throws: PSBTError.invalidField("global version")) { try PSBT(parsing: raw([([0], txBytes), ([0xfb], [0])], [[], []])) }470 let v0 = try PSBT(parsing: raw([([0], txBytes), ([0xfb], [0, 0, 0, 0])], [[], []]))471 #expect(v0.version == 0)472 #expect(try PSBT(parsing: v0.serialized()) == v0)473 // unsigned transaction carrying a scriptSig, or in witness form474 var signed = tx475 signed.inputs[0].scriptSig = [0x51]476 #expect(throws: PSBTError.unsignedTransactionNotEmpty) { try PSBT(parsing: raw([([0], signed.serialized())], [[], []])) }477 var witnessed = tx478 witnessed.inputs[0].witness = [[1]]479 #expect((try? PSBT(parsing: raw([([0], witnessed.serialized())], [[], []]))) == nil)480 // missing output map, extra map481 #expect((try? PSBT(parsing: raw([([0], txBytes)], [[]]))) == nil)482 #expect(throws: PSBTError.serialization(.trailingBytes)) { try PSBT(parsing: raw([([0], txBytes)], [[], [], []])) }483 // malformed typed fields484 let bad: [(Bytes, Bytes)] = [485 ([0x01], [1, 2, 3]), // witness UTXO too short486 ([0x01], Wire.u64(5) + [0x01, 0x51, 0x00]), // witness UTXO with trailing byte487 ([0x01, 0x00], Wire.u64(5) + [0x01, 0x51]), // key data on a keyless field488 ([0x02] + Bytes(repeating: 2, count: 32), [0x30]), // partial signature key of 32 bytes489 ([0x02, 0x05] + Bytes(repeating: 2, count: 32), [0x30]), // not a public key490 ([0x03], [1, 0, 0]), // sighash type of 3 bytes491 ([0x04, 0x00], [0x51]), ([0x05, 0x00], [0x51]), ([0x07, 0x00], [0x51]), ([0x08, 0x00], [0x00]),492 ([0x06] + generatorKey, [1, 2, 3, 4, 5]), // derivation not a multiple of 4493 ([0x06] + generatorKey, []), // derivation without fingerprint494 ([0x06] + Bytes(generatorKey.dropLast()), [1, 2, 3, 4]), // derivation key of 32 bytes495 ([0x08], [0x02, 0x01, 0x51]), // witness stack shorter than announced496 ([0x08], [0x01, 0x01, 0x51, 0x00]), // witness stack with trailing byte497 ([0x00], [1, 2, 3]), // non-witness UTXO that is not a transaction498 ]499 for (k, v) in bad {500 #expect((try? PSBT(parsing: raw([([0], txBytes)], [[(k, v)], []]))) == nil, "accepted input field \(k.hex)")501 }502 for (k, v) in [([0x00, 0x00], [0x51]), ([0x01, 0x00], [0x51]), ([0x02] + generatorKey, [1, 2, 3]), ([0x02, 0x09], [1, 2, 3, 4])] as [(Bytes, Bytes)] {503 #expect((try? PSBT(parsing: raw([([0], txBytes)], [[], [(k, v)]]))) == nil, "accepted output field \(k.hex)")504 }505 // value length running past the end; key length running past the end506 #expect((try? PSBT(parsing: PSBT.magic + [0x01, 0x00, 0xfd, 0xff, 0xff, 0x00])) == nil)507 #expect((try? PSBT(parsing: PSBT.magic + [0xfe, 0xff, 0xff, 0xff, 0x7f, 0x00])) == nil)508 #expect((try? PSBT(parsing: PSBT.magic + [0xfd, 0x01, 0x00, 0x00])) == nil)509 }510511 /// 2-of-3 P2WSH wallet from a descriptor: update, two cosigners on separate copies, combine, finalize, extract.512 @Test func multisigAccountPSBTFlow() throws {513 let cosigners = try (1...3).map { try ExtendedKey.master(seed: Bytes(repeating: UInt8($0), count: 32)) }514 let path = DerivationPath("m/48'/1'/0'/2'")!515 let accounts = try cosigners.map { try $0.derive(path) }516 let keys = try zip(cosigners, accounts).map { master, account in517 try DescriptorKey(extendedKey: account, testNetwork: true, origin: .init(fingerprint: master.fingerprint, path: path),518 steps: [.multipath([0, 1])], wildcard: true)519 }520 let descriptor = try OutputDescriptor.wshMultisig(required: 2, keys: keys, sorted: true)521 let wallet = try MultisigAccount(descriptor: descriptor.string, network: .testnet)522 let witnessScript = try wallet.witnessScript(chain: .receive, index: 3)523 let utxo = BitcoinUTXO(outPoint: BitcoinOutPoint(hash: Bytes(repeating: 0x21, count: 32), index: 1)!, value: 250_000,524 scriptPubKey: try wallet.scriptPubKey(chain: .receive, index: 3), confirmations: 3, witnessScript: witnessScript)525 var request = BitcoinSpendRequest(recipients: [.init(value: 100_000, scriptPubKey: try BitcoinScript.p2wpkh(publicKey: testPublicKey(4)))],526 utxos: [utxo], feeRate: FeeRate(satPerVByte: 10), changeScript: try wallet.scriptPubKey(chain: .change, index: 0))527 request.seed = 7528 let plan = try BitcoinTransactionBuilder.build(request)529 var psbt = try plan.psbt()530 #expect(psbt.inputs[0].witnessScript == witnessScript)531 psbt.inputs[0].witnessScript = nil532 #expect(try wallet.update(psbt: &psbt, searchLimit: 5) == 1)533 #expect(psbt.inputs[0].witnessScript == witnessScript)534 #expect(psbt.inputs[0].derivations.count == 3)535 #expect(psbt.inputs[0].derivations.allSatisfy { $0.path.description.hasPrefix("m/48'/1'/0'/2'/0/3") })536 let change = try #require(plan.changeIndex)537 #expect(psbt.outputs[change].witnessScript == (try wallet.witnessScript(chain: .change, index: 0)))538 #expect(psbt.outputs[change].derivations.count == 3)539540 var a = psbt, c = psbt541 #expect(try wallet.sign(psbt: &a, cosignerKey: accounts[0], searchLimit: 5) == 1)542 #expect(try wallet.sign(psbt: &c, cosignerKey: accounts[2], searchLimit: 5) == 1)543 #expect(try wallet.sign(psbt: &a, cosignerKey: accounts[0], searchLimit: 5) == 0)544 #expect(throws: BitcoinAccountError.invalidAccountKey) { try wallet.sign(psbt: &a, cosignerKey: cosigners[0], searchLimit: 5) }545 #expect(throws: BitcoinAccountError.watchOnly) { try wallet.sign(psbt: &a, cosignerKey: accounts[1].neutered, searchLimit: 5) }546 #expect(throws: PSBTError.notEnoughSignatures) {547 var one = a548 try one.finalize()549 }550 var combined = try PSBT.combine([a, c])551 #expect(combined.inputs[0].partialSignatures.count == 2)552 try combined.finalize()553 let witness = try #require(combined.inputs[0].finalScriptWitness)554 #expect(witness.count == 4 && witness[0].isEmpty && witness[3] == witnessScript)555 let tx = try combined.extractTransaction()556 try BitcoinVerifier.verify(transaction: tx, spentOutputs: [utxo.output])557 #expect(tx.weight <= plan.estimatedWeight && plan.estimatedWeight - tx.weight <= 4)558 #expect(plan.fee >= plan.targetFeeRate.fee(weight: tx.weight))559 // a third signature is harmless: the finalizer keeps the threshold560 var all = try PSBT.combine([a, c])561 #expect(try wallet.sign(psbt: &all, cosignerKey: accounts[1], searchLimit: 5) == 1)562 try all.finalize()563 #expect(all.inputs[0].finalScriptWitness?.count == 4)564 try BitcoinVerifier.verify(transaction: try all.extractTransaction(), spentOutputs: [utxo.output])565 }566}567