SPB Git

Repository Public

FindingsPSBTAmountTests.swift 21.4 KB 368 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Tests/QyvoraWalletTests/FindingsPSBTAmountTests.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 QyvoraCore45import QyvoraBitcoin46import QyvoraNetworking47@testable import QyvoraWallet4849/// Regression tests of QYV-SVC-008 (BIP-143 fee attack on a cold signer): input amounts that rest on the PSBT's50/// word alone are reported, need an explicit confirmation, and are never signed on unaudited mainnet.51struct PSBTAmountVerificationTests {52    /// A cold full wallet (no network, no snapshot) and what the tests need about its account.53    struct Cold {54        let h: Harness55        let account: BIP84Account56        let fingerprint: Bytes57    }5859    static func cold(network: BitcoinNetwork = .signet) async throws -> Cold {60        let backend = FakeBackend()61        backend.forbidAllRequests = true62        let h = try await Harness.make(backend: backend)63        try await h.service.setColdMode(true)64        try await h.service.importWallet(words: Harness.abandon, password: Harness.password)65        let account = try BIP84Account(master: try ExtendedKey.master(seed: try BIP39.seed(mnemonic: Harness.abandon)), network: network)66        return Cold(h: h, account: account, fingerprint: try #require(account.masterFingerprint))67    }6869    /// A real transaction paying `value` to receive address `index` of the account; `salt` makes it distinct.70    static func funding(_ account: BIP84Account, index: UInt32, value: UInt64, salt: UInt8) throws -> BitcoinTransaction {71        let source = try #require(BitcoinOutPoint(txid: String(repeating: String(format: "%02x", salt), count: 32), vout: 0))72        return BitcoinTransaction(inputs: [.init(previousOutput: source, scriptSig: [0x51])],73                                  outputs: [.init(value: value, scriptPubKey: try account.scriptPubKey(chain: .receive, index: index))])74    }7576    /// The transaction of the attack: two coins of the wallet (60 000 and 50 000 sat), 100 000 sat paid, 500 sat of77    /// change… and therefore 9 500 sat of fee, or much more when a coin is really larger than declared.78    struct Scenario {79        let a: BitcoinTransaction80        let b: BitcoinTransaction81        let tx: BitcoinTransaction8283        init(_ account: BIP84Account, network: BitcoinNetwork = .signet, realB: UInt64 = 50_000) throws {84            a = try PSBTAmountVerificationTests.funding(account, index: 0, value: 60_000, salt: 0xa1)85            b = try PSBTAmountVerificationTests.funding(account, index: 1, value: realB, salt: 0xb2)86            let external = try BitcoinAddress(scriptPubKey: try BitcoinScript.p2wpkh(publicKeyHash: Bytes(repeating: 0x77, count: 20)), network: network)87            tx = BitcoinTransaction(inputs: [.init(previousOutput: BitcoinOutPoint(txid: a.txid, vout: 0)!, sequence: BitcoinTransaction.Input.sequenceRBF),88                                             .init(previousOutput: BitcoinOutPoint(txid: b.txid, vout: 0)!, sequence: BitcoinTransaction.Input.sequenceRBF)],89                                    outputs: [.init(value: 100_000, scriptPubKey: external.scriptPubKey),90                                              .init(value: 500, scriptPubKey: try account.scriptPubKey(chain: .change, index: 0))])91        }92    }9394    @Test func amountsStatedOnlyByThePSBTAreReportedAndNeedAnExplicitConfirmation() async throws {95        let c = try await Self.cold()96        defer { c.h.cleanup() }97        let s = try Scenario(c.account)98        var psbt = try PSBT(unsignedTransaction: s.tx)99        try psbt.setWitnessUTXO(s.a.outputs[0], inputIndex: 0)100        try psbt.setWitnessUTXO(s.b.outputs[0], inputIndex: 1)101102        let review = try await c.h.service.reviewPSBT([psbt.base64])103        #expect(review.fee == 9_500 && !review.inputAmountsVerified)104        #expect(review.warnings.contains { $0.contains("fee is not verified") && $0.contains("2 input amount(s)") })105        #expect(review.summary.contains { $0.hasPrefix("Fee:") && $0.hasSuffix("NOT VERIFIED") })106        // refused by default, before any key is read107        guard case .invalidPSBT(let why)? = await walletError({ try await c.h.service.signPSBT([psbt.base64]) }) else {108            Issue.record("unverified amounts must not be signed by default")109            return110        }111        #expect(why.contains("cannot be verified") && why.contains("explicit confirmation"))112        // with the explicit confirmation, on a test network, it is signed113        let signed = try await c.h.service.signPSBT([psbt.base64], acceptUnverifiedAmounts: true)114        #expect(signed.signaturesAdded == 2 && !signed.review.inputAmountsVerified)115    }116117    /// The attack itself, in two rounds: the second coin is really worth 5 000 000 sat. Each round declares one coin118    /// at its real amount (its signature is valid) and the other one low, so that the fee looks like 9 500 sat.119    @Test func theTwoRoundFeeAttackYieldsNoSignatureWithoutConfirmationAndIsCaughtWithPreviousTransactions() async throws {120        let c = try await Self.cold()121        defer { c.h.cleanup() }122        let s = try Scenario(c.account, realB: 5_000_000)123        let lowB = BitcoinTransaction.Output(value: 50_000, scriptPubKey: s.b.outputs[0].scriptPubKey)124        let lowA = BitcoinTransaction.Output(value: 100, scriptPubKey: s.a.outputs[0].scriptPubKey)125126        var round1 = try PSBT(unsignedTransaction: s.tx)127        try round1.setWitnessUTXO(s.a.outputs[0], inputIndex: 0)128        try round1.setWitnessUTXO(lowB, inputIndex: 1)129        var round2 = try PSBT(unsignedTransaction: s.tx)130        try round2.setWitnessUTXO(lowA, inputIndex: 0)131        try round2.setWitnessUTXO(s.b.outputs[0], inputIndex: 1)132        for round in [round1, round2] {133            let review = try await c.h.service.reviewPSBT([round.base64])134            #expect(!review.inputAmountsVerified && review.warnings.contains { $0.contains("fee is not verified") })135            guard case .invalidPSBT? = await walletError({ try await c.h.service.signPSBT([round.base64]) }) else {136                Issue.record("a round of the attack was signed without confirmation")137                return138            }139        }140141        // the same lie cannot be told with the previous transactions attached: the parser and the signer compare them142        var honest = try PSBT(unsignedTransaction: s.tx)143        try honest.setNonWitnessUTXO(s.a, inputIndex: 0)144        try honest.setNonWitnessUTXO(s.b, inputIndex: 1)145        #expect(throws: PSBTError.self) { try honest.setWitnessUTXO(lowB, inputIndex: 1) }146        let review = try await c.h.service.reviewPSBT([honest.base64])147        #expect(review.inputAmountsVerified && review.fee == 60_000 + 5_000_000 - 100_500)148        // and the real fee is now what the fee ceiling sees: 4 959 500 sat is beyond what the wallet signs149        guard case .invalidPSBT(let why)? = await walletError({ try await c.h.service.signPSBT([honest.base64]) }) else {150            Issue.record("the real fee must be refused")151            return152        }153        #expect(why.contains("beyond"))154        // a previous transaction that does not hash to the outpoint is not a PSBT the wallet reads155        var forged = s.b156        forged.outputs[0].value = 50_000157        #expect(throws: PSBTError.self) { try honest.setNonWitnessUTXO(forged, inputIndex: 1) }158    }159160    @Test func previousTransactionsOrASingleInputMakeTheAmountsVerified() async throws {161        let c = try await Self.cold()162        defer { c.h.cleanup() }163        let s = try Scenario(c.account)164        // every input carries its previous transaction165        var full = try PSBT(unsignedTransaction: s.tx)166        try full.setNonWitnessUTXO(s.a, inputIndex: 0)167        try full.setNonWitnessUTXO(s.b, inputIndex: 1)168        let review = try await c.h.service.reviewPSBT([full.base64])169        #expect(review.inputAmountsVerified && review.fee == 9_500 && !review.warnings.contains { $0.contains("not verified") })170        #expect(try await c.h.service.signPSBT([full.base64]).signaturesAdded == 2)171        // one of the two only: not verified172        var half = try PSBT(unsignedTransaction: s.tx)173        try half.setNonWitnessUTXO(s.a, inputIndex: 0)174        try half.setWitnessUTXO(s.b.outputs[0], inputIndex: 1)175        let halfReview = try await c.h.service.reviewPSBT([half.base64])176        #expect(!halfReview.inputAmountsVerified && halfReview.warnings.contains { $0.contains("1 input amount(s)") })177        // a single input: its SegWit signature commits to its amount, a false amount gives an invalid signature178        let single = BitcoinTransaction(inputs: [s.tx.inputs[0]], outputs: [.init(value: 59_000, scriptPubKey: s.tx.outputs[0].scriptPubKey)])179        var one = try PSBT(unsignedTransaction: single)180        try one.setWitnessUTXO(s.a.outputs[0], inputIndex: 0)181        let oneReview = try await c.h.service.reviewPSBT([one.base64])182        #expect(oneReview.inputAmountsVerified && oneReview.warnings.isEmpty)183        #expect(try await c.h.service.signPSBT([one.base64]).signaturesAdded == 1)184    }185186    /// An online wallet knows its coins: a witness-only PSBT over them is verified against what it read itself, and a187    /// PSBT that states another amount for one of them is refused.188    @Test func coinsTheWalletReadItselfAreVerifiedAgainstItsSnapshot() async throws {189        let h = try await Harness.abandonWallet()190        defer { h.cleanup() }191        let a0 = try await h.receive(0), a1 = try await h.receive(1)192        h.backend.fund(a0, 80_000, height: 100)193        h.backend.fund(a1, 40_000, height: 101)194        _ = try await h.service.syncBitcoin()195        let plan = try await h.service.prepareBitcoinSend(to: externalAddress(), amount: 100_000, feeRate: FeeRate(satPerVByte: 3))196        #expect(plan.inputs.count == 2)197        let account = try await h.service.bitcoinAccount()198        let psbt = try account.psbt(for: plan.plan)199        #expect(psbt.inputs.allSatisfy { $0.nonWitnessUTXO == nil })200        #expect(try await h.service.reviewPSBT([psbt.base64]).inputAmountsVerified)201        var lying = psbt202        lying.inputs[1].witnessUTXO?.value += 1_000203        #expect(try await h.service.reviewPSBT([lying.base64]).inputAmountsVerified == false)204        guard case .invalidPSBT? = await walletError({ try await h.service.signPSBT([lying.base64], acceptUnverifiedAmounts: true) }) else {205            Issue.record("an amount that contradicts the wallet's own reading must be refused")206            return207        }208        #expect(try await h.service.signPSBT([psbt.base64]).signaturesAdded == 2)209    }210211    /// Export side: the previous transactions are attached when the endpoint serves them, and only when they hash to212    /// the outpoint; a failing or lying endpoint leaves the witness UTXO alone.213    @Test func exportAttachesPreviousTransactionsThatHashToTheOutpoint() async throws {214        let h = try await Harness.abandonWallet()215        defer { h.cleanup() }216        let a0 = try await h.receive(0), a1 = try await h.receive(1)217        let first = h.backend.fundReal(a0, 80_000, height: 100)218        let second = h.backend.fundReal(a1, 40_000, height: 101)219        _ = try await h.service.syncBitcoin()220        let plan = try await h.service.prepareBitcoinSend(to: externalAddress(), amount: 100_000, feeRate: FeeRate(satPerVByte: 3))221        var exported = try PSBT(base64: try await h.service.exportPSBT(plan).text)222        #expect(exported.inputs.count == 2 && exported.inputs.allSatisfy { $0.nonWitnessUTXO != nil })223        // the endpoint answers the first request with the other transaction, and fails the second one224        h.backend.rawTransactions[first] = h.backend.rawTransactions[second]225        h.backend.rawTransactions[second] = nil226        exported = try PSBT(base64: try await h.service.exportPSBT(plan).text)227        #expect(exported.inputs.allSatisfy { $0.nonWitnessUTXO == nil && $0.witnessUTXO != nil })228        // cold mode: no request at all229        try await h.service.setColdMode(true)230        let before = await h.service.networkRequestCount()231        exported = try PSBT(base64: try await h.service.exportPSBT(plan).text)232        #expect(exported.inputs.allSatisfy { $0.nonWitnessUTXO == nil })233        #expect(await h.service.networkRequestCount() == before)234    }235}236237/// On mainnet with an unaudited engine no confirmation is offered: nothing can bound a hidden fee.238extension MainnetPolicyTests {239    @Test func unverifiedAmountsAreNeverSignedOnUnauditedMainnet() async throws {240        Self.reset()241        defer { Self.reset() }242        let h = try await Self.mainnetWallet()243        defer { h.cleanup() }244        try await h.service.setColdMode(true)245        let account = try BIP84Account(master: try ExtendedKey.master(seed: try BIP39.seed(mnemonic: Harness.abandon)), network: .mainnet)246        let s = try PSBTAmountVerificationTests.Scenario(account, network: .mainnet)247        var psbt = try PSBT(unsignedTransaction: s.tx)248        try psbt.setWitnessUTXO(s.a.outputs[0], inputIndex: 0)249        try psbt.setWitnessUTXO(s.b.outputs[0], inputIndex: 1)250        #expect(try await h.service.reviewPSBT([psbt.base64]).inputAmountsVerified == false)251        for accept in [false, true] {252            guard case .invalidPSBT(let why)? = await walletError({ try await h.service.signPSBT([psbt.base64], acceptUnverifiedAmounts: accept) }) else {253                Issue.record("unverified amounts were signed on unaudited mainnet")254                return255            }256            #expect(why.contains("On mainnet this build does not sign"))257        }258        // with the previous transactions the same payment is signed259        var full = try PSBT(unsignedTransaction: s.tx)260        try full.setNonWitnessUTXO(s.a, inputIndex: 0)261        try full.setNonWitnessUTXO(s.b, inputIndex: 1)262        #expect(try await h.service.signPSBT([full.base64]).signaturesAdded == 2)263    }264}265266/// Regression tests of QYV-SVC-011: the account public keys of the unauthenticated profile file are checked against267/// the vault at every unlock.268struct AccountBindingTests {269    /// An attacker's account: the BIP-84 keys of another phrase.270    static func foreign() throws -> WalletService.PublicData {271        let words = ["legal", "winner", "thank", "year", "wave", "sausage", "worth", "useful", "legal", "winner", "thank", "yellow"]272        return try WalletService.publicData(master: try ExtendedKey.master(seed: try BIP39.seed(mnemonic: words)))273    }274275    /// Rewrites the account data of the profile file, as someone with write access to the container would.276    static func tamper(_ h: Harness, with data: WalletService.PublicData) throws {277        let url = h.directory.appendingPathComponent(WalletService.profileFile)278        var json = try #require(JSONSerialization.jsonObject(with: Data(contentsOf: url)) as? [String: Any])279        let accounts = try #require(JSONSerialization.jsonObject(with: JSONEncoder().encode(data.accounts)) as? [String: Any])280        json["bitcoinAccounts"] = accounts281        json["ethereumAddress"] = try #require(JSONSerialization.jsonObject(with: JSONEncoder().encode([data.ethereum])) as? [Any])[0]282        try JSONSerialization.data(withJSONObject: json).write(to: url)283    }284285    @Test func aReplacedAccountKeyIsRestoredFromTheVaultAtUnlock() async throws {286        let h = try await Harness.abandonWallet()287        defer { h.cleanup() }288        #expect(try await h.vault.report().recordCounts["watchOnlyAccount"] == 1)289        let genuine = try await h.receive(0)290        #expect(genuine == Harness.abandonFirstTestAddress)291        let attacker = try Self.foreign()292        try Self.tamper(h, with: attacker)293294        // a new session over the modified file: before the unlock the profile is what the file says…295        let reopened = try await Harness.make(clock: h.clock, directory: h.directory, configure: false)296        #expect(try await reopened.receive(0) != genuine)297        #expect(await reopened.service.currentProfile().ethereumAddress == attacker.ethereum)298        #expect(await reopened.service.accountBindingRepairCount() == 0)299        // …and the unlock puts the wallet's own keys back, in memory and in the file300        try await reopened.service.unlock(password: Harness.password)301        #expect(try await reopened.receive(0) == genuine)302        #expect(await reopened.service.currentProfile().ethereumAddress?.checksummed == Harness.abandonEthereumAddress)303        #expect(await reopened.service.accountBindingRepairCount() == 1)304        let third = try await Harness.make(clock: h.clock, directory: h.directory, configure: false)305        #expect(try await third.receive(0) == genuine)306        // an untouched profile is not "repaired"307        try await third.service.unlock(password: Harness.password)308        #expect(await third.service.accountBindingRepairCount() == 0)309    }310311    @Test func everyUnlockMethodChecksTheBinding() async throws {312        let h = try await Harness.abandonWallet()313        defer { h.cleanup() }314        try await h.service.enablePIN("481516")315        try await h.service.enableBiometrics(useSecureEnclave: false)316        let attacker = try Self.foreign()317        for n in 0..<3 {318            func unlock() async throws {319                switch n {320                case 0: try await h.service.unlock(pin: "481516")321                case 1: try await h.service.unlockWithBiometrics(prompt: "t")322                default: try await h.service.unlock(password: Harness.password)323                }324            }325            await h.service.lock()326            // the running service is given the attacker's account, as a modified file would on the next launch327            await h.service.replaceAccountDataForTesting(attacker)328            #expect(try await h.receive(0) != Harness.abandonFirstTestAddress)329            try await unlock()330            #expect(try await h.receive(0) == Harness.abandonFirstTestAddress)331            #expect(await h.service.accountBindingRepairCount() == n + 1)332        }333    }334335    /// A vault created before the binding existed has no record: the first unlock derives the keys from the recovery336    /// phrase, repairs a profile that does not match, and writes the record.337    @Test func aVaultWithoutBindingGetsOneFromItsPhrase() async throws {338        let h = try await Harness.abandonWallet()339        defer { h.cleanup() }340        let record = try #require(try await h.service.accountBindingRecord())341        try await h.vault.deleteRecord(record.id)342        #expect(try await h.vault.report().recordCounts["watchOnlyAccount"] == nil)343        try Self.tamper(h, with: try Self.foreign())344        let reopened = try await Harness.make(clock: h.clock, directory: h.directory, configure: false)345        try await reopened.service.unlock(password: Harness.password)346        #expect(try await reopened.receive(0) == Harness.abandonFirstTestAddress)347        #expect(await reopened.service.accountBindingRepairCount() == 1)348        #expect(try await reopened.vault.report().recordCounts["watchOnlyAccount"] == 1)349        #expect(try await reopened.service.accountBindingRecord()?.data?.ethereum.checksummed == Harness.abandonEthereumAddress)350    }351352    @Test func aRestoredBackupCarriesTheBindingOfItsPhrase() async throws {353        let h = try await Harness.abandonWallet()354        defer { h.cleanup() }355        let directory = FileManager.default.temporaryDirectory.appendingPathComponent("qy-bind-\(UUID().uuidString)")356        try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)357        defer { try? FileManager.default.removeItem(at: directory) }358        let url = directory.appendingPathComponent("wallet.qyvora")359        _ = try await h.service.createBackup(to: url, password: "backup river stone 71")360        let target = try await Harness.make()361        defer { target.cleanup() }362        try await target.service.restoreBackup(from: url, backupPassword: "backup river stone 71", newPassword: "new device granite lamp 5")363        #expect(try await target.vault.report().recordCounts["watchOnlyAccount"] == 1)364        #expect(try await target.service.accountBindingRecord()?.data == (try await h.service.accountBindingRecord()?.data))365        #expect(try await target.receive(0) == Harness.abandonFirstTestAddress)366    }367}368
Files main
Menu

Theme