Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Tests/QyvoraBitcoinTests/UTXOCoinsAuditRegressionTests.swift8// Module : Tests9// Repository : https://git.spboucher.ai/qyvora10// Project Website : Not specified11// Created : 2026-12-0512// 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 Testing43import QyvoraMath44import QyvoraSymmetric45import QyvoraCore46@testable import QyvoraBitcoin4748/// Regression tests of the multi-chain security audit, UTXO coins (finding QYV-SVC-064): the amounts a PSBT states49/// are authenticated before a fee is reported or anything is signed on the networks whose wallet inputs are not SegWit.50@Suite struct UTXOCoinsAuditRegressionTests {51 struct Fixture {52 let account: UTXOAccount53 let plan: BitcoinTransactionPlan54 let previous: [String: BitcoinTransaction]55 let psbt: PSBT56 }5758 /// An account with two coins (each from its own transaction) and a payment spending both.59 static func fixture(_ network: BitcoinNetwork, purpose: UTXOAccountPurpose? = nil) throws -> Fixture {60 let account = try UTXOAccount(master: try abandonMaster(), network: network, purpose: purpose)61 var previous = [String: BitcoinTransaction]()62 var utxos = [BitcoinUTXO]()63 for (index, value) in [(UInt32(0), UInt64(700_000_000)), (3, 900_000_000)] {64 let script = try account.scriptPubKey(chain: .receive, index: index)65 let funding = BitcoinTransaction(version: 1, inputs: [.init(previousOutput: BitcoinOutPoint(hash: Bytes(repeating: UInt8(index + 1), count: 32), index: 0)!, scriptSig: [0x51])],66 outputs: [.init(value: 5, scriptPubKey: [0x51]), .init(value: value, scriptPubKey: script)])67 previous[funding.txid] = funding68 utxos.append(BitcoinUTXO(outPoint: BitcoinOutPoint(hash: funding.txidBytes, index: 1)!, value: value, scriptPubKey: script, confirmations: 6,69 derivation: .init(chain: 0, index: index)))70 }71 var request = BitcoinSpendRequest(network: network, recipients: [.init(value: 1_500_000_000, scriptPubKey: try BitcoinScript.p2pkh(publicKeyHash: Bytes(repeating: 0x42, count: 20)))],72 utxos: utxos, feeRate: .minimum(for: network), changeScript: try account.scriptPubKey(chain: .change, index: 0))73 request.seed = 1174 let plan = try BitcoinTransactionBuilder.build(request)75 #expect(plan.inputs.count == 2)76 return Fixture(account: account, plan: plan, previous: previous, psbt: try account.psbt(for: plan, previousTransactions: previous))77 }7879 /// QYV-SVC-064 (a). `PSBT.inputs` is a public property: a previous transaction put there without the setter was80 /// taken at its word by `spentOutput` and `fee`. It now counts only when it hashes to the outpoint's identifier.81 @Test func aPreviousTransactionSetThroughThePropertyIsAuthenticated() throws {82 for network in [BitcoinNetwork.dogecoin, .bitcoinCash, .litecoin] {83 let f = try Self.fixture(network, purpose: .bip44)84 var psbt = try PSBT(parsing: f.psbt.serialized())85 psbt.prepare(for: network)86 #expect(psbt.fee == f.plan.fee)87 let outPoint = f.plan.inputs[0].outPoint88 var fake = try #require(f.previous[outPoint.txid])89 fake.outputs[1].value = 1_000_000 // the "indexer" understates the coin: the difference would become fee90 psbt.inputs[0].nonWitnessUTXO = fake91 #expect(psbt.spentOutput(inputIndex: 0) == nil && psbt.fee == nil, "\(network)")92 let before = psbt93 #expect(throws: PSBTError.nonWitnessUTXOMismatch) { try f.account.sign(psbt: &psbt) }94 #expect(psbt == before)95 // an index beyond the transaction's inputs is no longer read96 psbt.inputs.append(PSBT.Input())97 psbt.inputs[2].nonWitnessUTXO = fake98 #expect(psbt.spentOutput(inputIndex: 2) == nil && psbt.spentOutput(inputIndex: 99) == nil)99 }100 }101102 /// QYV-SVC-064 (b). The two-round fee burn: a PSBT shows one input of the wallet with its previous transaction and103 /// leaves the other without any amount; the account signed the first (the original digest commits to no amount),104 /// then the second in another round, and the two signatures together spend both coins for a fee nobody saw.105 /// On Dogecoin, Bitcoin Cash and BIP-44 accounts the account now signs only when every amount is authenticated.106 @Test func nothingIsSignedWhenTheFeeIsNotAuthenticated() throws {107 for network in [BitcoinNetwork.dogecoin, .dogecoinTestnet, .bitcoinCash, .bitcoinCashTestnet, .litecoin] {108 let f = try Self.fixture(network, purpose: .bip44)109 for hidden in 0..<2 {110 // no record at all for one input111 var round = f.psbt112 round.inputs[hidden].nonWitnessUTXO = nil113 var parsed = try PSBT(parsing: round.serialized())114 parsed.prepare(for: network)115 #expect(parsed.fee == nil)116 let before = parsed117 #expect(throws: PSBTError.nonWitnessUTXORequired) { try f.account.sign(psbt: &parsed) }118 #expect(parsed == before && parsed.inputs.allSatisfy { $0.partialSignatures.isEmpty }, "\(network): a signature was made")119120 // a witness-UTXO record stating a tenth of the coin121 round.inputs[hidden].witnessUTXO = BitcoinTransaction.Output(value: f.plan.inputs[hidden].value / 10, scriptPubKey: f.plan.inputs[hidden].scriptPubKey)122 var lying = try PSBT(parsing: round.serialized())123 lying.prepare(for: network)124 if network.sighashScheme != .bip143 { #expect(lying.fee == nil, "\(network): a fee was computed from an unauthenticated amount") }125 #expect(throws: PSBTError.nonWitnessUTXORequired) { try f.account.sign(psbt: &lying) }126 #expect(lying.inputs.allSatisfy { $0.partialSignatures.isEmpty })127 }128 // the complete PSBT is signed, and the fee shown is the fee paid129 var whole = try PSBT(parsing: f.psbt.serialized())130 #expect(try f.account.sign(psbt: &whole) == 2 && whole.fee == f.plan.fee)131 try whole.finalize()132 let tx = try whole.extractTransaction()133 #expect(tx == (try f.account.sign(plan: f.plan, previousTransactions: f.previous)))134 #expect(f.plan.inputs.reduce(UInt64(0)) { $0 + $1.value } - tx.outputs.reduce(UInt64(0)) { $0 + $1.value } == f.plan.fee)135 }136 // a SegWit account keeps the BIP-174 behaviour: a witness UTXO is enough, the signature commits to it137 let l = try Self.fixture(.litecoin)138 var segwit = try PSBT(parsing: try l.account.psbt(for: l.plan).serialized())139 #expect(segwit.inputs.allSatisfy { $0.nonWitnessUTXO == nil && $0.witnessUTXO != nil })140 #expect(try l.account.sign(psbt: &segwit) == 2 && segwit.fee == l.plan.fee)141 }142}143