Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : security/tests/Sources/FuzzTargets/Targets+Bitcoin.swift8// Module : Tests9// 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 AuditSupport42import Foundation43import QyvoraBitcoin44import QyvoraCore45import QyvoraMath46import QyvoraSecp256k14748// Bitcoin parsers: transactions, PSBT, output descriptors, addresses, scripts, WIF.4950/// String literals of the engine's own test sources (official BIP vectors), reused as fuzz seeds.51/// Only called by `qyfuzz seed`, on a checkout.52func repoLiterals(_ relativePath: String, pattern: String, limit: Int = 40) -> [String] {53 let url = AuditPaths.repo.appendingPathComponent(relativePath)54 guard let text = try? String(contentsOf: url, encoding: .utf8), let re = try? NSRegularExpression(pattern: pattern) else { return [] }55 var seen = Set<String>()56 var out = [String]()57 for m in re.matches(in: text, range: NSRange(text.startIndex..., in: text)) {58 guard let r = Range(m.range(at: 1), in: text) else { continue }59 let s = String(text[r])60 if seen.insert(s).inserted { out.append(s) }61 if out.count >= limit { break }62 }63 return out64}6566func testSources(_ module: String) -> [String] {67 let dir = AuditPaths.repo.appendingPathComponent("Tests/\(module)Tests")68 let names = (try? FileManager.default.contentsOfDirectory(atPath: dir.path)) ?? []69 return names.filter { $0.hasSuffix(".swift") }.sorted().map { "Tests/\(module)Tests/\($0)" }70}7172func fixtureTransaction() -> BitcoinTransaction {73 let prev = BitcoinOutPoint(hash: fixtureBytes("prev", 32), index: 1)!74 let key = (try? Secp256k1.publicKey(privateKey: fixtureBytes("txkey", 32))) ?? Bytes(repeating: 2, count: 33)75 let script = (try? BitcoinScript.p2wpkh(publicKey: key)) ?? []76 return BitcoinTransaction(77 inputs: [.init(previousOutput: prev, sequence: 0xffff_fffd, witness: [Bytes(repeating: 0x30, count: 71), key])],78 outputs: [.init(value: 50_000, scriptPubKey: script), .init(value: 1_234, scriptPubKey: script)], lockTime: 0)79}8081func transactionSeeds() -> [Bytes] {82 var out = [fixtureTransaction().serialized(), fixtureTransaction().serialized(includeWitness: false)]83 for f in testSources("QyvoraBitcoin") {84 for h in repoLiterals(f, pattern: "\"((?:01|02)000000[0-9a-f]{100,2000})\"", limit: 12) {85 if let b = Hex.decode(h), out.count < 24 { out.append(b) }86 }87 }88 return out89}9091func psbtSeeds() -> [Bytes] {92 var out = [Bytes]()93 if var unsigned = Optional(fixtureTransaction()) {94 unsigned.inputs[0].witness = []95 if let p = try? PSBT(unsignedTransaction: unsigned) { out.append(p.serialized()) }96 }97 for f in testSources("QyvoraBitcoin") {98 for h in repoLiterals(f, pattern: "\"(70736274ff[0-9a-f]{20,4000})\"", limit: 16) {99 if let b = Hex.decode(h), out.count < 28 { out.append(b) }100 }101 for s in repoLiterals(f, pattern: "\"(cHNidP[A-Za-z0-9+/=]{20,4000})\"", limit: 16) {102 if let d = Data(base64Encoded: s), out.count < 28 { out.append(Bytes(d)) }103 }104 }105 return out106}107108func descriptorSeeds() -> [Bytes] {109 var out = [Bytes]()110 if let master = try? ExtendedKey.master(seed: fixtureBytes("descriptor", 32)) {111 for network in [BitcoinNetwork.mainnet, .testnet] {112 if let account = try? BIP84Account(master: master, network: network), let d = try? account.descriptors() {113 out += [Bytes(d.receive.string.utf8), Bytes(d.change.string.utf8), Bytes(d.combined.string.utf8)]114 }115 }116 }117 for f in testSources("QyvoraBitcoin") {118 for s in repoLiterals(f, pattern: "\"((?:wpkh|wsh)\\([^\"\\\\]{10,600})\"", limit: 14) where out.count < 30 {119 out.append(Bytes(s.utf8))120 }121 }122 return out123}124125func addressSeeds() -> [Bytes] {126 var out = [Bytes]()127 let key = (try? Secp256k1.publicKey(privateKey: fixtureBytes("addr", 32))) ?? []128 for network in BitcoinNetwork.allCases {129 if let a = try? BitcoinAddress.p2wpkh(publicKey: key, network: network) { out.append(Bytes(a.string.utf8)) }130 if let a = try? BitcoinAddress.p2wsh(witnessScript: [0x51], network: network) { out.append(Bytes(a.string.utf8)) }131 for script in [try? BitcoinScript.p2pkh(publicKey: key), try? BitcoinScript.p2sh(redeemScript: [0x51]), try? BitcoinScript.p2tr(outputKey: fixtureBytes("tr", 32))] {132 if let script, let a = try? BitcoinAddress(scriptPubKey: script, network: network) { out.append(Bytes(a.string.utf8)) }133 }134 }135 return out136}137138func scriptSeeds() -> [Bytes] {139 let key = (try? Secp256k1.publicKey(privateKey: fixtureBytes("script", 32))) ?? Bytes(repeating: 2, count: 33)140 let key2 = (try? Secp256k1.publicKey(privateKey: fixtureBytes("script2", 32))) ?? Bytes(repeating: 3, count: 33)141 let candidates: [Bytes?] = [142 try? BitcoinScript.p2pkh(publicKey: key), try? BitcoinScript.p2sh(redeemScript: [0x51]), try? BitcoinScript.p2wpkh(publicKey: key),143 try? BitcoinScript.p2wsh(witnessScript: [0x51]), try? BitcoinScript.p2tr(outputKey: fixtureBytes("tr", 32)),144 try? BitcoinScript.p2pk(publicKey: key), try? BitcoinScript.multisig(required: 1, publicKeys: [key, key2], sorted: true),145 try? BitcoinScript.nullData(Bytes("qyvora".utf8)), [0x4c, 0x02, 0xaa, 0xbb], [0x4d, 0x01, 0x00, 0xcc], [0x4e, 0x01, 0, 0, 0, 0xdd],146 ]147 return candidates.compactMap { $0 }148}149150let bitcoinTargets: [FuzzTarget] = [151 FuzzTarget(152 "bitcoin-transaction", "BitcoinTransaction parse, re-serialisation, identifiers, sighash and verifier on the parsed value",153 maxLength: 8192, seeds: transactionSeeds154 ) { input in155 for allowWitness in [true, false] {156 guard let tx = attempt(allowWitness ? "w:" : "l:", { try BitcoinTransaction(parsing: input, allowWitness: allowWitness) }) else { continue }157 let again = tx.serialized()158 fuzzCheck(again == input, "strict parser accepted a non-canonical serialisation")159 guard let reparsed = try? BitcoinTransaction(parsing: again, allowWitness: allowWitness) else { fuzzFail("serialised transaction does not parse") }160 fuzzCheck(reparsed == tx, "transaction parse/serialise round trip")161 fuzzUse(tx.txid)162 fuzzUse(tx.wtxid)163 fuzzUse(tx.vsize)164 fuzzUse(tx.outputValue)165 fuzzUse(tx.signalsRBF)166 // sighash and verification over attacker-controlled structure: any error is fine, a trap is not167 let type = BitcoinSighashType(rawValue: UInt32(input.last ?? 1))168 for i in 0..<min(tx.inputs.count, 4) {169 let scriptCode = tx.outputs.first?.scriptPubKey ?? []170 fuzzUse(try? BitcoinSighash.segwitV0(transaction: tx, inputIndex: i, scriptCode: scriptCode, value: tx.outputs.first?.value ?? 0, type: type))171 fuzzUse(try? BitcoinSighash.legacy(transaction: tx, inputIndex: i, scriptCode: scriptCode, type: type))172 for o in tx.outputs.prefix(3) {173 fuzzUse(try? BitcoinVerifier.verifyInput(transaction: tx, inputIndex: i, spentOutput: o))174 }175 }176 fuzzUse(try? BitcoinSighash.segwitV0(transaction: tx, inputIndex: tx.inputs.count, scriptCode: [], value: 0))177 if !tx.outputs.isEmpty, tx.inputs.count <= 16 {178 let spent = tx.inputs.indices.map { tx.outputs[$0 % tx.outputs.count] }179 fuzzUse(BitcoinVerifier.isValid(transaction: tx, spentOutputs: spent))180 fuzzUse(BitcoinVerifier.isValid(transaction: tx, spentOutputs: Array(spent.dropLast()), requireLowS: false))181 }182 }183 },184185 FuzzTarget("psbt", "PSBT parse (binary), re-serialisation idempotence, accessors, combine and extraction", maxLength: 8192, seeds: psbtSeeds) {186 input in187 guard let psbt = attempt({ try PSBT(parsing: input) }) else { return }188 let bytes = psbt.serialized()189 guard let again = try? PSBT(parsing: bytes) else { fuzzFail("serialised PSBT does not parse") }190 fuzzCheck(again.serialized() == bytes, "PSBT serialisation is not idempotent")191 fuzzCheck(again == psbt, "PSBT parse/serialise round trip")192 fuzzUse(psbt.fee)193 fuzzUse(psbt.isFinalized)194 fuzzUse(psbt.normalized)195 for i in 0..<min(psbt.inputs.count + 1, 6) { fuzzUse(psbt.spentOutput(inputIndex: i)) }196 attempt("x:") { try psbt.extractTransaction(verify: true) }197 attempt("u:") { try psbt.extractTransaction(verify: false) }198 if let combined = attempt("c:", { try PSBT.combine([psbt, again]) }) {199 fuzzCheck((try? PSBT(parsing: combined.serialized())) != nil, "combined PSBT does not parse")200 }201 if let text = Optional(psbt.base64), let fromText = try? PSBT(base64: text) {202 fuzzCheck(fromText == psbt, "PSBT base64 round trip")203 } else {204 fuzzFail("PSBT base64 form does not parse")205 }206 },207208 FuzzTarget(209 "psbt-text", "PSBT from base64 and hexadecimal text", maxLength: 8192, text: true, dictionary: ["cHNidP8B", "70736274ff", "="],210 seeds: { psbtSeeds().prefix(6).map { Bytes(Data($0).base64EncodedString().utf8) } + psbtSeeds().prefix(2).map { Bytes(Hex.encode($0).utf8) } }211 ) { input in212 let s = fuzzString(input)213 attempt("b64:") { try PSBT(base64: s) }214 attempt("hex:") { try PSBT(hex: s) }215 },216217 FuzzTarget(218 "descriptor", "Output descriptor and key-expression parsing, checksum, derivation of scripts and addresses",219 maxLength: 1024, text: true,220 dictionary: ["wpkh(", "wsh(", "multi(", "sortedmulti(", ")", "#", "/<0;1>/*", "/*", "h/", "'/", "[", "]", "/84h/0h/0h", ",", "xpub", "tpub", "/2147483648", "/4294967295"],221 seeds: descriptorSeeds222 ) { input in223 let s = fuzzString(input)224 attempt("key:") { try DescriptorKey(parsing: s) }225 for requireChecksum in [false, true] {226 guard let d = attempt(requireChecksum ? "c:" : "n:", { try OutputDescriptor(parsing: s, requireChecksum: requireChecksum) }) else { continue }227 let text = d.string228 guard let again = try? OutputDescriptor(parsing: text, requireChecksum: true) else { fuzzFail("printed descriptor does not parse: \(text)") }229 fuzzCheck(again == d && again.string == text, "descriptor print/parse round trip")230 fuzzUse(d.isRanged)231 fuzzUse(d.isTestNetwork)232 let index = UInt32(truncatingIfNeeded: input.count &* 2_654_435_761)233 for branch in 0..<min(d.multipathCount + 1, 4) {234 fuzzUse(try? d.singlePath(branch))235 fuzzUse(try? d.publicKeys(index: index, branch: branch))236 fuzzUse(try? d.witnessScript(index: index, branch: branch))237 if let script = try? d.scriptPubKey(index: index, branch: branch) {238 for network in BitcoinNetwork.allCases {239 if let a = try? d.address(index: index, branch: branch, network: network) {240 fuzzCheck(a.scriptPubKey == script, "descriptor address does not match its script")241 }242 }243 }244 }245 for k in d.keys { fuzzUse(k.fullPath(index: index)) }246 }247 },248249 FuzzTarget(250 "bitcoin-address", "BitcoinAddress text parsing on every network and scriptPubKey to address", maxLength: 128, text: true,251 dictionary: ["bc1q", "tb1q", "bcrt1q", "bc1p", "1", "3", "m", "n", "2"], seeds: addressSeeds252 ) { input in253 let s = fuzzString(input)254 var accepted = 0255 for network in BitcoinNetwork.allCases {256 guard let a = attempt(network.rawValue + ":", { try BitcoinAddress(s, network: network) }) else { continue }257 accepted += 1258 guard let again = try? BitcoinAddress(scriptPubKey: a.scriptPubKey, network: network) else { fuzzFail("parsed address has no address for its own script") }259 fuzzCheck(again.string == a.string && again.type == a.type, "address/script round trip")260 // Bitcoin Cash (added with the multi-chain upgrade): the legacy Base58 form is accepted, flagged and shown as261 // CashAddr, and a CashAddr typed without its prefix is completed with it262 let bitcoinCashForm = network.cashAddrPrefix != nil && (a.isLegacyFormat ? a.base58String == s : a.stringWithoutPrefix == s.lowercased())263 fuzzCheck(a.string == s || a.string == s.lowercased() || bitcoinCashForm, "address canonical form differs from the accepted text")264 }265 fuzzUse(accepted)266 for network in BitcoinNetwork.allCases {267 if let a = try? BitcoinAddress(scriptPubKey: input, network: network) {268 FuzzOutcome.note("script")269 fuzzCheck(BitcoinAddress.parse(a.string, network: network)?.scriptPubKey == input, "script/address round trip")270 }271 }272 },273274 FuzzTarget("bitcoin-script", "Script decode, classification, multisig and witness-program recognition", maxLength: 1024, seeds: scriptSeeds) { input in275 if let elements = attempt({ try BitcoinScript.decode(input) }) { fuzzUse(elements.count) }276 let cls = BitcoinScript.classify(input)277 FuzzOutcome.note(String(describing: cls.type))278 if let m = BitcoinScript.parseMultisig(input) {279 FuzzOutcome.note("multisig")280 fuzzCheck(m.required >= 1 && m.required <= m.publicKeys.count, "multisig threshold out of range")281 }282 if let w = BitcoinScript.witnessProgram(of: input) {283 fuzzCheck(w.version <= 16 && w.program.count == input.count - 2, "witness program shape")284 if let rebuilt = try? BitcoinScript.witnessProgram(version: w.version, program: w.program) {285 fuzzCheck(rebuilt == input, "witness program round trip")286 }287 }288 fuzzUse(BitcoinScript.isUnspendable(input))289 fuzzUse(BitcoinScript.push(input))290 },291292 FuzzTarget(293 "bitcoin-wif", "WIF private-key decoding on every network", maxLength: 80, text: true,294 seeds: {295 BitcoinNetwork.allCases.flatMap { n in296 [true, false].compactMap { c in (try? BitcoinWIF.encode(privateKey: fixtureBytes("wif", 32), network: n, compressed: c)).map { Bytes($0.utf8) } }297 }298 }299 ) { input in300 let s = fuzzString(input)301 for network in BitcoinNetwork.allCases {302 guard let d = attempt(network.rawValue + ":", { try BitcoinWIF.decode(s, network: network) }) else { continue }303 fuzzCheck(d.privateKey.count == 32, "WIF key length")304 fuzzCheck((try? BitcoinWIF.encode(privateKey: d.privateKey, network: network, compressed: d.compressed)) == s, "WIF round trip")305 }306 },307]308309// MARK: - Signing a PSBT that came from outside (cold signing, co-signing)310311let signingKey = fixtureBytes("psbt-sign-key", 32)312let signingMaster = try? ExtendedKey.master(seed: fixtureBytes("psbt-sign-master", 32))313314/// PSBTs that spend outputs of the fixture key and of the fixture account, unsigned and signed.315func psbtSigningSeeds() -> [Bytes] {316 var out = [Bytes]()317 guard let prev = BitcoinOutPoint(hash: fixtureBytes("sign-prev", 32), index: 0),318 let publicKey = try? Secp256k1.publicKey(privateKey: signingKey), let script = try? BitcoinScript.p2wpkh(publicKey: publicKey)319 else { return out }320 let tx = BitcoinTransaction(inputs: [.init(previousOutput: prev, sequence: 0xffff_fffd)], outputs: [.init(value: 40_000, scriptPubKey: script)])321 if var p = try? PSBT(unsignedTransaction: tx), (try? p.setWitnessUTXO(.init(value: 50_000, scriptPubKey: script), inputIndex: 0)) != nil {322 out.append(p.serialized())323 if (try? p.sign(privateKeys: [signingKey])) == 1 { out.append(p.serialized()) }324 if (try? p.finalize()) != nil { out.append(p.serialized()) }325 }326 if let master = signingMaster, let account = try? BIP84Account(master: master, network: .testnet),327 let accountScript = try? account.scriptPubKey(chain: .receive, index: 3), let accountKey = try? account.publicKey(chain: .receive, index: 3)328 {329 let spend = BitcoinTransaction(inputs: [.init(previousOutput: prev)], outputs: [.init(value: 9_000, scriptPubKey: accountScript)])330 if var p = try? PSBT(unsignedTransaction: spend), (try? p.setWitnessUTXO(.init(value: 10_000, scriptPubKey: accountScript), inputIndex: 0)) != nil {331 let derivation = PSBT.KeyDerivation(publicKey: accountKey, fingerprint: master.fingerprint, path: account.path(chain: .receive, index: 3))332 try? p.addInputDerivation(derivation, inputIndex: 0)333 try? p.addOutputDerivation(derivation, outputIndex: 0)334 out.append(p.serialized())335 }336 }337 return out338}339340let bitcoinSigningTargets: [FuzzTarget] = [341 FuzzTarget(342 "psbt-sign", "Signer, finalizer and extractor roles on a PSBT received from outside, with fixed keys and a fixed account",343 maxLength: 8192, seeds: psbtSigningSeeds344 ) { input in345 guard let parsed = attempt({ try PSBT(parsing: input) }) else { return }346 let prefinalized = parsed.inputs.contains { $0.isFinalized }347 var psbt = parsed348 let options = PSBT.SigningOptions(allowedSighashTypes: [.all, .none, .single, .allAnyoneCanPay], requireNonWitnessUTXO: input.count % 2 == 0)349 if let added = attempt("sign:", { try psbt.sign(privateKeys: [signingKey], options: options) }) {350 fuzzCheck(added >= 0 && added <= psbt.inputs.count, "signature count out of range")351 }352 for i in 0..<min(psbt.inputs.count + 1, 5) { attempt("one:") { try psbt.sign(inputIndex: i, privateKey: signingKey) } }353 if let master = signingMaster, let account = try? BIP84Account(master: master, network: .testnet) {354 attempt("account:") { try account.sign(psbt: &psbt, searchLimit: 8) }355 }356 guard let afterSigning = try? PSBT(parsing: psbt.serialized()) else { fuzzFail("PSBT no longer parses after signing") }357 fuzzCheck(afterSigning == psbt, "signed PSBT round trip")358 fuzzCheck(afterSigning.unsignedTransaction == parsed.unsignedTransaction, "signing changed the unsigned transaction")359 var finalized = psbt360 if attempt("finalize:", { try finalized.finalize() }) != nil {361 fuzzCheck(finalized.isFinalized || finalized.inputs.isEmpty, "finalize() returned with unfinalized inputs")362 if !prefinalized, !finalized.inputs.isEmpty {363 // every signature was checked by the finalizer: extraction with verification cannot fail364 guard let tx = try? finalized.extractTransaction(verify: true) else { fuzzFail("finalized PSBT does not extract") }365 fuzzCheck(tx.inputs.count == parsed.unsignedTransaction.inputs.count && tx.outputs == parsed.unsignedTransaction.outputs, "extracted transaction differs from the unsigned one")366 } else {367 attempt("extract:") { try finalized.extractTransaction(verify: true) }368 }369 }370 for i in 0..<min(psbt.inputs.count + 1, 3) { attempt("fin1:") { try psbt.finalizeInput(i) } }371 }372]373