Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Tests/QyvoraWalletTests/FindingsFeeLimitTests.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 QyvoraEthereum47import QyvoraNetworking48@testable import QyvoraWallet4950/// Regression tests of QYV-SVC-009: the per-transaction ceilings of an unaudited mainnet build bound the fee too,51/// at prepare and at sign, on both chains. They live in the serialized mainnet suite because `MainnetPolicy` is52/// process-wide.53extension MainnetPolicyTests {54 @Test func feeCeilingConstantsAreTheDocumentedOnes() {55 #expect(MainnetPolicy.limits.bitcoinFeeSatoshisPerTransaction == 20_000)56 #expect(MainnetPolicy.limits.bitcoinFeeRateSatPerVByte == 200)57 #expect(BaseUnits.format(MainnetPolicy.limits.etherFeeWeiPerTransaction, decimals: 18) == "0.01")58 // the fee ceilings are below the value ceilings they complete59 #expect(MainnetPolicy.limits.bitcoinFeeSatoshisPerTransaction < MainnetPolicy.limits.bitcoinSatoshisPerTransaction)60 #expect(MainnetPolicy.limits.etherFeeWeiPerTransaction < MainnetPolicy.limits.etherWeiPerTransaction)61 }6263 @Test func bitcoinFeeCeilingsAreEnforcedAtPrepareAndAtSign() async throws {64 Self.reset()65 defer { Self.reset() }66 let h = try await Self.mainnetWallet()67 defer { h.cleanup() }68 h.backend.fund(Self.mainnetAddress, 500_000, height: 100)69 let snapshot = try await h.service.syncBitcoin()70 let rateLimit = WalletError.exceedsUnauditedLimit(limit: "a fee rate of 200 sat/vB")71 let feeLimit = WalletError.exceedsUnauditedLimit(limit: "a fee of 20000 sat per transaction")7273 // the ceiling of the service follows the policy, and the tiers offered never exceed it74 #expect(WalletService.bitcoinFeeRateCeiling(.mainnet) == 200)75 #expect(WalletService.bitcoinFeeRateCeiling(.signet) == WalletService.bitcoinMaximumFeeRate)76 h.backend.feeEstimates = "{\"1\":900.0,\"6\":450.0,\"144\":300.0}"77 let options = try await h.service.bitcoinFeeOptions()78 #expect(options.fast.rate == FeeRate(satPerVByte: 200) && options.slow.rate == FeeRate(satPerVByte: 200))7980 // prepare: one input and two outputs (about 141 vB) at 100 sat/vB stay below 20 000 sat81 let atCeiling = try await h.service.prepareBitcoinSend(to: Self.external(), amount: 100_000, feeRate: FeeRate(satPerVByte: 100))82 #expect(atCeiling.fee <= 20_000 && atCeiling.fee > 10_000)83 // the same payment at 201 sat/vB: refused although the general caps (1 000 sat/vB, 1 000 000 sat) allow it84 #expect(await walletError { try await h.service.prepareBitcoinSend(to: Self.external(), amount: 100_000, feeRate: FeeRate(satPerVByte: 201)) } == feeLimit)85 // the two ceilings, at their exact bounds86 try await h.service.enforceUnauditedBitcoinFeeLimit(network: .mainnet, fee: 20_000, vsize: 100)87 #expect(await walletError { try await h.service.enforceUnauditedBitcoinFeeLimit(network: .mainnet, fee: 20_001, vsize: 1_000) } == feeLimit)88 #expect(await walletError { try await h.service.enforceUnauditedBitcoinFeeLimit(network: .mainnet, fee: 20_000, vsize: 99) } == rateLimit)89 try await h.service.enforceUnauditedBitcoinFeeLimit(network: .signet, fee: 900_000, vsize: 100)9091 // sign: a plan built with the check bypassed is refused before any key is read, on every path92 let account = try await h.service.bitcoinAccount()93 let over = try await h.service.buildBitcoinPlan(account: account, snapshot: snapshot, purpose: .payment,94 destination: try BitcoinAddress(Self.external(), network: .mainnet), amount: 100_000,95 feeRate: FeeRate(satPerVByte: 400), sendMax: false, coinControl: BitcoinCoinControl(), enforceLimits: false)96 #expect(over.fee > 20_000)97 #expect(await walletError { try await h.service.signAndBroadcastBitcoin(over) } == feeLimit)98 #expect(await walletError { try await h.service.exportPSBT(over) } == feeLimit)99 let psbt = try account.psbt(for: over.plan).base64100 #expect(await walletError { try await h.service.signPSBT([psbt]) } == feeLimit)101 #expect(await walletError { try await h.service.finalizeAndBroadcastPSBT([psbt]) } == feeLimit)102 #expect(h.backend.broadcastBitcoin.isEmpty)103104 // the plan at the ceiling goes through105 _ = try await h.service.signAndBroadcastBitcoin(atCeiling)106 #expect(h.backend.broadcastBitcoin.count == 1)107108 // the absolute ceiling binds on a transaction with many inputs at an allowed rate109 let many = try await Self.mainnetWallet()110 defer { many.cleanup() }111 for _ in 0..<12 { many.backend.fund(Self.mainnetAddress, 20_000, height: 100) }112 _ = try await many.service.syncBitcoin()113 // eleven inputs of 68 vB at 30 sat/vB cost more than 20 000 sat114 #expect(await walletError { try await many.service.prepareBitcoinSend(to: Self.external(), amount: 190_000, feeRate: FeeRate(satPerVByte: 30)) } == feeLimit)115116 // a test network keeps the general ceilings only117 try await h.service.setActiveNetworks(bitcoin: .signet, ethereum: .sepolia)118 h.backend.network = .signet119 h.backend.genesis = BitcoinNetwork.signet.genesisHash120 let test = try await h.receive(0)121 h.backend.fund(test, 500_000, height: 100)122 _ = try await h.service.syncBitcoin()123 let free = try await h.service.prepareBitcoinSend(to: externalAddress(), amount: 100_000, feeRate: FeeRate(satPerVByte: 400))124 #expect(free.fee > 20_000)125 }126127 @Test func ethereumFeeCeilingIsEnforcedAtPrepareAndAtSign() async throws {128 Self.reset()129 defer { Self.reset() }130 let h = try await Self.mainnetWallet()131 defer { h.cleanup() }132 let owner = EthereumWalletTests.owner133 h.backend.balances[owner] = EthereumWalletTests.oneEther134 let recipient = EthereumWalletTests.recipient135 let feeLimit = WalletError.exceedsUnauditedLimit(limit: "a maximum fee of 0.01 ETH per transaction")136 let amount = UInt256(10_000_000_000_000_000)137138 // 21 000 gas × (2 × 200 gwei + 1 gwei) = 0.008421 ETH: allowed139 h.backend.baseFee = UInt256(200_000_000_000)140 let review = try await h.service.prepareEthereumSend(asset: .ether, to: recipient, amount: amount)141 #expect(review.maximumFee <= MainnetPolicy.limits.etherFeeWeiPerTransaction)142143 // a hostile endpoint announces a base fee of 5 000 gwei (accepted by the client, below its 10 000 gwei bound):144 // 21 000 × 10 001 gwei = 0.21 ETH would have been signed before; it is now refused at prepare145 h.backend.baseFee = UInt256(5_000_000_000_000)146 #expect(await walletError { try await h.service.prepareEthereumSend(asset: .ether, to: recipient, amount: amount) } == feeLimit)147148 // at sign: the reviewed transaction with its fee raised, through the hot and the cold path149 var expensive = review.transaction150 expensive.maxFeePerGas = UInt256(477_000_000_000) // × 21 000 = 0.010017 ETH151 let forged = EthereumSendReview(id: UUID(), network: review.network, createdAt: review.createdAt, from: review.from, asset: .ether,152 recipient: review.recipient, amount: review.amount, transaction: expensive, call: .etherTransfer, feeTier: .normal,153 baseFee: review.baseFee, maximumFee: review.maximumFee, maximumTotalCost: review.maximumTotalCost, isSendMax: false,154 warnings: [])155 #expect(await walletError { try await h.service.signAndBroadcastEthereum(forged) } == feeLimit)156 #expect(await walletError { try await h.service.signColdEthereumPayload(["0x" + Hex.encode(expensive.unsignedPayload)]) } == feeLimit)157 #expect(h.backend.broadcastEthereum.isEmpty)158 // exactly at the ceiling: 0.01 ETH / 21 000 gas159 var exact = review.transaction160 exact.maxFeePerGas = UInt256(476_190_476_190)161 #expect(try await h.service.signColdEthereumPayload(["0x" + Hex.encode(exact.unsignedPayload)]).hash.count == 66)162163 // the reviewed transaction itself goes through164 h.backend.baseFee = UInt256(200_000_000_000)165 _ = try await h.service.signAndBroadcastEthereum(review)166 #expect(h.backend.broadcastEthereum.count == 1)167168 // not limited on a test network169 try await h.service.setActiveNetworks(bitcoin: .signet, ethereum: .sepolia)170 h.backend.chainID = 11_155_111171 h.backend.baseFee = UInt256(5_000_000_000_000)172 let free = try await h.service.prepareEthereumSend(asset: .ether, to: recipient, amount: amount)173 #expect(free.maximumFee > MainnetPolicy.limits.etherFeeWeiPerTransaction)174 }175}176177/// Regression tests of QYV-APP-010: a payment to an address this wallet never paid carries a warning.178struct FirstPaymentWarningTests {179 @Test func bitcoinWarnsOnceThenRemembersThePayment() async throws {180 let h = try await Harness.abandonWallet()181 defer { h.cleanup() }182 let a0 = try await h.receive(0), a1 = try await h.receive(1)183 h.backend.fund(a0, 200_000, height: 100)184 h.backend.fund(a1, 200_000, height: 100)185 _ = try await h.service.syncBitcoin()186 let rate = FeeRate(satPerVByte: 2)187188 let first = try await h.service.prepareBitcoinSend(to: externalAddress(), amount: 20_000, feeRate: rate)189 #expect(first.warnings.contains(.firstPaymentToAddress) && !first.warnings.contains(.destinationAlreadyPaid))190 #expect(BitcoinSendWarning.firstPaymentToAddress.message.contains("First payment to this address"))191 // an address of this wallet is not a "first payment": it has its own warning192 let own = try await h.service.prepareBitcoinSend(to: try await h.receive(5), amount: 20_000, feeRate: rate)193 #expect(own.warnings.contains(.destinationIsOwnAddress) && !own.warnings.contains(.firstPaymentToAddress))194195 // once paid, the same address is known: in this session at once, and after a synchronization from the history196 _ = try await h.service.signAndBroadcastBitcoin(first)197 let again = try await h.service.prepareBitcoinSend(to: externalAddress(), amount: 20_000, feeRate: rate)198 #expect(again.warnings.contains(.destinationAlreadyPaid) && !again.warnings.contains(.firstPaymentToAddress))199 let other = try await h.service.prepareBitcoinSend(to: externalAddress(0x42), amount: 20_000, feeRate: rate)200 #expect(other.warnings.contains(.firstPaymentToAddress))201 h.backend.confirmAll(at: 150)202 _ = try await h.service.syncBitcoin()203 let afterSync = try await h.service.prepareBitcoinSend(to: externalAddress(), amount: 20_000, feeRate: rate)204 #expect(afterSync.warnings.contains(.destinationAlreadyPaid) && !afterSync.warnings.contains(.firstPaymentToAddress))205 }206207 @Test func ethereumWarnsUnlessTheHistoryOrTheSessionShowsAPayment() async throws {208 let h = try await Harness.abandonWallet()209 defer { h.cleanup() }210 let me = await h.ethereumAddress211 h.backend.balances[me] = EthereumWalletTests.oneEther212 let recipient = EthereumWalletTests.recipient213 let known = "0x00000000000000000000000000000000000000bb"214 // the indexer reports one earlier payment, to `known`, and one failed attempt to `recipient`215 func item(_ hash: String, to: String, status: String) -> String {216 "{\"hash\":\"0x\(String(repeating: hash, count: 32))\",\"from\":{\"hash\":\"\(me)\"},\"to\":{\"hash\":\"\(to)\"},\"value\":\"1000\",\"status\":\"\(status)\",\"block_number\":100,\"timestamp\":\"2026-01-01T00:00:00.000000Z\"}"217 }218 h.backend.indexerTransactions = "{\"items\":[" + item("ab", to: known, status: "ok") + "," + item("cd", to: recipient.lowercased(), status: "error") + "],\"next_page_params\":null}"219 let snapshot = try await h.service.syncEthereum()220 #expect(snapshot.history.value?.count == 2)221222 let toKnown = try await h.service.prepareEthereumSend(asset: .ether, to: known, amount: UInt256(1_000))223 #expect(!toKnown.warnings.contains(.firstPaymentToRecipient))224 // a failed transaction paid nobody225 let first = try await h.service.prepareEthereumSend(asset: .ether, to: recipient, amount: UInt256(1_000))226 #expect(first.warnings.contains(.firstPaymentToRecipient))227 #expect(EthereumSendWarning.firstPaymentToRecipient.message.contains("First payment to this address"))228 let own = try await h.service.prepareEthereumSend(asset: .ether, to: Harness.abandonEthereumAddress, amount: UInt256(1_000))229 #expect(own.warnings.contains(.recipientIsOwnAddress) && !own.warnings.contains(.firstPaymentToRecipient))230 // after the payment was broadcast in this session the recipient is known231 _ = try await h.service.signAndBroadcastEthereum(first)232 let again = try await h.service.prepareEthereumSend(asset: .ether, to: recipient, amount: UInt256(1_000), replacePending: true)233 #expect(!again.warnings.contains(.firstPaymentToRecipient))234 }235}236