SPB Git

Repository Public

Targets+MultichainWallet.swift 47.0 KB 687 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : security/tests/Sources/FuzzTargets/Targets+MultichainWallet.swift8// Module           : Tests9// Repository       : https://git.spboucher.ai/qyvora10// Project Website  : Not specified11// Created          : 2026-12-0412// 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 QyvoraEthereum46import QyvoraMath47import QyvoraNetworking48import QyvoraSolana49import QyvoraStorage50import QyvoraTron51import QyvoraVault52@testable import QyvoraWallet5354// The machinery shared by every chain family, under untrusted text and files: the cold-mode envelope, the watch-only55// package, the persisted chain snapshots, address validation and the account binding record. One full wallet (the56// BIP-39 test phrase, tiny key derivation, temporary directory, cold mode) per process; nothing reaches the network.5758/// A transport that refuses every request: the cold wallet must never use it.59struct MCRefusingTransport: HTTPTransport {60    func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) { throw URLError(.notConnectedToInternet) }61}6263final class MCFuzzWallet: @unchecked Sendable {64    static let fixedNow = Date(timeIntervalSince1970: 1_800_000_000)65    static let instant = MonotonicInstant(bootSession: Bytes(repeating: 0xb0, count: 16), seconds: 5_000)6667    let service: WalletService68    let store: FileStore69    let profile: WalletProfile7071    init(service: WalletService, store: FileStore, profile: WalletProfile) {72        self.service = service73        self.store = store74        self.profile = profile75    }7677    /// A service on a new temporary directory, clocks stopped (an authentication stays fresh, nothing expires).78    static func newService(_ tag: String) -> (WalletService, FileStore, URL)? {79        let dir = FileManager.default.temporaryDirectory.appendingPathComponent("qyfuzz-mc-\(tag)-\(getpid())-\(UUID().uuidString.prefix(8))")80        guard let store = try? FileStore(root: dir) else { return nil }81        let vault = Vault(fileStore: store, keychain: InMemoryKeychainStore(), configuration: .init(kdf: .insecureForTesting, now: { fixedNow }, monotonic: { instant }))82        guard let service = try? WalletService(vault: vault, fileStore: store, transport: MCRefusingTransport(), now: { fixedNow }, monotonic: { instant }, sleep: { _ in },83                                               transactionSeed: 7, backupKDF: .insecureForTesting, tronPacing: .unthrottled) else { return nil }84        return (service, store, dir)85    }8687    /// The cold wallet of this process: every chain enabled, test networks, cold mode.88    static let shared: MCFuzzWallet? = {89        guard let (service, store, _) = newService("cold") else { return nil }90        nonisolated(unsafe) var profile: WalletProfile?91        fuzzAwait {92            do {93                try await service.importWallet(words: BIP39.words(from: abandon), password: "correct horse battery staple 42")94                try await service.setEnabledChains(ChainRegistry.mainChains.map(\.id))95                try await service.setColdMode(true)96                profile = await service.currentProfile()97            } catch {}98        }99        guard let profile, profile.kind == .full, profile.solanaAddress != nil, profile.tronAddress != nil else { return nil }100        return MCFuzzWallet(service: service, store: store, profile: profile)101    }()102}103104// MARK: Seeds105106func coldEnvelopeSeeds() -> [Bytes] {107    guard let w = MCFuzzWallet.shared, let me = SolanaPublicKey(base58: w.profile.solanaAddress ?? ""), let tronMe = TronAddress(w.profile.tronAddress ?? ""),108          let stranger = try? SolanaKeys.publicKey(privateSeed: Bytes(repeating: 9, count: 32)), let tronStranger = TronAddress(hash: Bytes(repeating: 0x33, count: 20)) else { return [] }109    var texts = [String]()110    if let message = try? SolanaMessage(feePayer: me, instructions: [SolanaSystemProgram.transfer(from: me, to: stranger, lamports: 250_000_000)], recentBlockhash: Bytes(repeating: 7, count: 32)),111       let payload = try? SolanaTransaction(message: message).base64() {112        texts.append("qyvtx1|u|solana-devnet|\(payload)")113        texts.append("qyvtx1|u|solana-testnet|\(payload)")114        texts.append("qyvtx1|u|tron-nile|\(payload)")115    }116    let ms = UInt64(MCFuzzWallet.fixedNow.timeIntervalSince1970 * 1000), number: UInt64 = 60_000_000117    if let reference = TronBlockReference(number: number, id: Endian.be64(number) + Bytes(repeating: 0xab, count: 24), timestamp: ms),118       let tx = try? TronTransaction.transfer(from: tronMe, to: tronStranger, amountSun: 5_000_000, reference: reference, timestamp: ms, expiration: ms + 1_800_000) {119        texts.append("qyvtx1|u|tron-nile|\(Hex.encode(tx.rawData))")120        texts.append("qyvtx1|u|solana-devnet|\(Hex.encode(tx.rawData))")121    }122    let to = EthereumAddress(bytes: Bytes(repeating: 0x70, count: 20))123    for network in [EthereumNetwork.sepolia, .baseSepolia, .polygonAmoy, .bscTestnet, .mainnet] {124        let tx = EIP1559Transaction(chainID: network.chainID, nonce: 3, maxPriorityFeePerGas: UInt256(1_000_000_000), maxFeePerGas: UInt256(30_000_000_000), gasLimit: 21_000, to: to, value: UInt256(1_000))125        texts.append("0x" + Hex.encode(tx.unsignedPayload))126    }127    if let token = to {128        let call = EIP1559Transaction(chainID: 11_155_111, nonce: 0, maxPriorityFeePerGas: UInt256(1), maxFeePerGas: UInt256(2), gasLimit: 60_000, to: token, value: .zero, data: ERC20.transfer(to: token, amount: UInt256(5)))129        texts.append("0x" + Hex.encode(call.unsignedPayload))130    }131    // the signed form of the first ones (signatures of the public test phrase: no secret)132    nonisolated(unsafe) var signed = [String]()133    let unsigned = texts134    fuzzAwait {135        for text in unsigned.prefix(8) {136            if let s = try? await w.service.signColdTransaction([text]) { signed.append(s.export.text) }137        }138    }139    return (texts + signed + ["qyvtx1|u|solana-devnet|", "qyvtx1|s|tron-nile|00", "qyvtx2|u|solana-devnet|AAAA"]).map { Bytes($0.utf8) }140}141142func watchOnlySeeds() -> [Bytes] {143    guard let w = MCFuzzWallet.shared else { return [] }144    nonisolated(unsafe) var text = ""145    fuzzAwait { text = (try? await w.service.exportWatchOnlyPackage().text) ?? "" }146    guard !text.isEmpty, var object = (try? JSONSerialization.jsonObject(with: Data(text.utf8))) as? [String: Any] else { return [] }147    var out = [Bytes(text.utf8)]148    func add(_ o: [String: Any]) {149        if let d = try? JSONSerialization.data(withJSONObject: o, options: [.sortedKeys]) { out.append(Bytes(d)) }150    }151    var v1 = object152    v1["version"] = 1153    for key in ["solanaAddress", "tronAddress", "accounts", "enabledChains"] { v1[key] = nil }154    add(v1)155    object["bitcoin"] = nil156    add(object)157    object["accounts"] = nil158    object["enabledChains"] = ["solana", "tron", "ethereum", "base"]159    add(object)160    return out161}162163func chainSnapshotSeeds() -> [Bytes] {164    guard let w = MCFuzzWallet.shared, let solAddress = w.profile.solanaAddress, let tronAddress = w.profile.tronAddress, let evmAddress = w.profile.ethereumAddress,165          let solIdentity = WalletService.solanaIdentity(w.profile, network: .devnet), let tronIdentity = WalletService.tronIdentity(w.profile, network: .nile) else { return [] }166    let encoder = JSONEncoder()167    encoder.outputFormatting = [.sortedKeys]168    var out = [Bytes]()169    let when = MCFuzzWallet.fixedNow170    let token = ChainToken(chain: .solanaDevnet, address: solAddress, symbol: "TKN", name: "Token", decimals: 6, standard: .spl)171    let entry = ActivityEntry(chain: .solanaDevnet, id: "a", hash: "a", direction: .received, counterparty: solAddress, amount: UInt256(5), decimals: 9, symbol: "SOL", fee: nil,172                              status: .finalized, time: when, blockHeight: 4, kind: .native)173    let sol = SolanaChainRecord(identity: solIdentity, network: .devnet, address: solAddress, synchronizedAt: when, slot: 5, lamports: 7,174                                extras: SolanaExtras(accountExists: true, systemAccountRent: 890_880, tokenAccountRent: 2_039_280, token2022AccountRent: 2_074_080, tokenAccountCount: 1),175                                holdings: [ChainHolding(token: token, amount: UInt256(5), reason: nil, warning: nil, listed: true)], history: [entry], historyReason: nil, hasOutgoing: false, notes: ["n"])176    if let d = try? encoder.encode(sol) { out.append(Bytes("a".utf8) + Bytes(d)) }177    let resources = TronChainRecord.Resources(TronResources(freeNetLimit: 600, freeNetUsed: 0, netLimit: 0, netUsed: 0, energyLimit: 0, energyUsed: 0))178    let parameters = TronChainRecord.Parameters(TronChainParameters(bandwidthPriceSun: 1_000, energyPriceSun: 100, accountActivationFeeSun: 1_000_000, createAccountFeeSun: 100_000,179                                                                    createAccountBandwidthRate: 1, maximumFeeLimitSun: 15_000_000_000, memoFeeSun: 1_000_000))180    let tronToken = ChainToken(chain: .tronNile, address: tronAddress, symbol: "TKN", name: "Token", decimals: 6, standard: .trc20)181    let tron = TronChainRecord(identity: tronIdentity, network: .nile, address: tronAddress, synchronizedAt: when, blockNumber: 9, balanceSun: 11, isActivated: true, resources: resources,182                               parameters: parameters, holdings: [ChainHolding(token: tronToken, amount: nil, reason: "x", warning: nil, listed: false)], history: nil, historyReason: "x", hasOutgoing: nil, notes: [])183    if let d = try? encoder.encode(tron) { out.append(Bytes("b".utf8) + Bytes(d)) }184    for (letter, network) in [("c", EthereumNetwork.baseSepolia), ("d", .sepolia)] {185        guard let identity = WalletService.ethereumIdentity(w.profile, network: network), let contract = EthereumAddress(bytes: Bytes(repeating: 0xc3, count: 20)) else { continue }186        let info = TokenInfo(network: network, address: contract, symbol: "DET", name: "Detected", decimals: 6, custom: true)187        let history = EthereumHistoryEntry(hash: "0x" + sampleTxid, kind: .token(address: contract.checksummed, symbol: "DET", decimals: 6, verified: true), direction: .received, counterparty: sampleAddress,188                                           amount: UInt256(5), fee: nil, succeeded: true, time: when, blockNumber: 9, id: "x")189        let snapshot = EthereumSnapshot(network: network, address: evmAddress, synchronizedAt: when, blockNumber: 10, balance: UInt256(123), latestNonce: 2, pendingNonce: 3,190                                        tokens: [], detectedTokens: [TokenBalance(token: info, balance: .available(UInt256(9)))], history: .available([history]),191                                        approvals: .available([TokenApproval(token: info, spender: contract, allowance: .max, isUnlimited: true)]), notes: ["n"])192        if let d = try? encoder.encode(EthereumSnapshotRecord(snapshot, identity: identity)) { out.append(Bytes(letter.utf8) + Bytes(d)) }193    }194    return out195}196197func checkAddressSeeds() -> [Bytes] {198    var out = [String]()199    let all = ChainRegistry.all200    func selector(_ index: Int) -> String { String(UnicodeScalar(UInt8(0x61 + index % 26))) + String(UnicodeScalar(UInt8(0x61 + index / 26))) }201    let h = Bytes(repeating: 0x5a, count: 20)202    for (index, chain) in all.enumerated() {203        switch chain.kind {204        case .utxo(let network):205            for script in [try? BitcoinScript.p2pkh(publicKeyHash: h), try? BitcoinScript.p2sh(scriptHash: h), network.supportsSegWit ? try? BitcoinScript.p2wpkh(publicKeyHash: h) : nil].compactMap({ $0 }) {206                if let a = try? BitcoinAddress(scriptPubKey: script, network: network).string { out.append(selector(index) + a) }207            }208        case .evm: out += [selector(index) + sampleAddress, selector(index) + sampleAddress.lowercased(), selector(index) + "0x" + String(repeating: "0", count: 40)]209        case .solana:210            if let key = try? SolanaKeys.publicKey(privateSeed: Bytes(repeating: 9, count: 32)) { out += [selector(index) + key.base58, selector(index) + "11111111111111111111111111111111"] }211        case .tron:212            if let a = TronAddress(hash: h) { out += [selector(index) + a.base58, selector(index) + a.hex, selector(index) + "0x" + Hex.encode(h)] }213        }214    }215    return out.map { Bytes($0.utf8) }216}217218func accountBindingSeeds() -> [Bytes] {219    guard let seed = try? BIP39.seed(mnemonic: BIP39.words(from: abandon)), let data = try? WalletService.publicData(seed: seed) else { return [] }220    let payload = WalletService.AccountBinding(data).encoded221    var out = [payload]222    if var object = (try? JSONSerialization.jsonObject(with: Data(payload))) as? [String: Any] {223        object["version"] = 1224        object["solanaAddress"] = nil225        object["tronAddress"] = nil226        if let d = try? JSONSerialization.data(withJSONObject: object, options: [.sortedKeys]) { out.append(Bytes(d)) }227        object["version"] = 3228        if let d = try? JSONSerialization.data(withJSONObject: object, options: [.sortedKeys]) { out.append(Bytes(d)) }229    }230    return out231}232233/// The coin networks whose persisted synchronization the fuzzer writes, by selector.234let utxoCoinSnapshotNetworks: [BitcoinNetwork] = [.litecoinTestnet, .dogecoinTestnet, .bitcoinCashTestnet]235236/// A record as a synchronization writes it: the first receive address funded once and paid from once, then funded237/// again (unconfirmed); the first change address holding the remainder.238func utxoCoinSnapshotRecord(_ profile: WalletProfile, network: BitcoinNetwork) -> UTXOCoinSyncRecord? {239    guard let identity = WalletService.utxoCoinIdentity(profile, network: network), let data = profile.bitcoinAccounts[WalletService.accountKey(network)],240          let account = try? UTXOAccount(extendedKey: data.extendedPublicKey, network: network),241          let receive = try? account.address(chain: .receive, index: 0), let change = try? account.address(chain: .change, index: 0) else { return nil }242    func out(_ a: BitcoinAddress, _ value: UInt64) -> UTXOCoinSyncRecord.Output { .init(address: a.stringWithoutPrefix, scriptPubKey: Hex.encode(a.scriptPubKey), value: value) }243    let stranger = UTXOCoinSyncRecord.Output(address: nil, scriptPubKey: "76a914" + String(repeating: "77", count: 20) + "88ac", value: 100_000)244    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)245    let fund = UTXOCoinSyncRecord.Transaction(txid: funding, inputs: [.init(txid: source, vout: 0, previous: nil, sequence: 0xffff_fffe)], outputs: [out(receive, 500_000)],246                                              fee: nil, virtualSize: 110, height: 100, time: 1_790_000_000)247    let spend = UTXOCoinSyncRecord.Transaction(txid: spending, inputs: [.init(txid: funding, vout: 0, previous: out(receive, 500_000), sequence: 0xffff_fffe)],248                                               outputs: [stranger, out(change, 399_000)], fee: 1_000, virtualSize: 141, height: 120, time: 1_790_001_000)249    let again = UTXOCoinSyncRecord.Transaction(txid: second, inputs: [.init(txid: source, vout: 1, previous: nil, sequence: nil)], outputs: [out(receive, 70_000)],250                                               fee: nil, virtualSize: nil, height: nil, time: nil)251    let entries = [252        UTXOCoinSyncRecord.Entry(chain: 0, index: 0, address: receive.string, isUsed: true, hasSpent: true, transactionCount: 3, confirmedBalance: 0, isComplete: true,253                                 coins: [.init(txid: second, vout: 0, value: 70_000, height: nil, isCoinbase: false)], transactions: [fund, spend, again], truncated: false),254        UTXOCoinSyncRecord.Entry(chain: 1, index: 0, address: change.string, isUsed: true, hasSpent: false, transactionCount: 1, confirmedBalance: 399_000, isComplete: true,255                                 coins: [.init(txid: spending, vout: 1, value: 399_000, height: 120, isCoinbase: nil)], transactions: [spend], truncated: false),256    ]257    return UTXOCoinSyncRecord(identity: identity, network: network, synchronizedAt: MCFuzzWallet.fixedNow, tipHeight: 130, notes: ["n"], entries: entries)258}259260func utxoCoinSnapshotSeeds() -> [Bytes] {261    guard let w = MCFuzzWallet.shared else { return [] }262    let encoder = JSONEncoder()263    encoder.outputFormatting = [.sortedKeys]264    var out = [Bytes]()265    for (i, network) in utxoCoinSnapshotNetworks.enumerated() {266        guard let record = utxoCoinSnapshotRecord(w.profile, network: network), let d = try? encoder.encode(record) else { continue }267        out.append([UInt8(0x61 + i)] + Bytes(d))268        // the same record with nothing in it, and with one entry only269        var empty = record270        empty.entries = []271        if let d = try? encoder.encode(empty) { out.append([UInt8(0x61 + i)] + Bytes(d)) }272        var one = record273        one.entries = [record.entries[1]]274        if let d = try? encoder.encode(one) { out.append([UInt8(0x61 + i)] + Bytes(d)) }275    }276    return out277}278279func hiddenTokenSeeds() -> [Bytes] {280    guard let w = MCFuzzWallet.shared, let sol = w.profile.solanaAddress, let tron = w.profile.tronAddress else { return [] }281    let evm = "0x" + String(repeating: "c3", count: 20)282    return [283        "sepolia:\(evm)\nsolana-devnet:\(sol)\ntron-nile:\(tron)\n\nasolana-devnet:\(sol)",284        "sepolia:\(evm)\nsepolia:\(evm)\nbaseSepolia:\(evm)\n\nb\(evm)",285        "tron-nile:\(tron)\ntron-nile:\n:\n\nc\(tron)",286        "solana-devnet:\(sol)\n\na\(sol)",287        "\nd",288    ].map { Bytes($0.utf8) }289}290291extension WalletService {292    /// The hidden list as a hostile profile file would give it (the profile is not authenticated: QYV-SVC-011).293    func setHiddenTokensForFuzzing(_ list: [String]) { profile.hiddenTokens = list }294}295296/// A full wallet of its own for the hidden-token target, which changes the profile.297enum HiddenTokenSlot {298    static let service: WalletService? = {299        guard let (service, _, _) = MCFuzzWallet.newService("hidden") else { return nil }300        nonisolated(unsafe) var ready = false301        fuzzAwait {302            do {303                try await service.importWallet(words: BIP39.words(from: abandon), password: "correct horse battery staple 42")304                try await service.setEnabledChains(ChainRegistry.mainChains.map(\.id))305                ready = true306            } catch {}307        }308        return ready ? service : nil309    }()310}311312/// The installation the watch-only target imports into: replaced by a new one each time an import succeeds.313final class WatchOnlySlot: @unchecked Sendable {314    static let shared = WatchOnlySlot()315    private let lock = NSLock()316    private var current: (WalletService, URL)?317318    func empty() -> WalletService? {319        lock.withLock {320            if let current { return current.0 }321            guard let (service, _, dir) = MCFuzzWallet.newService("watch") else { return nil }322            current = (service, dir)323            return service324        }325    }326327    func discard() {328        lock.withLock {329            if let current { try? FileManager.default.removeItem(at: current.1) }330            current = nil331        }332    }333}334335let multichainWalletTargets: [FuzzTarget] = [336    FuzzTarget(337        "cold-envelope", "Cold-mode transaction text on a cold wallet with every chain enabled: the qyvtx1 envelope (Solana, TRON), the 0x02 payload (EVM), a PSBT; review, then signature of what was reviewed",338        maxLength: 3000, text: true,339        dictionary: ["qyvtx1|", "|u|", "|s|", "|", "solana-devnet", "solana-testnet", "solana", "tron-nile", "tron-shasta", "tron", "ethereum-sepolia", "base-sepolia", "bitcoin-signet", "litecoin-testnet", "0x02", "0x",340                     "AAAA", "==", "=", "cHNidP8", "70736274ff", "qyvora1:"],341        seeds: coldEnvelopeSeeds342    ) { input in343        guard let w = MCFuzzWallet.shared else { return }344        let text = fuzzString(input)345        fuzzAwait {346            let review: ColdTransactionReview347            do {348                review = try await w.service.reviewColdTransaction([text])349            } catch {350                FuzzOutcome.note(error: error)351                return352            }353            FuzzOutcome.note("review-" + review.chain.family.rawValue)354            fuzzCheck(review.chain.isTest || MainnetPolicy.mainnetEnabled, "a main network was reviewed while the gate is closed")355            fuzzCheck(!review.summary.isEmpty && review.summary.count <= 400, "summary out of bounds")356            let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)357            let parts = trimmed.split(separator: "|", omittingEmptySubsequences: false).map(String.init)358            let isEnvelope = trimmed.hasPrefix("qyvtx1|")359            if isEnvelope {360                fuzzCheck(parts.count == 4 && parts[1] == "u" && parts[2] == review.chain.id.rawValue, "the envelope does not name the reviewed chain")361            }362            var unsignedBytes = Bytes()363            switch review.body {364            case .solana(let decoded):365                guard isEnvelope, parts.count == 4, let bytes = SolanaBase64.decode(parts[3]), let tx = try? SolanaTransaction.decode(bytes), (try? tx.serialize()) == bytes else { fuzzFail("a Solana review without a canonical Solana payload") }366                fuzzCheck(tx.message.feePayer.base58 == w.profile.solanaAddress && decoded.feePayer == tx.message.feePayer, "a Solana transaction of another account was reviewed")367                if SolanaBase64.encode(bytes) != parts[3] { FuzzOutcome.note("base64-not-canonical") }368                unsignedBytes = tx.message.serialize()369            case .tron(let decoded):370                guard isEnvelope, parts.count == 4, let bytes = Hex.decode(parts[3]), let tx = try? TronTransaction.decode(rawData: bytes), tx.rawData == bytes else { fuzzFail("a TRON review without a canonical TRON payload") }371                fuzzCheck(decoded.owner == nil || decoded.owner?.base58 == w.profile.tronAddress, "a TRON transaction of another account was reviewed")372                unsignedBytes = bytes373            case .evm(let inner):374                fuzzCheck(!isEnvelope && trimmed.hasPrefix("0x") && Hex.decode(String(trimmed.dropFirst(2))) == inner.transaction.unsignedPayload, "what is reviewed is not the canonical encoding of the payload")375                fuzzCheck(inner.transaction.chainID == inner.network.chainID && review.chain.id == ChainRegistry.id(inner.network), "the reviewed network is not the chain identifier of the payload")376                fuzzCheck(inner.transaction.accessList.isEmpty && inner.transaction.to != nil && inner.transaction.maxPriorityFeePerGas <= inner.transaction.maxFeePerGas && inner.transaction.gasLimit <= 200_000,377                          "an EVM transaction outside the supported forms was reviewed")378                unsignedBytes = inner.transaction.unsignedPayload379            case .bitcoin:380                fuzzCheck(!isEnvelope, "an envelope reviewed as a PSBT")381            }382            // the signature: of exactly what was reviewed, by this wallet's account, returned under the same label383            do {384                let signed = try await w.service.signColdTransaction([text])385                FuzzOutcome.note("signed")386                let out = signed.export.text387                switch review.body {388                case .solana:389                    let o = out.split(separator: "|", omittingEmptySubsequences: false).map(String.init)390                    guard o.count == 4, o[0] == "qyvtx1", o[1] == "s", o[2] == review.chain.id.rawValue, let tx = try? SolanaTransaction.decode(base64: o[3]) else { fuzzFail("signed Solana envelope shape") }391                    fuzzCheck(tx.message.serialize() == unsignedBytes && tx.isFullySigned && tx.verifySignatures() && tx.id == signed.id, "the signed Solana transaction is not the reviewed one")392                case .tron:393                    let o = out.split(separator: "|", omittingEmptySubsequences: false).map(String.init)394                    guard o.count == 4, o[0] == "qyvtx1", o[1] == "s", o[2] == review.chain.id.rawValue, let bytes = Hex.decode(o[3]), let tx = try? SignedTronTransaction.decode(bytes) else { fuzzFail("signed TRON envelope shape") }395                    fuzzCheck(tx.transaction.rawData == unsignedBytes && tx.isSignedByOwner && tx.txIDHex == signed.id, "the signed TRON transaction is not the reviewed one")396                case .evm(let inner):397                    guard out.hasPrefix("0x"), let raw = Hex.decode(String(out.dropFirst(2))), let tx = try? SignedEIP1559Transaction.decode(raw) else { fuzzFail("signed EVM payload shape") }398                    fuzzCheck(tx.transaction == inner.transaction && (try? tx.sender()) == w.profile.ethereumAddress && tx.hashHex == signed.id, "the signed EVM transaction is not the reviewed one")399                    fuzzCheck(!inner.warnings.contains(.blindSigning), "undecodable call data was signed without the explicit permission")400                case .bitcoin: break401                }402                fuzzCheck(!review.requiresBlindSigning, "blind signing happened without the explicit permission")403                // the signed text is not signed again and does not review as an unsigned transaction404                if case .bitcoin = review.body {} else {405                    fuzzCheck((try? await w.service.signColdTransaction([out])) == nil, "a signed transaction was signed again")406                }407            } catch {408                FuzzOutcome.note("sign:" + String(describing: error))409            }410        }411    },412413    FuzzTarget(414        "watch-only-v2", "Watch-only package (versions 1 and 2) imported into an empty installation: strict reading, public material only, no wallet left behind an error",415        maxLength: 6000, text: true,416        dictionary: ["\"format\":", "\"qyvora-watch-only\"", "\"version\":", "\"bitcoin\":", "\"network\":", "\"extendedPublicKey\":", "\"masterFingerprint\":", "\"descriptor\":", "\"receiveDescriptor\":", "\"changeDescriptor\":",417                     "\"ethereumAddress\":", "\"solanaAddress\":", "\"tronAddress\":", "\"accounts\":", "\"enabledChains\":", "\"signet\"", "\"testnet\"", "\"mainnet\"", "\"litecoinTestnet\"", "\"dogecoinTestnet\"",418                     "\"bitcoinCashTestnet\"", "\"litecoin\"", "tpub", "xpub", "tprv", "xprv", "vpub", "zpub", "\"solana\"", "\"tron\"", "\"base\"", "null", "1", "2", "3", "[", "]", "{", "}"],419        seeds: watchOnlySeeds420    ) { input in421        guard let service = WatchOnlySlot.shared.empty() else { return }422        let text = fuzzString(input)423        fuzzAwait {424            do {425                try await service.importWatchOnly(package: [text])426            } catch {427                FuzzOutcome.note(error: error)428                let profile = await service.currentProfile()429                fuzzCheck(profile.kind == nil && profile.bitcoinAccounts.isEmpty && profile.ethereumAddress == nil && profile.solanaAddress == nil && profile.tronAddress == nil,430                          "a refused package left a wallet behind: \(String(describing: error))")431                return432            }433            FuzzOutcome.note("imported")434            let profile = await service.currentProfile()435            fuzzCheck(profile.kind == .watchOnly, "an import without error left no watch-only wallet")436            let hasVault = await service.snapshot().vault.exists437            fuzzCheck(!hasVault, "a watch-only import created a vault")438            fuzzCheck(profile.solanaAddress.map { SolanaPublicKey(base58: $0) != nil } ?? true, "a malformed Solana address was stored")439            fuzzCheck(profile.tronAddress.map { TronAddress($0) != nil } ?? true, "a malformed TRON address was stored")440            fuzzCheck(profile.ethereumAddress.map { !$0.isZero } ?? true, "the zero address is watched")441            for (key, account) in profile.bitcoinAccounts {442                guard let parsed = try? ExtendedKey.parse(account.extendedPublicKey) else { fuzzFail("a malformed account key was stored") }443                fuzzCheck(!parsed.version.isPrivate && parsed.key.privateKey == nil, "a private account key was stored")444                fuzzCheck(key == "test" || key == "main" || BitcoinNetwork(rawValue: key) != nil, "an account under an unknown name")445                fuzzCheck(key == "test" || (BitcoinNetwork(rawValue: key)?.isTest ?? false) || MainnetPolicy.mainnetEnabled, "a main-network account was imported while the gate is closed")446            }447            let mains = Set(ChainRegistry.mainChains.map(\.id))448            fuzzCheck(!profile.enabledChains.isEmpty && Set(profile.enabledChains).isSubset(of: mains), "the enabled list is not a list of main chains")449            for id in profile.enabledChains {450                guard let descriptor = ChainRegistry.descriptor(id) else { continue }451                let has: Bool452                switch descriptor.family {453                case .utxo: has = !profile.bitcoinAccounts.isEmpty454                case .evm: has = profile.ethereumAddress != nil455                case .solana: has = profile.solanaAddress != nil456                case .tron: has = profile.tronAddress != nil457                }458                fuzzCheck(has, "\(id) is enabled without an account of its family")459            }460            fuzzCheck(profile.bitcoinNetwork.isTest && profile.ethereumNetwork.isTest || MainnetPolicy.mainnetEnabled, "an import moved the wallet to a main network")461            let chains = await service.chainSnapshots()462            fuzzUse(chains.count)463            WatchOnlySlot.shared.discard()464        }465    },466467    FuzzTarget(468        "chain-snapshot", "Persisted chain snapshots (Solana, TRON, EVM) written by a hostile hand and read back through the service's own loaders",469        maxLength: 6000, text: true,470        dictionary: ["\"version\":", "\"identity\":", "\"network\":", "\"address\":", "\"lamports\":", "\"balanceSun\":", "\"balance\":", "\"holdings\":", "\"history\":", "\"notes\":", "\"decimals\":", "\"chain\":",471                     "\"latestNonce\":", "\"pendingNonce\":", "\"detectedTokens\":", "\"tokens\":", "\"state\":", "\"available\"", "\"devnet\"", "\"mainnet-beta\"", "\"nile\"", "\"mainnet\"", "\"baseSepolia\"", "\"base\"",472                     "18446744073709551615", "9223372036854775808", "-1", "1e999", "256", "37", "null", "[", "]", "{", "}"],473        seeds: chainSnapshotSeeds474    ) { input in475        guard let w = MCFuzzWallet.shared, let selector = input.first else { return }476        let body = Bytes(input.dropFirst())477        let profile = w.profile478        func bounded(_ data: ChainData) {479            fuzzCheck(data.isFromPreviousSession, "a restored snapshot is not flagged as coming from a previous session")480            fuzzCheck(data.tokens.count + data.detectedTokens.count <= 2_400 && data.notes.count <= 60 && (data.history.value?.count ?? 0) <= 20_000, "a restored snapshot is out of bounds")481            fuzzCheck((data.tokens + data.detectedTokens).allSatisfy { (0...255).contains($0.token.decimals) }, "token decimals out of range")482            fuzzUse(String(describing: data).utf8.count)483        }484        switch fuzzSelector(selector, 4) {485        case 0:486            let name = SolanaChainRecord.fileName(.devnet)487            guard (try? w.store.write(body, to: name, keepPrevious: false)) != nil else { return }488            if let r = WalletService.restoredSolana(fileStore: w.store, profile: profile, network: .devnet) {489                FuzzOutcome.note("solana")490                fuzzCheck(r.address == profile.solanaAddress && r.network == .devnet && r.identity == WalletService.solanaIdentity(profile, network: .devnet), "a Solana snapshot of another account or network was restored")491                fuzzCheck(r.holdings.count <= 1_200 && (r.history?.count ?? 0) <= 500 && r.holdings.allSatisfy { $0.token.chain == .solanaDevnet }, "Solana snapshot bounds")492                bounded(WalletService.chainData(r))493            } else {494                fuzzCheck(!w.store.exists(name), "a refused Solana snapshot was left on disk")495            }496        case 1:497            let name = TronChainRecord.fileName(.nile)498            guard (try? w.store.write(body, to: name, keepPrevious: false)) != nil else { return }499            if let r = WalletService.restoredTron(fileStore: w.store, profile: profile, network: .nile) {500                FuzzOutcome.note("tron")501                fuzzCheck(r.address == profile.tronAddress && r.network == .nile && r.balanceSun <= UInt64(Int64.max), "a TRON snapshot of another account or network, or out of range, was restored")502                fuzzCheck(r.holdings.count <= 200 && (r.history?.count ?? 0) <= 500 && r.holdings.allSatisfy { $0.token.chain == .tronNile && $0.token.decimals <= 77 }, "TRON snapshot bounds")503                bounded(WalletService.chainData(r))504            } else {505                fuzzCheck(!w.store.exists(name), "a refused TRON snapshot was left on disk")506            }507        default:508            let network: EthereumNetwork = fuzzSelector(selector, 4) == 2 ? .baseSepolia : .sepolia509            let name = EthereumSnapshotRecord.fileName(for: network)510            guard (try? w.store.write(body, to: name, keepPrevious: false)) != nil else { return }511            if let s = WalletService.restoredEthereum(fileStore: w.store, profile: profile, network: network) {512                FuzzOutcome.note("evm")513                fuzzCheck(s.address == profile.ethereumAddress && s.network == network && s.isFromPreviousSession && s.pendingNonce >= s.latestNonce && s.pendingNonce - s.latestNonce <= 10_000,514                          "an EVM snapshot of another account or network, or out of range, was restored")515                fuzzCheck((s.tokens + s.detectedTokens).allSatisfy { (0...36).contains($0.token.decimals) && $0.token.network == network && !$0.token.address.isZero }, "EVM snapshot token bounds")516                bounded(WalletService.chainData(s))517            } else {518                fuzzCheck(!w.store.exists(name), "a refused EVM snapshot was left on disk")519            }520        }521    },522523    FuzzTarget(524        "check-address", "Address validation of every network of every family on arbitrary text: canonical form, own-address detection, and no text valid for two families",525        maxLength: 200, text: true,526        dictionary: ["0x", "0X", "bitcoincash:", "bchtest:", "bc1q", "tb1q", "ltc1q", "tltc1q", "bc1p", "T", "41", "1", "3", "D", "L", "M", "n", "m", "2", "q", "p", "11111111111111111111111111111111", " ", "\n"],527        seeds: checkAddressSeeds528    ) { input in529        guard let w = MCFuzzWallet.shared, input.count >= 2 else { return }530        let all = ChainRegistry.all531        let chain = all[(fuzzSelector(input[0], 26) + 26 * fuzzSelector(input[1], 2)) % all.count]532        let text = fuzzString(Bytes(input.dropFirst(2)))533        fuzzAwait {534            let check: AddressCheck535            do {536                check = try await w.service.checkAddress(text, chain: chain.id)537            } catch let error as WalletError {538                guard case .address(let refusal) = error else { fuzzFail("address validation failed with \(error)") }539                FuzzOutcome.note(String(describing: refusal))540                fuzzUse(WalletMessages.text(for: error).utf8.count)541                return542            } catch {543                fuzzFail("address validation threw \(error)")544            }545            FuzzOutcome.note("valid-" + chain.family.rawValue)546            fuzzCheck(check.chain == chain.id && !check.canonical.isEmpty && check.canonical.utf8.count <= 120 && check.notes.count <= 6, "address check out of bounds")547            // the canonical form is itself valid, as the same address548            let again = try? await w.service.checkAddress(check.canonical, chain: chain.id)549            fuzzCheck(again?.canonical == check.canonical && again?.isOwnAddress == check.isOwnAddress, "the canonical form is not stable")550            // no other family takes the same text551            for other in [ChainID.bitcoinSignet, .bitcoin, .litecoin, .dogecoin, .bitcoinCash, .ethereumSepolia, .solanaDevnet, .tronNile] {552                guard let descriptor = ChainRegistry.descriptor(other), descriptor.family != chain.family else { continue }553                let elsewhere = try? await w.service.checkAddress(text, chain: other)554                fuzzCheck(elsewhere == nil, "\(text) is valid on \(chain.id) and on \(other)")555            }556            switch chain.kind {557            case .evm:558                guard let address = EthereumAddress(check.canonical) else { fuzzFail("the canonical EVM form does not parse") }559                fuzzCheck(address.checksummed == check.canonical && !address.isZero && check.isOwnAddress == (address == w.profile.ethereumAddress), "EVM canonical form")560            case .solana:561                fuzzCheck(SolanaPublicKey(base58: check.canonical) != nil && check.isOwnAddress == (check.canonical == w.profile.solanaAddress) && !check.notes.isEmpty, "Solana canonical form")562            case .tron:563                fuzzCheck(TronAddress(check.canonical) != nil && check.isOwnAddress == (check.canonical == w.profile.tronAddress), "TRON canonical form")564            case .utxo(let network):565                guard let address = try? BitcoinAddress(check.canonical, network: network) else { fuzzFail("the canonical UTXO form does not parse on its network") }566                fuzzCheck(address.type != .witnessUnknown, "an address of an unassigned witness version was accepted")567            }568        }569    },570571    FuzzTarget(572        "account-binding-v2", "Account binding record of the vault (versions 1 and 2): strict reading, round trip, well-formed addresses only",573        maxLength: 4096, text: true,574        dictionary: ["\"format\":", "\"qyvora-account-binding\"", "\"version\":", "\"bitcoinAccounts\":", "\"ethereumAddress\":", "\"solanaAddress\":", "\"tronAddress\":", "\"extendedPublicKey\":", "\"masterFingerprint\":",575                     "\"test\"", "\"main\"", "\"litecoinTestnet\"", "tpub", "xpub", "tprv", "1", "2", "3", "null", "{", "}"],576        seeds: accountBindingSeeds577    ) { input in578        guard let data = WalletService.AccountBinding.decode(input) else {579            FuzzOutcome.note("refused")580            return581        }582        FuzzOutcome.note(data.isComplete ? "complete" : "partial")583        fuzzCheck(input.count <= WalletService.AccountBinding.maximumBytes, "an oversized record was read")584        fuzzCheck(data.solana.map { SolanaPublicKey(base58: $0)?.base58 == $0 } ?? true, "a Solana address that is not canonical came out of the record")585        fuzzCheck(data.tron.map { TronAddress($0)?.base58 == $0 } ?? true, "a TRON address that is not canonical came out of the record")586        // what was read is written back and read again as the same value587        let again = WalletService.AccountBinding(data).encoded588        fuzzCheck(WalletService.AccountBinding.decode(again) == data, "the record does not survive a round trip")589        var profile = WalletProfile()590        profile.apply(data)591        fuzzCheck(profile.publicData == data, "applying the record to a profile changes it")592        fuzzUse(String(decoding: again, as: UTF8.self).contains("\"" + WalletService.AccountBinding.format + "\""))593    },594595    FuzzTarget(596        "utxo-coin-snapshot", "Persisted synchronization of a UTXO coin (Litecoin, Dogecoin, Bitcoin Cash) written by a hostile hand and read back through the service's own loader",597        maxLength: 6000, text: true,598        dictionary: ["\"version\":", "\"identity\":", "\"network\":", "\"synchronizedAt\":", "\"tipHeight\":", "\"notes\":", "\"entries\":", "\"chain\":", "\"index\":", "\"address\":", "\"isUsed\":",599                     "\"hasSpent\":", "\"transactionCount\":", "\"confirmedBalance\":", "\"isComplete\":", "\"coins\":", "\"transactions\":", "\"truncated\":", "\"txid\":", "\"vout\":", "\"value\":",600                     "\"height\":", "\"isCoinbase\":", "\"inputs\":", "\"outputs\":", "\"previous\":", "\"sequence\":", "\"scriptPubKey\":", "\"fee\":", "\"virtualSize\":", "\"time\":",601                     "\"litecoinTestnet\"", "\"dogecoinTestnet\"", "\"bitcoinCashTestnet\"", "\"litecoin\"", "true", "false", "null", "18446744073709551615", "9223372036854775808", "4294967295",602                     "100000000", "8400000000000000", "-1", "1e999", "[", "]", "{", "}"],603        seeds: utxoCoinSnapshotSeeds604    ) { input in605        guard let w = MCFuzzWallet.shared, let selector = input.first else { return }606        let network = utxoCoinSnapshotNetworks[fuzzSelector(selector, utxoCoinSnapshotNetworks.count)]607        let name = UTXOCoinSyncRecord.fileName(network)608        guard (try? w.store.write(Bytes(input.dropFirst()), to: name, keepPrevious: false)) != nil else { return }609        guard let state = WalletService.restoredUTXOCoin(fileStore: w.store, profile: w.profile, network: network) else {610            FuzzOutcome.note("refused")611            fuzzCheck(!w.store.exists(name), "a refused coin record was left on disk")612            return613        }614        guard let s = state.snapshot else { fuzzFail("a restored coin state without a snapshot") }615        FuzzOutcome.note("restored-" + network.rawValue)616        // what is restored is shown, never spent from: it is flagged, and nothing else of the state comes from the file617        fuzzCheck(s.isFromPreviousSession && s.network == network, "a restored coin snapshot is not flagged, or is of another network")618        fuzzCheck(state.paidScripts.isEmpty && state.locallySpent.isEmpty && state.error == nil, "a restored coin state carries more than its snapshot")619        let maximum = network.maximumMoney620        fuzzCheck(s.tipHeight < 100_000_000 && s.notes.count <= 4_100 && s.addresses.count <= 2 * Int(WalletService.maximumScanIndex), "restored coin snapshot out of bounds")621        fuzzCheck(s.balance.confirmed <= maximum && s.balance.pending <= maximum, "restored balance beyond the monetary range")622        var total: UInt64 = 0623        var seen = Set<BitcoinOutPoint>()624        guard let data = w.profile.bitcoinAccounts[WalletService.accountKey(network)], let account = try? UTXOAccount(extendedKey: data.extendedPublicKey, network: network) else {625            fuzzFail("no account for a restored coin snapshot")626        }627        for u in s.utxos {628            fuzzCheck(u.utxo.value > 0 && u.utxo.value <= maximum && seen.insert(u.utxo.outPoint).inserted, "a restored coin is out of range or listed twice")629            total += u.utxo.value630            // every coin sits on an address derived from the account again, at the position the record gave631            guard let d = u.utxo.derivation, let chain = UTXOAccount.Chain(rawValue: d.chain) else { fuzzFail("a restored coin without a position") }632            fuzzCheck((try? account.scriptPubKey(chain: chain, index: d.index)) == u.utxo.scriptPubKey, "a restored coin is not on an address of the account")633        }634        fuzzCheck(total <= maximum && s.balance.confirmed + s.balance.pending == total, "the restored balance is not the sum of the restored coins")635        for a in s.addresses { fuzzCheck((try? BitcoinAddress(a.address, network: network)) != nil, "a restored address is not an address of the network") }636        let chain = WalletService.chainData(s)637        fuzzCheck(chain.isFromPreviousSession, "the uniform view of a restored coin snapshot is not flagged")638        fuzzUse(String(describing: chain).utf8.count)639    },640641    FuzzTarget(642        "hidden-tokens", "The hidden-token list of a hostile profile, listed and shown again: bounded, no network, no change to the token lists",643        maxLength: 3000, text: true,644        dictionary: ["sepolia:", "baseSepolia:", "solana-devnet:", "tron-nile:", "solana:", "tron:", "mainnet:", "0x", ":", "\n", "\n\n", "a", "b", "c", "d"],645        seeds: hiddenTokenSeeds646    ) { input in647        // text: the hidden list, one entry per line; an empty line; then a selector letter and the address to show again648        let text = fuzzString(input)649        let parts = text.components(separatedBy: "\n\n")650        let hidden = parts[0].split(separator: "\n", omittingEmptySubsequences: false).map(String.init)651        guard hidden.count <= 200, let slot = HiddenTokenSlot.service else { return }652        let request = parts.count > 1 ? parts[1] : ""653        let chains: [ChainID] = [.solanaDevnet, .ethereumSepolia, .tronNile, .baseSepolia, .bitcoinSignet, .solana]654        let chain = chains[fuzzSelector(request.utf8.first ?? 0x61, chains.count)]655        let address = String(request.dropFirst())656        fuzzAwait {657            await slot.setHiddenTokensForFuzzing(hidden)658            let before = await slot.currentProfile()659            var listedTotal = 0660            for id in chains {661                let listed = await slot.hiddenTokens(chain: id)662                listedTotal += listed.count663                fuzzCheck(listed.count <= hidden.count && listed.allSatisfy { $0.chain == id }, "more hidden tokens listed than stored, or of another chain")664                // a token is described from the wallet's own list only665                fuzzCheck(listed.allSatisfy { $0.token == nil || $0.token?.chain == id }, "a hidden token described as a token of another chain")666            }667            fuzzCheck(listedTotal <= hidden.count, "an entry of the hidden list is listed on two chains")668            do {669                try await slot.showHiddenToken(HiddenToken(chain: chain, address: address, token: ChainToken(chain: chain, address: address, symbol: "LIE", name: "Lie", decimals: 0, standard: .erc20)))670            } catch let error as WalletError {671                FuzzOutcome.note(String(String(describing: error).prefix(24)))672            } catch {673                fuzzFail("showHiddenToken threw \(error)")674            }675            let after = await slot.currentProfile()676            fuzzCheck(after.customTokens == before.customTokens && after.customSolanaTokens == before.customSolanaTokens && after.customTronTokens == before.customTronTokens,677                      "showing a hidden token changed a token list")678            fuzzCheck(Set(after.hiddenTokens).isSubset(of: Set(before.hiddenTokens)), "showing a hidden token added to the hidden list")679            let gone = Set(before.hiddenTokens).subtracting(after.hiddenTokens)680            if !gone.isEmpty {681                FuzzOutcome.note("shown")682                fuzzCheck(gone.count == 1 && gone.allSatisfy { $0.hasSuffix(":" + address) }, "showing one token removed another entry")683            }684        }685    },686]687
Files main
Menu

Theme