SPB Git

Repository Public

NewEntryPointsProperties.swift 21.2 KB 295 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : security/tests/Tests/PropertyAuditTests/NewEntryPointsProperties.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 AuditSupport42import Foundation43import QyvoraBitcoin44import QyvoraCore45import QyvoraMath46import QyvoraStorage47import Testing4849@testable import QyvoraWallet5051// The entry points brought by the merge of `main` (4ac4e69) that read hostile on-disk state: the persisted52// synchronization of Litecoin, Dogecoin and Bitcoin Cash (`utxo-sync-<network>.json`) and the hidden-token list of53// the profile. One wallet on the BIP-39 test phrase, test networks, a transport that refuses every request.5455extension WalletService {56    /// The hidden list as a hostile profile file would give it (the profile is not authenticated: QYV-SVC-011).57    func auditSetHiddenTokens(_ list: [String]) { profile.hiddenTokens = list }58}5960@Suite struct NewEntryPointsProperties {61    static let networks: [BitcoinNetwork] = [.litecoinTestnet, .dogecoinTestnet, .bitcoinCashTestnet]6263    /// A record as a synchronization writes it: the first receive address funded, spent from, and funded again (that64    /// coin sits behind a published key); the first change address holding the remainder.65    static func record(_ profile: WalletProfile, network: BitcoinNetwork) throws -> (record: UTXOCoinSyncRecord, account: UTXOAccount) {66        let identity = try #require(WalletService.utxoCoinIdentity(profile, network: network))67        let data = try #require(profile.bitcoinAccounts[WalletService.accountKey(network)])68        let account = try UTXOAccount(extendedKey: data.extendedPublicKey, network: network)69        let receive = try account.address(chain: .receive, index: 0), change = try account.address(chain: .change, index: 0)70        func out(_ a: BitcoinAddress, _ value: UInt64) -> UTXOCoinSyncRecord.Output { .init(address: a.stringWithoutPrefix, scriptPubKey: Hex.encode(a.scriptPubKey), value: value) }71        let stranger = UTXOCoinSyncRecord.Output(address: nil, scriptPubKey: "76a914" + String(repeating: "77", count: 20) + "88ac", value: 100_000)72        let source = String(repeating: "a1", count: 32), funding = String(repeating: "b2", count: 32), spending = String(repeating: "c3", count: 32), second = String(repeating: "d4", count: 32)73        let fund = UTXOCoinSyncRecord.Transaction(txid: funding, inputs: [.init(txid: source, vout: 0, previous: nil, sequence: 0xffff_fffe)], outputs: [out(receive, 500_000)],74                                                  fee: nil, virtualSize: 110, height: 100, time: 1_790_000_000)75        let spend = UTXOCoinSyncRecord.Transaction(txid: spending, inputs: [.init(txid: funding, vout: 0, previous: out(receive, 500_000), sequence: 0xffff_fffe)],76                                                   outputs: [stranger, out(change, 399_000)], fee: 1_000, virtualSize: 141, height: 120, time: 1_790_001_000)77        let again = UTXOCoinSyncRecord.Transaction(txid: second, inputs: [.init(txid: source, vout: 1, previous: nil, sequence: nil)], outputs: [out(receive, 70_000)],78                                                   fee: nil, virtualSize: 110, height: 125, time: 1_790_002_000)79        let entries = [80            UTXOCoinSyncRecord.Entry(chain: 0, index: 0, address: receive.string, isUsed: true, hasSpent: true, transactionCount: 3, confirmedBalance: 70_000, isComplete: true,81                                     coins: [.init(txid: second, vout: 0, value: 70_000, height: 125, isCoinbase: false)], transactions: [fund, spend, again], truncated: false),82            UTXOCoinSyncRecord.Entry(chain: 1, index: 0, address: change.string, isUsed: true, hasSpent: false, transactionCount: 1, confirmedBalance: 399_000, isComplete: true,83                                     coins: [.init(txid: spending, vout: 1, value: 399_000, height: 120, isCoinbase: nil)], transactions: [spend], truncated: false),84        ]85        return (UTXOCoinSyncRecord(identity: identity, network: network, synchronizedAt: Date(timeIntervalSince1970: 1_790_003_000), tipHeight: 130, notes: ["n"], entries: entries), account)86    }8788    /// One structural change of a record, chosen by the generator.89    static func mutate(_ r: inout UTXOCoinSyncRecord, _ rng: inout AuditRNG) {90        let amounts: [UInt64] = [0, 1, 546, 70_000, 399_000, 500_000, 8_400_000_000_000_000, 10_000_000_000 * 100_000_000, UInt64(Int64.max), UInt64.max - 1, UInt64.max]91        let heights: [Int?] = [nil, -1, 0, 1, 99, 130, 131, 99_999_999, 100_000_000, Int(Int32.max), Int.max, Int.min]92        let hexes = [String(repeating: "b2", count: 32), String(repeating: "c3", count: 32), String(repeating: "d4", count: 32), String(repeating: "e5", count: 32), String(repeating: "B2", count: 32), "", "zz",93                     String(repeating: "0", count: 63)]94        let e = r.entries.isEmpty ? 0 : rng.int(0...(r.entries.count - 1))95        switch rng.int(0...27) {96        case 0: r.version = rng.pick([0, 1, 2, -1, Int.max])97        case 1: r.identity = rng.pick(["", r.identity + "x", String(r.identity.dropLast()), "utxo|v1|" + r.network.rawValue + "||"])98        case 2: r.network = rng.pick(BitcoinNetwork.allCases)99        case 3: r.tipHeight = rng.pick([0, 1, 119, 124, 130, 99_999_999, 100_000_000, UInt32.max])100        case 4: r.synchronizedAt = Date(timeIntervalSince1970: rng.pick([-1e300, -1, 0, 1e9, 4e9, 1e18, 1e300]))101        case 5: r.notes = Array(repeating: String(repeating: "n", count: rng.int(0...40)), count: rng.pick([0, 1, 50, 51, 400]))102        case 6: r.entries = Array(r.entries.reversed())103        case 7: if !r.entries.isEmpty { r.entries.append(r.entries[e]) }104        case 8: if !r.entries.isEmpty { r.entries.remove(at: e) }105        case 9: if !r.entries.isEmpty { r.entries[e].index = rng.pick([0, 1, 19, 1_999, 2_000, UInt32.max]) }106        case 10: if !r.entries.isEmpty { r.entries[e].chain = rng.pick([0, 1, 2, UInt32.max]) }107        case 11: if !r.entries.isEmpty { r.entries[e].address = rng.pick(["", r.entries[e].address.uppercased(), r.entries[(e + 1) % r.entries.count].address, "tltc1q6rz28mcfaxtmd6v789l9rrlrusdprr9pesrjxk"]) }108        case 12: if !r.entries.isEmpty { r.entries[e].isUsed.toggle() }109        case 13: if !r.entries.isEmpty { r.entries[e].hasSpent.toggle() }110        case 14: if !r.entries.isEmpty { r.entries[e].truncated.toggle() }111        case 15: if !r.entries.isEmpty { r.entries[e].isComplete.toggle() }112        case 16: if !r.entries.isEmpty { r.entries[e].transactionCount = rng.pick([nil, 0, -1, Int.max, Int.min]) }113        case 17: if !r.entries.isEmpty { r.entries[e].confirmedBalance = rng.pick(amounts) }114        case 18: if !r.entries.isEmpty, !r.entries[e].coins.isEmpty { r.entries[e].coins[0].value = rng.pick(amounts) }115        case 19: if !r.entries.isEmpty, !r.entries[e].coins.isEmpty { r.entries[e].coins[0].txid = rng.pick(hexes) }116        case 20: if !r.entries.isEmpty, !r.entries[e].coins.isEmpty { r.entries[e].coins[0].vout = rng.pick([0, 1, 2, 99_999, 100_000, UInt32.max]) }117        case 21: if !r.entries.isEmpty, !r.entries[e].coins.isEmpty { r.entries[e].coins[0].height = rng.pick(heights) }118        case 22: if !r.entries.isEmpty, let c = r.entries[e].coins.first { r.entries[e].coins += Array(repeating: c, count: rng.pick([1, 2, 5_000])) }119        case 23:120            if !r.entries.isEmpty, !r.entries[e].transactions.isEmpty {121                let t = rng.int(0...(r.entries[e].transactions.count - 1))122                switch rng.int(0...6) {123                case 0: r.entries[e].transactions[t].txid = rng.pick(hexes)124                case 1: r.entries[e].transactions[t].height = rng.pick(heights)125                case 2: r.entries[e].transactions[t].time = rng.pick(heights)126                case 3: r.entries[e].transactions[t].fee = rng.pick(amounts)127                case 4: r.entries[e].transactions[t].virtualSize = rng.pick(heights)128                case 5: r.entries[e].transactions[t].inputs = rng.bool() ? [] : r.entries[e].transactions[t].inputs + r.entries[e].transactions[t].inputs129                default: r.entries[e].transactions[t].outputs = rng.bool() ? [] : Array(r.entries[e].transactions[t].outputs.reversed())130                }131            }132        case 24:133            if !r.entries.isEmpty, !r.entries[e].transactions.isEmpty {134                let t = rng.int(0...(r.entries[e].transactions.count - 1))135                if !r.entries[e].transactions[t].outputs.isEmpty {136                    let o = rng.int(0...(r.entries[e].transactions[t].outputs.count - 1))137                    switch rng.int(0...2) {138                    case 0: r.entries[e].transactions[t].outputs[o].value = rng.pick(amounts)139                    case 1: r.entries[e].transactions[t].outputs[o].scriptPubKey = rng.pick([nil, "", "zz", "6a", String(repeating: "00", count: 10_001), "0014" + String(repeating: "ee", count: 20)])140                    default: r.entries[e].transactions[t].outputs[o].address = rng.pick([nil, "", "x", "1BoatSLRHtKNngkdXEeobR76b53LETtpyT"])141                    }142                }143            }144        case 25:145            if !r.entries.isEmpty, !r.entries[e].transactions.isEmpty {146                let t = rng.int(0...(r.entries[e].transactions.count - 1))147                if !r.entries[e].transactions[t].inputs.isEmpty {148                    switch rng.int(0...3) {149                    case 0: r.entries[e].transactions[t].inputs[0].txid = rng.pick(hexes + [nil] as [String?])150                    case 1: r.entries[e].transactions[t].inputs[0].vout = rng.pick([nil, 0, 1, 99_999, 100_000, UInt32.max])151                    case 2: r.entries[e].transactions[t].inputs[0].previous?.value = rng.pick(amounts)152                    default: r.entries[e].transactions[t].inputs[0].previous = nil153                    }154                }155            }156        case 26: if !r.entries.isEmpty, let t = r.entries[e].transactions.first { r.entries[e].transactions += Array(repeating: t, count: rng.pick([1, 3, 200])) }157        default: if !r.entries.isEmpty { r.entries[e].coins = [] }158        }159    }160161    @Test func forgedCoinRecordsAreRefusedOrFlaggedAndBounded() async throws {162        let seed = AuditSeed.make("new.utxo-coin-record")163        var rng = AuditRNG(seed: seed)164        var prop = Prop("a persisted coin synchronization altered in its structure is refused and removed, or restored flagged as the previous session's, on the account's own addresses, inside the monetary range, with nothing but its snapshot; never a trap",165                        algorithm: "restoredUTXOCoin", parameterSet: "Litecoin, Dogecoin and Bitcoin Cash test networks × 1 to 4 structural changes", seed: seed)166        let w = try await MCWallet.make()167        defer { w.cleanup() }168        let profile = await w.service.currentProfile()169        let encoder = JSONEncoder()170        var restored = 0, refused = 0171        for network in Self.networks {172            let (honest, account) = try Self.record(profile, network: network)173            let name = UTXOCoinSyncRecord.fileName(network)174            // the control: the unaltered record is restored, with its two coins, one of them behind a published key175            try w.store.write(Bytes(try encoder.encode(honest)), to: name, keepPrevious: false)176            let control = WalletService.restoredUTXOCoin(fileStore: w.store, profile: profile, network: network)?.snapshot177            prop.check(control?.isFromPreviousSession == true && control?.utxos.count == 2 && control?.balance.confirmed == 469_000178                           && control?.utxos.filter { $0.exposure == .revealedBySpend }.count == 1, "\(network): the honest record is not restored as written")179            let maximum = network.maximumMoney180            for _ in 0..<AuditMode.cases(quick: 250, full: 6_000) {181                var r = honest182                for _ in 0..<rng.int(1...4) { Self.mutate(&r, &rng) }183                guard let bytes = try? encoder.encode(r) else { continue }184                try w.store.write(Bytes(bytes), to: name, keepPrevious: false)185                guard let state = WalletService.restoredUTXOCoin(fileStore: w.store, profile: profile, network: network) else {186                    refused += 1187                    prop.check(!w.store.exists(name), "\(network): a refused record was left on disk")188                    continue189                }190                restored += 1191                guard let s = state.snapshot else {192                    prop.check(false, "\(network): a state without a snapshot")193                    continue194                }195                var ok = s.isFromPreviousSession && s.network == network && state.paidScripts.isEmpty && state.locallySpent.isEmpty196                ok = ok && r.identity == honest.identity && r.network == network && r.version == 1 && r.tipHeight < 100_000_000197                ok = ok && s.balance.confirmed <= maximum && s.balance.pending <= maximum && s.utxos.reduce(UInt64(0)) { $0 &+ $1.utxo.value } == s.balance.confirmed + s.balance.pending198                ok = ok && s.utxos.allSatisfy { u in199                    guard let d = u.utxo.derivation, let chain = UTXOAccount.Chain(rawValue: d.chain) else { return false }200                    return u.utxo.value > 0 && (try? account.scriptPubKey(chain: chain, index: d.index)) == u.utxo.scriptPubKey201                }202                ok = ok && WalletService.chainData(s).isFromPreviousSession203                prop.check(ok, "\(network): a restored record breaks an invariant")204            }205        }206        #expect(restored > 0 && refused > 0)207        prop.finish(note: "\(restored) altered records restored (flagged), \(refused) refused and removed")208    }209210    @Test func aRestoredCoinRecordIsNeverSpentFrom() async throws {211        let seed = AuditSeed.make("new.utxo-coin-record-spend")212        var rng = AuditRNG(seed: seed)213        var prop = Prop("after a restart on a persisted coin synchronization (honest or with inflated amounts), no payment and no sweep is prepared from its coins, whatever the amount, and no request is sent",214                        algorithm: "prepareSend / prepareSweepOfExposed on a restored UTXO coin", parameterSet: "Litecoin, Dogecoin and Bitcoin Cash test networks", seed: seed)215        let w = try await MCWallet.make()216        defer { w.cleanup() }217        let profile = await w.service.currentProfile()218        let encoder = JSONEncoder()219        for round in 0..<AuditMode.cases(quick: 2, full: 12) {220            for network in Self.networks {221                var (r, account) = try Self.record(profile, network: network)222                if round > 0 {223                    // a forgery that holds together: the coin behind the published key and the output that made it224                    let value = UInt64(rng.int(1...Int(min(network.maximumMoney / 2, UInt64(Int.max / 2)))))225                    r.entries[0].coins[0].value = value226                    r.entries[0].transactions[2].outputs[0].value = value227                }228                try w.store.write(Bytes(try encoder.encode(r)), to: UTXOCoinSyncRecord.fileName(network), keepPrevious: false)229                // the next launch, on the same directory230                let next = try await MCWallet.make(full: false, directory: w.directory)231                let chain = ChainRegistry.id(network)232                let data = await next.service.chainSnapshot(chain)?.data.value233                prop.check(data?.isFromPreviousSession == true && data?.native.confirmed == UInt256(r.entries[0].coins[0].value + 399_000), "\(network): the record is not shown as the previous session's")234                let recipient = try BitcoinAddress(scriptPubKey: network.supportsSegWit ? try BitcoinScript.p2wpkh(publicKeyHash: rng.bytes(20)) : try BitcoinScript.p2pkh(publicKeyHash: rng.bytes(20)),235                                                   network: network).string236                var options = SendOptions()237                options.bitcoinFeeRate = .minimum(for: network)238                for amount in [UInt64(1_000), 70_000, 399_000, UInt64(rng.int(1...1_000_000_000)), r.entries[0].coins[0].value] {239                    options.sendMax = rng.int(0...4) == 0240                    let refusal = await MCWallet.error { try await next.service.prepareSend(chain: chain, asset: .native, to: recipient, amount: UInt256(amount), options: options) }241                    if case .notSynchronized? = refusal { prop.check(true, "") } else { prop.check(false, "\(network): prepareSend answered \(String(describing: refusal))") }242                }243                let sweep = await MCWallet.error { try await next.service.prepareSweepOfExposed(chain: chain, feeRate: .minimum(for: network)) }244                if case .notSynchronized? = sweep { prop.check(true, "") } else { prop.check(false, "\(network): prepareSweepOfExposed answered \(String(describing: sweep))") }245                prop.check(next.transport.requests == 0, "\(network): \(next.transport.requests) request(s) were sent")246                _ = account247            }248        }249        prop.finish()250    }251252    @Test func aHostileHiddenListIsListedWithinBoundsAndShowingATokenChangesNoList() async throws {253        let seed = AuditSeed.make("new.hidden-tokens")254        var rng = AuditRNG(seed: seed)255        var prop = Prop("a hidden-token list of any content is listed per chain without duplicates across chains and within its own size; showing an entry again removes that entry only and changes no token list; no request",256                        algorithm: "hiddenTokens / showHiddenToken", parameterSet: "random lists of 0 to 300 entries, 6 chains", seed: seed)257        let w = try await MCWallet.make()258        defer { w.cleanup() }259        let chains: [ChainID] = [.solanaDevnet, .ethereumSepolia, .tronNile, .baseSepolia, .bitcoinSignet, .solana]260        let prefixes = ["sepolia:", "baseSepolia:", "solana-devnet:", "tron-nile:", "solana:", "mainnet:", ":", "", "sepolia:sepolia:"]261        let before = await w.service.currentProfile()262        let asked = w.transport.requests263        for _ in 0..<AuditMode.cases(quick: 40, full: 1_500) {264            var list = [String]()265            for _ in 0..<rng.pick([0, 1, 3, 20, 300]) {266                let body = rng.bool() ? "0x" + Hex.encode(rng.bytes(20)) : String(decoding: rng.bytes(rng.int(0...40)).map { 0x20 + $0 % 0x5f }, as: UTF8.self)267                let entry = rng.pick(prefixes) + body268                list.append(entry)269                if rng.int(0...5) == 0 { list.append(entry) }270            }271            await w.service.auditSetHiddenTokens(list)272            var total = 0, ok = true273            for id in chains {274                let listed = await w.service.hiddenTokens(chain: id)275                total += listed.count276                ok = ok && listed.allSatisfy { $0.chain == id && ($0.token == nil || $0.token?.chain == id) }277            }278            prop.check(ok && total <= list.count, "a hidden list of \(list.count) entries is listed as \(total)")279            // show one entry again, described with a lie280            let chain = rng.pick(chains)281            let listed = await w.service.hiddenTokens(chain: chain)282            let address = listed.isEmpty || rng.int(0...3) == 0 ? "0x" + Hex.encode(rng.bytes(20)) : rng.pick(listed).address283            let lie = ChainToken(chain: chain, address: address, symbol: "LIE", name: "Lie", decimals: 0, standard: .erc20)284            _ = await MCWallet.error { try await w.service.showHiddenToken(HiddenToken(chain: chain, address: address, token: lie)) }285            let after = await w.service.currentProfile()286            let gone = Set(list).subtracting(after.hiddenTokens)287            prop.check(after.customTokens == before.customTokens && after.customSolanaTokens == before.customSolanaTokens && after.customTronTokens == before.customTronTokens288                           && Set(after.hiddenTokens).isSubset(of: Set(list)) && gone.count <= 1 && gone.allSatisfy { $0.hasSuffix(":" + address) },289                       "showing \(address) on \(chain.rawValue) changed more than its own entry")290        }291        prop.check(w.transport.requests == asked, "requests were sent")292        prop.finish()293    }294}295
Files main
Menu

Theme