SPB Git

Repository Public

InterfaceDutiesAuditRegressionTests.swift 16.9 KB 261 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Tests/QyvoraWalletTests/InterfaceDutiesAuditRegressionTests.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 QyvoraCore45import QyvoraBitcoin46import QyvoraEthereum47import QyvoraNetworking48import QyvoraSolana49import QyvoraTron50@testable import QyvoraWallet5152// Regression tests of the controls that used to rest on the screens alone and are now rules of the service:53// QYV-APP-080 (a watch-only package is imported only with the code of that very package, and both devices can show its54// first addresses), QYV-APP-020 / 041 / 060 / 082 (a critical warning that was not acknowledged refuses the signature),55// QYV-APP-062 (a Bitcoin Cash payment of coins older than a chain split takes a newer coin of the wallet with it).56// In the serialized suite: these tests read the process-wide mainnet policy.5758extension MainnetPolicyTests {59    /// Moved from QyvoraCoreTests (see the note there).60    @Test func bothConditionsAreRequired() {61        defer { MainnetPolicy.configure(internalBuildAllowsMainnet: false, userOptedIn: false) }62        MainnetPolicy.configure(internalBuildAllowsMainnet: false, userOptedIn: false)63        #expect(!MainnetPolicy.mainnetAvailable && !MainnetPolicy.mainnetEnabled)64        MainnetPolicy.configure(internalBuildAllowsMainnet: false, userOptedIn: true)65        #expect(!MainnetPolicy.mainnetEnabled)66        MainnetPolicy.configure(internalBuildAllowsMainnet: true, userOptedIn: false)67        #expect(MainnetPolicy.mainnetAvailable && !MainnetPolicy.mainnetEnabled)68        MainnetPolicy.configure(internalBuildAllowsMainnet: true, userOptedIn: true)69        #expect(MainnetPolicy.mainnetEnabled && MainnetPolicy.unauditedMainnet)70        #expect(MainnetPolicy.limits.bitcoinSatoshisPerTransaction == 200_000)71        #expect(BaseUnits.format(MainnetPolicy.limits.etherWeiPerTransaction, decimals: 18) == "0.05")72    }7374    // MARK: QYV-APP-0807576    @Test func aWatchOnlyPackageIsImportedOnlyWithItsOwnCode() async throws {77        Self.reset()78        defer { Self.reset() }79        let cold = try await MultiHarness.wallet(chains: [.bitcoin, .litecoin, .ethereum, .solana, .tron])80        defer { cold.cleanup() }81        let export = try await cold.service.exportWatchOnlyPackage()8283        // the preview: no wallet, no network, the same from the text and from the frames in any order84        let preview = try WalletService.watchOnlyPreview(package: [export.text])85        #expect(try WalletService.watchOnlyPreview(package: export.frames.reversed()) == preview)86        #expect(preview.fingerprint == (try WalletService.watchOnlyFingerprint(package: export.frames)) && preview.fingerprintGroups.count == 5)87        #expect(preview.version == WatchOnlyPackage.currentVersion && preview.unreadable.isEmpty)88        // the first address of every account, as the cold device itself shows them89        let shown = await cold.service.snapshot()90        func address(_ chain: ChainID) -> String? { preview.accounts.first { $0.chain == chain }?.address }91        #expect(address(.ethereum) == MultiHarness.ethereumAddress && address(.solana) == MultiHarness.solanaAddress && address(.tron) == MultiHarness.tronAddress)92        for chain in shown.chains where chain.chain.family == .utxo {93            let receive = try #require(chain.receive?.address, "\(chain.id)")94            #expect(preview.accounts.contains { $0.address == receive && !$0.isMainnet }, "\(chain.id): \(receive)")95        }96        #expect(preview.accounts.count >= 5 && Set(preview.accounts.map(\.id)).count == preview.accounts.count)9798        // a substituted package: another EVM account. Its code and its address differ from what the cold device shows.99        var package = try JSONDecoder().decode(WatchOnlyPackage.self, from: Data(export.text.utf8))100        package.ethereumAddress = EthereumWalletTests.recipient101        let substituted = String(decoding: try JSONEncoder().encode(package), as: UTF8.self)102        let other = try WalletService.watchOnlyPreview(package: [substituted])103        #expect(other.fingerprint != preview.fingerprint)104        #expect(other.accounts.first { $0.chain == .ethereum }?.address.lowercased() == EthereumWalletTests.recipient.lowercased())105106        let online = try await MultiHarness.make()107        defer { online.cleanup() }108        // the code the user read on the cold device does not import the substituted package: nothing is created109        for code in [preview.fingerprint, "", "0000-0000-0000-0000-0000", String(other.fingerprint.dropLast())] {110            guard case .invalidInput(let why)? = await walletError({ try await online.service.importWatchOnly(package: [substituted], comparedFingerprint: code) }) else {111                Issue.record("imported with the code \"\(code)\"")112                return113            }114            #expect(why.contains("Nothing was imported"))115            #expect(await online.service.currentProfile().kind == nil)116        }117        // nor does the code of another package import the genuine one118        guard case .invalidInput? = await walletError({ try await online.service.importWatchOnly(package: export.frames, comparedFingerprint: other.fingerprint) }) else {119            Issue.record("imported with the code of another package")120            return121        }122        #expect(await online.service.currentProfile().kind == nil)123        // the genuine package with its own code, as a person may type or read it: lower case, spaces124        try await online.service.importWatchOnly(package: export.frames, comparedFingerprint: preview.fingerprint.lowercased().replacingOccurrences(of: "-", with: " "))125        let profile = await online.service.currentProfile()126        #expect(profile.kind == .watchOnly && profile.ethereumAddress?.checksummed == MultiHarness.ethereumAddress && profile.solanaAddress == MultiHarness.solanaAddress)127128        // what the preview does with a package it cannot read entirely, and with something that is no package129        var odd = try JSONDecoder().decode(WatchOnlyPackage.self, from: Data(export.text.utf8))130        odd.solanaAddress = "not-an-address"131        odd.accounts?["moonnet"] = BitcoinAccountPublicData(extendedPublicKey: "tpubNOPE", masterFingerprint: nil)132        let partial = try WalletService.watchOnlyPreview(package: [String(decoding: try JSONEncoder().encode(odd), as: UTF8.self)])133        #expect(partial.unreadable.count == 2 && !partial.accounts.contains { $0.chain == .solana } && partial.fingerprint != preview.fingerprint)134        for junk in ["", "{}", "[]", "{\"format\":\"qyvora-watch-only\",\"version\":99}", "{\"format\":\"other\",\"version\":2}", String(repeating: "x", count: 70_000)] {135            #expect(throws: WalletError.self) { try WalletService.watchOnlyPreview(package: [junk]) }136        }137    }138139    /// Moved here from MultiChainModelTests: the answer depends on the process-wide mainnet policy, which the tests140    /// of this serialized suite switch on and off. Outside the suite it failed about once in four runs, whenever a141    /// mainnet test of this suite ran at the same moment.142    @Test func aMainNetworkIsRefusedByNameWhileMainnetIsOff() async throws {143        Self.reset()144        defer { Self.reset() }145        let h = try await MultiHarness.wallet(chains: [.tron])146        defer { h.cleanup() }147        #expect(await walletError { try await h.service.prepareSend(chain: .solana, asset: .native, to: solanaStranger().base58, amount: UInt256(1)) }148            == .mainnetDisabled(WalletError.mainnetText))149        #expect(h.backend.requests.isEmpty)150    }151152    // MARK: QYV-APP-020, 041, 060, 082153154    @Test func aCriticalWarningThatWasNotAcknowledgedRefusesTheSignature() async throws {155        Self.reset()156        defer { Self.reset() }157        let h = try await Self.mainnetMultiWallet(chains: [.solana], prices: [("solana", "100"), ("usd-coin", "1")])158        defer { h.cleanup() }159        let node = h.backend.solana160        let recipient = solanaStranger()161        node.lamports[MultiHarness.solanaAddress] = 100 * MultiChainSendTests.sol162        node.lamports[recipient.base58] = MultiChainSendTests.sol163        let review = try await h.service.prepareSend(chain: .solana, asset: .native, to: recipient.base58, amount: UInt256(1_000_000))164        let critical = review.warnings.filter(\.isCritical).map(\.id)165        #expect(Set(critical) == ["first-payment", "unaudited-mainnet"] && review.hasCriticalWarning)166        // nothing, one of the two, a misspelt identifier: refused before anything is signed or sent167        for given in [Set<String>(), ["first-payment"], ["unaudited-mainnet"], ["first-payment", "unaudited-mainnet "], ["FIRST-PAYMENT", "UNAUDITED-MAINNET"]] {168            guard case .invalidInput(let why)? = await walletError({ try await h.service.signAndBroadcast(review, acknowledged: given) }) else {169                Issue.record("signed with \(given)")170                return171            }172            #expect(why.contains("not acknowledged"))173        }174        #expect(node.sent.isEmpty && node.simulations == 1)175        _ = try await h.service.signAndBroadcast(review, acknowledged: ["unaudited-mainnet", "first-payment", "something-else"])176        #expect(node.sent.count == 1)177        // the rule itself178        let two = [SendWarning(id: "a", message: "A", isCritical: true), SendWarning(id: "b", message: "B", isCritical: true), SendWarning(id: "c", message: "C", isCritical: false)]179        #expect(throws: WalletError.self) { try WalletService.requireAcknowledged(two, ["a"]) }180        #expect(throws: WalletError.self) { try WalletService.requireAcknowledged(two, ["c", "b"]) }181        try WalletService.requireAcknowledged(two, ["a", "b"])182        try WalletService.requireAcknowledged([], [])183    }184185    // MARK: QYV-SVC-025 (partial)186187    /// A plain SOL payment broadcast for a cold device is remembered under the key `prepareSend` computes for the188    /// same payment, so that preparing it again while it is in flight is refused. Anything else keeps its own key.189    @Test func aColdSolanaPaymentTakesTheKeyOfTheSamePaymentPreparedHere() throws {190        let me = try #require(SolanaPublicKey(base58: MultiHarness.solanaAddress))191        let recipient = solanaStranger()192        let blockhash = Bytes(repeating: 7, count: 32)193        let plain = try SolanaTransaction(message: SolanaMessage(feePayer: me, instructions: [SolanaSystemProgram.transfer(from: me, to: recipient, lamports: 250_000_000)],194                                                                 recentBlockhash: blockhash))195        #expect(WalletService.coldSolanaPaymentKey(plain, network: .devnet, owner: me)196            == WalletService.paymentKey(.solana(.devnet), recipient: recipient.base58, asset: .native, amount: UInt256(250_000_000)))197        #expect(WalletService.coldSolanaPaymentKey(plain, network: .devnet, owner: me) != WalletService.coldSolanaPaymentKey(plain, network: .mainnetBeta, owner: me))198        // two transfers, or an instruction the wallet cannot decode: not a plain payment199        let double = try SolanaTransaction(message: SolanaMessage(feePayer: me, instructions: [200            SolanaSystemProgram.transfer(from: me, to: recipient, lamports: 1), SolanaSystemProgram.transfer(from: me, to: solanaStranger(9), lamports: 2),201        ], recentBlockhash: blockhash))202        #expect(WalletService.coldSolanaPaymentKey(double, network: .devnet, owner: me).hasPrefix("cold|"))203        let unknown = SolanaInstruction(programID: solanaStranger(90), accounts: [SolanaAccountMeta(me, isSigner: true, isWritable: true)], data: [1, 2, 3])204        let blind = try SolanaTransaction(message: SolanaMessage(feePayer: me, instructions: [SolanaSystemProgram.transfer(from: me, to: recipient, lamports: 5), unknown],205                                                                 recentBlockhash: blockhash))206        #expect(WalletService.coldSolanaPaymentKey(blind, network: .devnet, owner: me).hasPrefix("cold|"))207    }208209    // MARK: QYV-APP-062210211    @Test func aBitcoinCashPaymentOfOldCoinsTakesANewerCoinWithIt() async throws {212        Self.reset()213        defer { Self.reset() }214        let h = try await Self.coinMainnetWallet(.bitcoinCash, .bitcoinCash)215        defer { h.cleanup() }216        h.backend.markets = ServiceTests.market([("bitcoin-cash", "500")])217        h.backend.tip = 950_000218        let old = h.backend.fund(CoinFixture.bitcoinCash0, 2_000_000, height: 500_000)219        let newer = h.backend.fund(CoinFixture.bitcoinCash0, 900_000, height: 700_000)220        let newest = h.backend.fund(CoinFixture.bitcoinCash0, 3_000_000, height: 800_000)221        try await h.service.synchronize(chain: .bitcoinCash)222        let oldCoin = try #require(BitcoinOutPoint(txid: old, vout: 0)), newerCoin = try #require(BitcoinOutPoint(txid: newer, vout: 0))223        // QYV-APP-061: this wallet reads Bitcoin Cash from one source, and its snapshot says so224        let coinNotes = try #require(await h.service.snapshot().chain(.bitcoinCash)?.data.value?.notes)225        #expect(coinNotes.contains { $0.hasPrefix(WalletService.singleIndexerNotePrefix) && $0.contains("not confirmed by a second source") })226        let recipient = CoinFixture.external(.bitcoinCash)227        func options(_ control: BitcoinCoinControl) -> SendOptions {228            var o = SendOptions()229            o.coinControl = control230            return o231        }232        // the old coin alone would do; the smallest coin created after the split is added, and nothing is replayable233        let review = try await h.service.prepareSend(chain: .bitcoinCash, asset: .native, to: recipient, amount: UInt256(500_000), options: options(BitcoinCoinControl(required: [oldCoin])))234        let plan = try CoinFixture.plan(review)235        #expect(Set(plan.inputs.map(\.outPoint)) == [oldCoin, newerCoin])236        #expect(!review.warnings.contains { $0.id == "bch.replayable-on-forks" })237        #expect(review.warnings.contains { $0.id == "bch.replay-protected" && !$0.isCritical })238        #expect(plan.inputs.reduce(0) { $0 + $1.value } == plan.amount + plan.fee + plan.changeValue && plan.amount == 500_000)239        _ = newest240241        // the user asked for exactly the old coin: the wallet does not add another, and the critical warning stays242        let exact = try await h.service.prepareSend(chain: .bitcoinCash, asset: .native, to: recipient, amount: UInt256(500_000),243                                                    options: options(BitcoinCoinControl(required: [oldCoin], useOnlyRequired: true)))244        #expect(try CoinFixture.plan(exact).inputs.map(\.outPoint) == [oldCoin])245        #expect(exact.warnings.contains { $0.id == "bch.replayable-on-forks" && $0.isCritical })246        guard case .invalidInput? = await walletError({ try await h.service.signAndBroadcast(exact, acknowledged: ["unaudited-mainnet"]) }) else {247            Issue.record("signed a replayable payment without the acknowledgement of the replay warning")248            return249        }250251        // frozen: a coin the user set aside is not taken252        try await h.service.setFrozen(true, outPoint: newerCoin)253        try await h.service.synchronize(chain: .bitcoinCash)254        let withFrozen = try await h.service.prepareSend(chain: .bitcoinCash, asset: .native, to: recipient, amount: UInt256(500_000), options: options(BitcoinCoinControl(required: [oldCoin])))255        #expect(!Set(try CoinFixture.plan(withFrozen).inputs.map(\.outPoint)).contains(newerCoin))256        #expect(!withFrozen.warnings.contains { $0.id == "bch.replayable-on-forks" })257        // the helper: nothing on another network, nothing when every coin is old258        #expect(WalletService.replayProtectingCoin(nil, excluding: plan) == nil)259    }260}261
Files main
Menu

Theme