Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Tests/QyvoraBitcoinTests/TransactionTests.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 QyvoraMath43import QyvoraSymmetric44import QyvoraSecp256k145import QyvoraCore46@testable import QyvoraBitcoin4748@Suite struct BIP143Tests {49 private func check(_ v: BIP143Vectors.Signing, tx: BitcoinTransaction, input: Int, scriptCode: Bytes, value: UInt64, type: BitcoinSighashType) throws {50 let preimage = try BitcoinSighash.segwitV0Preimage(transaction: tx, inputIndex: input, scriptCode: scriptCode, value: value, type: type)51 #expect(preimage.hex == v.preimage)52 let digest = try BitcoinSighash.segwitV0(transaction: tx, inputIndex: input, scriptCode: scriptCode, value: value, type: type)53 #expect(digest.hex == v.sigHash)54 // RFC 6979 + low-s reproduces the signature of the BIP byte for byte55 let signature = try BitcoinSigner.signature(digest: digest, privateKey: unhex(v.privateKey), sighashType: type)56 #expect(signature.hex == v.signature)57 #expect(try Secp256k1.publicKey(privateKey: unhex(v.privateKey)).hex == v.publicKey)58 #expect(BitcoinVerifier.checkSignature(unhex(v.signature), publicKey: unhex(v.publicKey), requireLowS: true) { _ in digest })59 }6061 @Test func nativeP2WPKH() throws {62 let v = BIP143Vectors.p2wpkh[0]63 var tx = try BitcoinTransaction(hex: BIP143Vectors.p2wpkhUnsigned)64 #expect(tx.hex == BIP143Vectors.p2wpkhUnsigned)65 let hash = unhex("1d0f172a0ecb48aee1be1f2687d2963ae33f71a1")66 #expect(try BitcoinSigner.p2wpkhScriptCode(publicKeyHash: hash).hex == v.scriptCode)67 try check(v, tx: tx, input: 1, scriptCode: unhex(v.scriptCode), value: 600_000_000, type: .all)6869 // signing through the public entry point gives the witness of the BIP's signed transaction70 let signed = try BitcoinTransaction(hex: BIP143Vectors.p2wpkhSigned)71 try BitcoinSigner.signP2WPKH(transaction: &tx, inputIndex: 1, privateKey: unhex(v.privateKey), value: 600_000_000,72 spentScriptPubKey: unhex("0014") + hash)73 #expect(tx.inputs[1].witness == signed.inputs[1].witness)74 #expect(tx.inputs[1].witness == [unhex(v.signature), unhex(v.publicKey)])75 // with the P2PK scriptSig of the BIP the whole transaction is reproduced76 tx.inputs[0].scriptSig = signed.inputs[0].scriptSig77 #expect(tx.hex == BIP143Vectors.p2wpkhSigned)78 let spent = BitcoinTransaction.Output(value: 600_000_000, scriptPubKey: unhex("0014") + hash)79 try BitcoinVerifier.verifyInput(transaction: signed, inputIndex: 1, spentOutput: spent)80 // the amount is committed: another value must fail81 #expect(throws: BitcoinVerifier.Error.invalidSignature) {82 try BitcoinVerifier.verifyInput(transaction: signed, inputIndex: 1, spentOutput: .init(value: 600_000_001, scriptPubKey: spent.scriptPubKey))83 }84 // P2PK inputs are outside the verifier: reported as unsupported, never as valid85 #expect(throws: BitcoinVerifier.Error.unsupportedScript) {86 try BitcoinVerifier.verifyInput(transaction: signed, inputIndex: 0, spentOutput: .init(87 value: 625_000_000, scriptPubKey: unhex("2103c9f4836b9a4f77fc0d81f7bcb01b7f1b35916864b9476c241ce9fc198bd25432ac")))88 }89 #expect(throws: BitcoinSigner.Error.keyNotInScript) {90 var copy = tx91 try BitcoinSigner.signP2WPKH(transaction: ©, inputIndex: 1, privateKey: testKey(9), value: 1, spentScriptPubKey: unhex("0014") + hash)92 }93 }9495 @Test func p2shP2WPKH() throws {96 let v = BIP143Vectors.p2shP2wpkh[0]97 let tx = try BitcoinTransaction(hex: BIP143Vectors.p2shP2wpkhUnsigned)98 try check(v, tx: tx, input: 0, scriptCode: unhex(v.scriptCode), value: 1_000_000_000, type: .all)99 let signed = try BitcoinTransaction(hex: BIP143Vectors.p2shP2wpkhSigned)100 #expect(signed.hex == BIP143Vectors.p2shP2wpkhSigned)101 try BitcoinVerifier.verifyInput(transaction: signed, inputIndex: 0, spentOutput: .init(102 value: 1_000_000_000, scriptPubKey: unhex("a9144733f37cf4db86fbc2efed2500b4f4e49f31202387")))103 #expect(throws: BitcoinVerifier.Error.scriptMismatch) {104 try BitcoinVerifier.verifyInput(transaction: signed, inputIndex: 0, spentOutput: .init(105 value: 1_000_000_000, scriptPubKey: unhex("a9144733f37cf4db86fbc2efed2500b4f4e49f31202487")))106 }107 }108109 /// OP_CODESEPARATOR and SIGHASH_SINGLE without a matching output: the hashOutputs is zero.110 @Test func nativeP2WSHSighashVectors() throws {111 let tx = try BitcoinTransaction(hex: BIP143Vectors.p2wshUnsigned)112 for v in BIP143Vectors.p2wsh {113 // the vector prints scriptCode with its length prefix114 let scriptCode = Bytes(unhex(v.scriptCode).dropFirst())115 try check(v, tx: tx, input: 1, scriptCode: scriptCode, value: 4_900_000_000, type: .single)116 }117 #expect(Bytes(unhex(BIP143Vectors.p2wsh[0].scriptCode).dropFirst()) == unhex(BIP143Vectors.p2wshWitnessScript))118 let signed = try BitcoinTransaction(hex: BIP143Vectors.p2wshSigned)119 #expect(signed.hex == BIP143Vectors.p2wshSigned)120 #expect(signed.inputs[1].witness.count == 3)121 #expect(signed.inputs[1].witness[2] == unhex(BIP143Vectors.p2wshWitnessScript))122 }123124 /// 6-of-6 multisig, one signature per SIGHASH type.125 @Test func p2shP2WSHAllSighashTypes() throws {126 let tx = try BitcoinTransaction(hex: BIP143Vectors.p2shP2wshUnsigned)127 let witnessScript = unhex(BIP143Vectors.p2shP2wshWitnessScript)128 let types: [BitcoinSighashType] = [.all, .none, .single, .allAnyoneCanPay, .noneAnyoneCanPay, .singleAnyoneCanPay]129 let value: UInt64 = 987_654_321130 var partials = [BitcoinPartialSignature]()131 for (v, type) in zip(BIP143Vectors.p2shP2wsh, types) {132 try check(v, tx: tx, input: 0, scriptCode: witnessScript, value: value, type: type)133 let partial = try BitcoinSigner.signP2WSHMultisig(transaction: tx, inputIndex: 0, witnessScript: witnessScript, value: value,134 privateKey: unhex(v.privateKey), sighashType: type)135 #expect(partial.signature.hex == v.signature && partial.publicKey.hex == v.publicKey)136 #expect(partial.sighashType == type)137 partials.append(partial)138 }139 let parsed = try #require(BitcoinScript.parseMultisig(witnessScript))140 #expect(parsed.required == 6 && parsed.publicKeys.map(\.hex) == BIP143Vectors.p2shP2wsh.map(\.publicKey))141142 // witness assembly from shuffled partial signatures reproduces the signed transaction of the BIP143 let signed = try BitcoinTransaction(hex: BIP143Vectors.p2shP2wshSigned)144 var mine = tx145 mine.inputs[0].witness = try BitcoinSigner.multisigWitness(witnessScript: witnessScript, signatures: partials.reversed())146 mine.inputs[0].scriptSig = BitcoinScript.pushRaw(try BitcoinScript.p2wsh(witnessScript: witnessScript))147 #expect(mine == signed)148 #expect(mine.hex == BIP143Vectors.p2shP2wshSigned)149 let spent = BitcoinTransaction.Output(value: value, scriptPubKey: unhex("a9149993a429037b5d912407a71c252019287b8d27a587"))150 try BitcoinVerifier.verify(transaction: signed, spentOutputs: [spent])151152 #expect(throws: BitcoinSigner.Error.notEnoughSignatures) {153 try BitcoinSigner.multisigWitness(witnessScript: witnessScript, signatures: Array(partials.dropLast()))154 }155 #expect(throws: BitcoinSigner.Error.keyNotInScript) {156 try BitcoinSigner.signP2WSHMultisig(transaction: tx, inputIndex: 0, witnessScript: witnessScript, value: value, privateKey: testKey(3))157 }158 #expect(throws: BitcoinSigner.Error.notMultisigScript) {159 try BitcoinSigner.signP2WSHMultisig(transaction: tx, inputIndex: 0, witnessScript: [0x51], value: value, privateKey: testKey(3))160 }161 // swapping two signatures breaks the CHECKMULTISIG order162 var swapped = signed163 swapped.inputs[0].witness.swapAt(1, 2)164 #expect(!BitcoinVerifier.isValid(transaction: swapped, spentOutputs: [spent]))165 // a non-empty dummy element is refused (NULLDUMMY)166 var dummy = signed167 dummy.inputs[0].witness[0] = [0]168 #expect(throws: BitcoinVerifier.Error.malformedUnlockingData) { try BitcoinVerifier.verify(transaction: dummy, spentOutputs: [spent]) }169 }170}171172@Suite struct TransactionTests {173 /// Real testnet transactions quoted by BIP-174 (the two funding transactions of its workflow): their identifiers are174 /// the outpoints spent by the BIP's PSBT, which makes the vectors self-checking.175 @Test func realSegwitTransactionsRoundTrip() throws {176 let expected = ["75ddabb27b8845f5247975c8a5ba7c6f336c4570708ebe230caf6db5217ae858",177 "1dea7cd05979072a3578cab271c02244ea8a090bbb46aa680a65ecd027048d83"]178 // the BIP lists them in the other order179 var found = Set<String>()180 for hex in BIP174Vectors.previousTransactions {181 let tx = try BitcoinTransaction(hex: hex)182 #expect(tx.hex == hex)183 found.insert(tx.txid)184 let stripped = try BitcoinTransaction(parsing: tx.serialized(includeWitness: false))185 #expect(stripped.txid == tx.txid)186 #expect(tx.weight == tx.serialized(includeWitness: false).count * 3 + tx.serialized().count)187 #expect(tx.vsize == (tx.weight + 3) / 4)188 if tx.hasWitness {189 #expect(tx.wtxid != tx.txid)190 #expect(tx.serialized().count > stripped.serialized().count)191 } else {192 #expect(tx.wtxid == tx.txid)193 #expect(tx.weight == tx.serialized().count * 4)194 }195 }196 #expect(found == Set(expected))197 // the P2SH-P2WPKH input of the first funding transaction verifies against nothing we know, but the final198 // transaction of the BIP spends both and is checked in the PSBT suite.199 let segwit = try BitcoinTransaction(hex: BIP174Vectors.previousTransactions[0])200 #expect(segwit.hasWitness && segwit.inputs[0].witness.count == 2)201 #expect(segwit.version == 2 && segwit.outputs.count == 2)202 #expect(segwit.outputValue == segwit.outputs[0].value + segwit.outputs[1].value)203 }204205 @Test func bip143SignedTransactionIdentity() throws {206 let tx = try BitcoinTransaction(hex: BIP143Vectors.p2wpkhSigned)207 #expect(tx.version == 1 && tx.lockTime == 17)208 #expect(tx.inputs[0].sequence == 0xffff_ffee && tx.inputs[1].sequence == 0xffff_ffff)209 #expect(tx.inputs[1].previousOutput.txid == "8ac60eb9575db5b2d987e29f301b5b819ea83a5c6579d282d189cc04b8e151ef")210 #expect(tx.inputs[1].previousOutput.index == 1)211 #expect(tx.outputs.map(\.value) == [112_340_000, 223_450_000])212 #expect(tx.txid == Hex.encode(SHA256.double(tx.serialized(includeWitness: false)).reversed()))213 #expect(tx.txid.count == 64)214 // base size 204, total 343 → weight 955, vsize 239215 #expect(tx.serialized(includeWitness: false).count * 3 + tx.serialized().count == tx.weight)216 // sequence 0xffffffee on the first input is below 0xfffffffe: replaceable under BIP-125217 #expect(tx.signalsRBF)218 }219220 @Test func outPoint() throws {221 let txid = "75ddabb27b8845f5247975c8a5ba7c6f336c4570708ebe230caf6db5217ae858"222 let op = try #require(BitcoinOutPoint(txid: txid, vout: 3))223 #expect(op.txid == txid && op.index == 3)224 #expect(op.hash.hex == "58e87a21b56daf0c23be8e7070456c336f7cbaa5c8757924f545887bb2abdd75")225 #expect(op.description == txid + ":3")226 #expect(BitcoinOutPoint(hash: op.hash, index: 3) == op)227 #expect(BitcoinOutPoint(txid: "abcd", vout: 0) == nil)228 #expect(BitcoinOutPoint(txid: String(repeating: "z", count: 64), vout: 0) == nil)229 #expect(BitcoinOutPoint(hash: [1, 2, 3], index: 0) == nil)230 }231232 private func sample() -> BitcoinTransaction {233 let op = BitcoinOutPoint(hash: Bytes(repeating: 0xab, count: 32), index: 1)!234 return BitcoinTransaction(inputs: [.init(previousOutput: op, sequence: BitcoinTransaction.Input.sequenceRBF, witness: [[1, 2], []])],235 outputs: [.init(value: 5000, scriptPubKey: unhex("0014") + Bytes(repeating: 7, count: 20))], lockTime: 800_000)236 }237238 @Test func buildAndReparse() throws {239 let tx = sample()240 let bytes = tx.serialized()241 #expect(Array(bytes[4..<6]) == [0x00, 0x01])242 #expect(try BitcoinTransaction(parsing: bytes) == tx)243 #expect(tx.signalsRBF)244 var legacy = tx245 legacy.inputs[0].witness = []246 #expect(legacy.serialized() == tx.serialized(includeWitness: false))247 #expect(try BitcoinTransaction(parsing: legacy.serialized()) == legacy)248 #expect(legacy.txid == tx.txid && legacy.wtxid != tx.wtxid)249 // negative version survives the round trip250 var negative = tx251 negative.version = -1252 #expect(try BitcoinTransaction(parsing: negative.serialized()).version == -1)253 }254255 @Test func parserRejectsMalformedData() throws {256 let tx = sample()257 let bytes = tx.serialized()258 // every strict prefix is truncated (or otherwise invalid): none may parse259 for n in 0..<bytes.count {260 #expect((try? BitcoinTransaction(parsing: Array(bytes.prefix(n)))) == nil, "prefix \(n) parsed")261 }262 #expect(throws: BitcoinSerializationError.trailingBytes) { try BitcoinTransaction(parsing: bytes + [0]) }263 #expect(throws: BitcoinSerializationError.malformed("hexadecimal")) { try BitcoinTransaction(hex: "zz") }264265 var legacy = tx266 legacy.inputs[0].witness = []267 let plain = legacy.serialized()268 // input count 0xfd 0x01 0x00: non-canonical CompactSize269 #expect(throws: BitcoinSerializationError.nonCanonicalVarInt) {270 try BitcoinTransaction(parsing: Array(plain[0..<4]) + [0xfd, 0x01, 0x00] + Array(plain[5...]))271 }272 #expect(throws: BitcoinSerializationError.nonCanonicalVarInt) {273 try BitcoinTransaction(parsing: Array(plain[0..<4]) + [0xfe, 0x01, 0x00, 0x00, 0x00] + Array(plain[5...]))274 }275 #expect(throws: BitcoinSerializationError.nonCanonicalVarInt) {276 try BitcoinTransaction(parsing: Array(plain[0..<4]) + [0xff, 1, 0, 0, 0, 0, 0, 0, 0] + Array(plain[5...]))277 }278 // input count far beyond what the data can hold279 #expect(throws: BitcoinSerializationError.oversized) {280 try BitcoinTransaction(parsing: Array(plain[0..<4]) + [0xfe, 0xff, 0xff, 0xff, 0x7f] + Array(plain[5...]))281 }282 #expect(throws: BitcoinSerializationError.oversized) {283 try BitcoinTransaction(parsing: Array(plain[0..<4]) + [0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff] + Array(plain[5...]))284 }285 // scriptSig length larger than the rest286 var longScript = plain287 longScript[4 + 1 + 36] = 0xfc288 #expect(throws: BitcoinSerializationError.truncated) { try BitcoinTransaction(parsing: longScript) }289 // witness flag other than 1290 var flag = bytes291 flag[5] = 0x02292 #expect((try? BitcoinTransaction(parsing: flag)) == nil)293 // witness flag set while every witness is empty294 let superfluous = Array(plain[0..<4]) + [0x00, 0x01] + Array(plain[4..<(plain.count - 4)]) + [0x00] + Array(plain.suffix(4))295 #expect(throws: BitcoinSerializationError.malformed("superfluous witness record")) { try BitcoinTransaction(parsing: superfluous) }296 // witness item count beyond the data297 var items = bytes298 let witnessStart = bytes.count - 4 - 5299 #expect(bytes[witnessStart] == 2)300 items[witnessStart] = 0xfc301 #expect((try? BitcoinTransaction(parsing: items)) == nil)302 // the witness form is refused when the caller asks for the legacy form only303 #expect((try? BitcoinTransaction(parsing: bytes, allowWitness: false)) == nil)304 #expect(try BitcoinTransaction(parsing: plain, allowWitness: false) == legacy)305 // larger than a block306 #expect(throws: BitcoinSerializationError.oversized) { try BitcoinTransaction(parsing: Bytes(repeating: 0, count: 4_000_001)) }307 }308309 @Test func sanityChecks() throws {310 let tx = sample()311 try tx.checkSanity()312 var t = tx313 t.inputs = []314 #expect(throws: BitcoinTransaction.SanityError.noInputs) { try t.checkSanity() }315 t = tx316 t.outputs = []317 #expect(throws: BitcoinTransaction.SanityError.noOutputs) { try t.checkSanity() }318 t = tx319 t.outputs[0].value = BitcoinLimits.maxMoney + 1320 #expect(throws: BitcoinTransaction.SanityError.valueOutOfRange) { try t.checkSanity() }321 #expect(t.outputValue == nil)322 t = tx323 t.outputs = [.init(value: BitcoinLimits.maxMoney, scriptPubKey: []), .init(value: 1, scriptPubKey: [])]324 #expect(throws: BitcoinTransaction.SanityError.valueOutOfRange) { try t.checkSanity() }325 t = tx326 t.inputs.append(t.inputs[0])327 #expect(throws: BitcoinTransaction.SanityError.duplicateInput) { try t.checkSanity() }328 t = tx329 t.inputs[0].previousOutput = BitcoinOutPoint(hash: Bytes(repeating: 0, count: 32), index: 0xffff_ffff)!330 #expect(throws: BitcoinTransaction.SanityError.nullInput) { try t.checkSanity() }331 }332333 @Test func sighashEdgeCases() throws {334 let tx = sample()335 #expect(throws: BitcoinSighash.Error.inputIndexOutOfRange) {336 try BitcoinSighash.segwitV0(transaction: tx, inputIndex: 1, scriptCode: [], value: 0)337 }338 #expect(throws: BitcoinSighash.Error.inputIndexOutOfRange) { try BitcoinSighash.legacy(transaction: tx, inputIndex: -1, scriptCode: []) }339 // legacy SIGHASH_SINGLE without a matching output hashes to "one"340 var two = tx341 two.inputs.append(.init(previousOutput: BitcoinOutPoint(hash: Bytes(repeating: 1, count: 32), index: 0)!))342 #expect(try BitcoinSighash.legacy(transaction: two, inputIndex: 1, scriptCode: [0x51], type: .single) == [1] + Bytes(repeating: 0, count: 31))343 // every SIGHASH type gives a distinct digest, for both algorithms344 let types: [BitcoinSighashType] = [.all, .none, .single, .allAnyoneCanPay, .noneAnyoneCanPay, .singleAnyoneCanPay]345 #expect(Set(try types.map { try BitcoinSighash.segwitV0(transaction: two, inputIndex: 0, scriptCode: [0x51], value: 1, type: $0) }).count == 6)346 #expect(Set(try types.map { try BitcoinSighash.legacy(transaction: two, inputIndex: 0, scriptCode: [0x51], type: $0) }).count == 6)347 // OP_CODESEPARATOR is removed from the legacy scriptCode348 #expect(try BitcoinSighash.legacy(transaction: tx, inputIndex: 0, scriptCode: [0x51, 0xab, 0x52])349 == BitcoinSighash.legacy(transaction: tx, inputIndex: 0, scriptCode: [0x51, 0x52]))350 #expect(throws: BitcoinSigner.Error.nonStandardSighashType) {351 try BitcoinSigner.signature(digest: Bytes(repeating: 1, count: 32), privateKey: testKey(1), sighashType: .init(rawValue: 0))352 }353 #expect(throws: BitcoinSigner.Error.invalidPrivateKey) {354 try BitcoinSigner.signature(digest: Bytes(repeating: 1, count: 32), privateKey: Bytes(repeating: 0, count: 32))355 }356 }357358 /// Build, sign and verify a 2-of-3 P2WSH spend and a P2WPKH spend in one transaction; then tamper with it.359 @Test func signAndVerifyOwnTransaction() throws {360 let keys = (1...3).map { testPublicKey(UInt8($0)) }361 for sorted in [false, true] {362 let witnessScript = try BitcoinScript.multisig(required: 2, publicKeys: keys.reversed(), sorted: sorted)363 let spent = [BitcoinTransaction.Output(value: 100_000, scriptPubKey: try BitcoinScript.p2wsh(witnessScript: witnessScript)),364 BitcoinTransaction.Output(value: 50_000, scriptPubKey: try BitcoinScript.p2wpkh(publicKey: testPublicKey(7)))]365 var tx = BitcoinTransaction(inputs: [.init(previousOutput: BitcoinOutPoint(hash: Bytes(repeating: 3, count: 32), index: 0)!),366 .init(previousOutput: BitcoinOutPoint(hash: Bytes(repeating: 4, count: 32), index: 5)!)],367 outputs: [.init(value: 149_000, scriptPubKey: try BitcoinScript.p2tr(outputKey: Bytes(repeating: 9, count: 32)))])368 try BitcoinSigner.signP2WPKH(transaction: &tx, inputIndex: 1, privateKey: testKey(7), value: 50_000, spentScriptPubKey: spent[1].scriptPubKey)369 let a = try BitcoinSigner.signP2WSHMultisig(transaction: tx, inputIndex: 0, witnessScript: witnessScript, value: 100_000, privateKey: testKey(3))370 let b = try BitcoinSigner.signP2WSHMultisig(transaction: tx, inputIndex: 0, witnessScript: witnessScript, value: 100_000, privateKey: testKey(1))371 #expect(throws: BitcoinSigner.Error.notEnoughSignatures) { try BitcoinSigner.multisigWitness(witnessScript: witnessScript, signatures: [a]) }372 tx.inputs[0].witness = try BitcoinSigner.multisigWitness(witnessScript: witnessScript, signatures: [a, b])373 #expect(tx.inputs[0].witness.count == 4 && tx.inputs[0].witness[0].isEmpty)374 try BitcoinVerifier.verify(transaction: tx, spentOutputs: spent)375 #expect(try BitcoinTransaction(parsing: tx.serialized()) == tx)376 // the estimate is an upper bound of the real weight, within a few units377 let estimate = BitcoinSizeEstimator.transactionWeight(378 inputWeights: [BitcoinSizeEstimator.inputWeight(scriptPubKey: spent[0].scriptPubKey, witnessScript: witnessScript)!,379 BitcoinSizeEstimator.inputWeight(scriptPubKey: spent[1].scriptPubKey)!],380 outputScripts: tx.outputs.map(\.scriptPubKey))381 #expect(estimate >= tx.weight && estimate - tx.weight <= 3 * 2)382383 var tampered = tx384 tampered.outputs[0].value -= 1385 #expect(throws: BitcoinVerifier.Error.invalidSignature) { try BitcoinVerifier.verify(transaction: tampered, spentOutputs: spent) }386 #expect(!BitcoinVerifier.isValid(transaction: tx, spentOutputs: [spent[0], .init(value: 50_001, scriptPubKey: spent[1].scriptPubKey)]))387 #expect(throws: BitcoinVerifier.Error.spentOutputCountMismatch) { try BitcoinVerifier.verify(transaction: tx, spentOutputs: [spent[0]]) }388 var wrongScript = tx389 wrongScript.inputs[0].witness[3] = try BitcoinScript.multisig(required: 1, publicKeys: keys, sorted: false)390 #expect(throws: BitcoinVerifier.Error.scriptMismatch) { try BitcoinVerifier.verify(transaction: wrongScript, spentOutputs: spent) }391 var noWitness = tx392 noWitness.inputs[1].witness = []393 #expect(throws: BitcoinVerifier.Error.malformedUnlockingData) { try BitcoinVerifier.verify(transaction: noWitness, spentOutputs: spent) }394 // high-s twin of a valid signature: rejected by policy, accepted when asked for consensus rules only395 var highS = tx396 let der = Bytes(tx.inputs[1].witness[0].dropLast())397 let compact = try Secp256k1.parseDER(der)398 let n = unhex("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141")399 var s = Bytes(repeating: 0, count: 32)400 var borrow = 0401 for i in stride(from: 31, through: 0, by: -1) {402 let d = Int(n[i]) - Int(compact[32 + i]) - borrow403 s[i] = UInt8((d + 256) % 256)404 borrow = d < 0 ? 1 : 0405 }406 func derInteger(_ v: Bytes) -> Bytes {407 var b = Bytes(v.drop(while: { $0 == 0 }))408 if b[0] & 0x80 != 0 { b.insert(0, at: 0) }409 return [0x02, UInt8(b.count)] + b410 }411 let body = derInteger(Bytes(compact[0..<32])) + derInteger(s)412 highS.inputs[1].witness[0] = [0x30, UInt8(body.count)] + body + [0x01]413 #expect(throws: BitcoinVerifier.Error.invalidSignature) { try BitcoinVerifier.verifyInput(transaction: highS, inputIndex: 1, spentOutput: spent[1]) }414 try BitcoinVerifier.verifyInput(transaction: highS, inputIndex: 1, spentOutput: spent[1], requireLowS: false)415 }416 }417}418