SPB Git

Repository Public

AuditRegressionTests.swift 7.2 KB 128 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Tests/QyvoraBitcoinTests/AuditRegressionTests.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 Foundation42import Testing43import QyvoraMath44import QyvoraCore45@testable import QyvoraBitcoin4647/// Regression tests of the security audit (findings QYV-SVC-003, QYV-SVC-004 and QYV-SVC-015): sums over amounts48/// that come from outside the wallet must never overflow.49@Suite struct BitcoinAuditRegressionTests {50    static let script = try! BitcoinScript.p2wpkh(publicKeyHash: Bytes(repeating: 0x11, count: 20))51    static let destination = try! BitcoinScript.p2wpkh(publicKeyHash: Bytes(repeating: 0x22, count: 20))5253    static func outPoint(_ n: Int) -> BitcoinOutPoint {54        var hash = Bytes(repeating: 0, count: 32)55        hash[0] = UInt8(n & 0xff)56        hash[1] = UInt8((n >> 8) & 0xff)57        hash[2] = UInt8((n >> 16) & 0xff)58        return BitcoinOutPoint(hash: hash, index: 0)!59    }6061    /// QYV-SVC-004. 9 000 inputs each claiming 21 million bitcoin: the sum exceeds 2^64 and `fee` used to trap.62    @Test func psbtFeeWithThousandsOfMaximalInputsIsNilNotATrap() throws {63        let count = 9_00064        let tx = BitcoinTransaction(inputs: (0..<count).map { BitcoinTransaction.Input(previousOutput: Self.outPoint($0)) },65                                    outputs: [BitcoinTransaction.Output(value: 1_000, scriptPubKey: Self.destination)])66        var psbt = try PSBT(unsignedTransaction: tx)67        for i in 0..<count {68            try psbt.setWitnessUTXO(BitcoinTransaction.Output(value: BitcoinLimits.maxMoney, scriptPubKey: Self.script), inputIndex: i)69        }70        #expect(psbt.fee == nil)7172        // the same through the parser, as an imported PSBT would arrive73        let parsed = try PSBT(parsing: psbt.serialized())74        #expect(parsed.inputs.count == count)75        #expect(parsed.fee == nil)7677        // a total inside the monetary range is still reported78        var small = try PSBT(unsignedTransaction: BitcoinTransaction(79            inputs: [BitcoinTransaction.Input(previousOutput: Self.outPoint(1)), BitcoinTransaction.Input(previousOutput: Self.outPoint(2))],80            outputs: [BitcoinTransaction.Output(value: 1_000, scriptPubKey: Self.destination)]))81        try small.setWitnessUTXO(BitcoinTransaction.Output(value: 700, scriptPubKey: Self.script), inputIndex: 0)82        try small.setWitnessUTXO(BitcoinTransaction.Output(value: 800, scriptPubKey: Self.script), inputIndex: 1)83        #expect(small.fee == 500)84        // two inputs of 21 million bitcoin each: individually in range, together not85        try small.setWitnessUTXO(BitcoinTransaction.Output(value: BitcoinLimits.maxMoney, scriptPubKey: Self.script), inputIndex: 0)86        try small.setWitnessUTXO(BitcoinTransaction.Output(value: BitcoinLimits.maxMoney, scriptPubKey: Self.script), inputIndex: 1)87        #expect(small.fee == nil)88    }8990    /// QYV-SVC-003. Candidate lists whose total exceeds the money supply used to overflow the input sums of the builder91    /// (UInt64 in "send max", Int64 in Branch and Bound). The request is now refused up front.92    @Test func builderRefusesCandidatesWhoseTotalExceedsTheMoneySupply() {93        func utxos(_ count: Int, value: UInt64) -> [BitcoinUTXO] {94            (0..<count).map { BitcoinUTXO(outPoint: Self.outPoint($0), value: value, scriptPubKey: Self.script, confirmations: 6) }95        }96        let rate = FeeRate(satPerVByte: 2)97        // 9 000 × 2.1e15 > 2^64 (UInt64 overflow), 4 500 × 2.1e15 > 2^63 (Int64 overflow)98        for count in [9_000, 4_500, 2] {99            let payment = BitcoinSpendRequest(recipients: [BitcoinTransaction.Output(value: 50_000, scriptPubKey: Self.destination)],100                                              utxos: utxos(count, value: BitcoinLimits.maxMoney), feeRate: rate, changeScript: Self.script)101            #expect(throws: BitcoinBuildError.invalidAmount) { _ = try BitcoinTransactionBuilder.build(payment) }102            let sendMax = BitcoinSpendRequest(recipients: [], utxos: utxos(count, value: BitcoinLimits.maxMoney), feeRate: rate, changeScript: nil,103                                              sendMaxScript: Self.destination)104            #expect(throws: BitcoinBuildError.invalidAmount) { _ = try BitcoinTransactionBuilder.build(sendMax) }105        }106        // a single output above the money supply is refused as well107        let single = BitcoinSpendRequest(recipients: [BitcoinTransaction.Output(value: 50_000, scriptPubKey: Self.destination)],108                                         utxos: utxos(1, value: BitcoinLimits.maxMoney + 1), feeRate: rate, changeScript: Self.script)109        #expect(throws: BitcoinBuildError.invalidAmount) { _ = try BitcoinTransactionBuilder.build(single) }110        // exactly the money supply in one candidate is still a valid request111        let whole = BitcoinSpendRequest(recipients: [BitcoinTransaction.Output(value: 50_000, scriptPubKey: Self.destination)],112                                        utxos: utxos(1, value: BitcoinLimits.maxMoney), feeRate: rate, changeScript: Self.script)113        #expect((try? BitcoinTransactionBuilder.build(whole)) != nil)114    }115116    /// QYV-SVC-015. Oversized WIF text is refused before the quadratic Base58 decoding.117    @Test func oversizedWIFTextIsRefusedWithoutDecoding() throws {118        let key = Bytes(repeating: 0x42, count: 32)119        let wif = try BitcoinWIF.encode(privateKey: key, network: .signet)120        #expect(try BitcoinWIF.decode(wif, network: .signet).privateKey == key)121        let clock = ContinuousClock()122        let elapsed = clock.measure {123            #expect(throws: BitcoinWIF.Error.invalidEncoding) { _ = try BitcoinWIF.decode(String(repeating: "1", count: 2_000_000), network: .signet) }124        }125        #expect(elapsed < .seconds(2))126    }127}128
Files main
Menu

Theme