SPB Git

Repository Public

MultichainWalletProperties.swift 67.4 KB 853 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : security/tests/Tests/PropertyAuditTests/MultichainWalletProperties.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 QyvoraEthereum46import QyvoraMath47import QyvoraNetworking48import QyvoraSolana49import QyvoraStorage50import QyvoraTron51import QyvoraVault52import Testing5354@testable import QyvoraWallet5556// The machinery every chain family goes through in the wallet service: address validation, the cold-mode envelope,57// the watch-only package, the account binding kept in the vault, and the files that keep the last synchronization.58// One wallet on the BIP-39 test phrase, a temporary directory, a transport that refuses every request: nothing59// reaches the network and no real funds exist.6061/// A transport that never answers and counts what was asked of it.62final class MCDeadTransport: HTTPTransport, @unchecked Sendable {63    private let lock = NSLock()64    private var count = 065    var requests: Int { lock.withLock { count } }66    func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) {67        lock.withLock { count += 1 }68        throw URLError(.notConnectedToInternet)69    }70}7172struct MCWallet {73    static let phrase = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about".split(separator: " ").map(String.init)74    static let password = "correct horse battery staple 42"7576    let service: WalletService77    let store: FileStore78    let directory: URL79    let transport: MCDeadTransport8081    /// A service on a new directory; `full` imports the test phrase and enables every chain.82    static func make(full: Bool = true, directory: URL? = nil) async throws -> MCWallet {83        let dir = directory ?? FileManager.default.temporaryDirectory.appendingPathComponent("qy-mc-prop-\(UUID().uuidString)")84        let store = try FileStore(root: dir)85        let vault = Vault(fileStore: store, keychain: InMemoryKeychainStore(), configuration: .init(kdf: .insecureForTesting))86        let transport = MCDeadTransport()87        let service = try WalletService(vault: vault, fileStore: store, transport: transport, sleep: { _ in }, transactionSeed: 7, backupKDF: .insecureForTesting, tronPacing: .unthrottled)88        if full, directory == nil {89            try await service.importWallet(words: phrase, password: password)90            try await service.setEnabledChains(ChainRegistry.mainChains.map(\.id))91        }92        return MCWallet(service: service, store: store, directory: dir, transport: transport)93    }9495    func cleanup() { try? FileManager.default.removeItem(at: directory) }9697    static func error<T>(_ body: () async throws -> T) async -> WalletError? {98        do {99            _ = try await body()100            return nil101        } catch let e as WalletError {102            return e103        } catch {104            return .invalidInput("not a WalletError: \(error)")105        }106    }107}108109@Suite struct MultichainAddressProperties {110    /// A valid address of each UTXO network, of each form the network has.111    static func utxoAddresses(_ rng: inout AuditRNG, _ network: BitcoinNetwork) -> [String] {112        let h = rng.bytes(20)113        var scripts = [try? BitcoinScript.p2pkh(publicKeyHash: h), try? BitcoinScript.p2sh(scriptHash: h)]114        if network.supportsSegWit { scripts.append(try? BitcoinScript.p2wpkh(publicKeyHash: h)) }115        return scripts.compactMap { $0 }.compactMap { try? BitcoinAddress(scriptPubKey: $0, network: network).string }116    }117118    @Test func noAddressIsValidForAnotherFamily() async throws {119        let seed = AuditSeed.make("mc.check-address")120        var rng = AuditRNG(seed: seed)121        var prop = Prop("an address of one family is refused by name on every chain of another family; accepted in its canonical form on its own network; never a trap", algorithm: "checkAddress", parameterSet: "\(ChainRegistry.all.count) networks × addresses of 4 families", seed: seed)122        let w = try await MCWallet.make()123        defer { w.cleanup() }124        var crossTestCoins = 0125        for _ in 0..<AuditMode.cases(quick: 2, full: 60) {126            var samples = [(family: ChainFamily, network: BitcoinNetwork?, text: String, canonical: String)]()127            let evm = EthereumAddress(bytes: rng.bytes(20))!128            samples.append((.evm, nil, evm.checksummed, evm.checksummed))129            samples.append((.evm, nil, evm.checksummed.lowercased(), evm.checksummed))130            samples.append((.evm, nil, "0x" + evm.checksummed.dropFirst(2).uppercased(), evm.checksummed))131            if let tron = TronAddress(hash: rng.bytes(20)) { samples.append((.tron, nil, tron.base58, tron.base58)) }132            if let sol = try? SolanaKeys.publicKey(privateSeed: rng.bytes(32)) { samples.append((.solana, nil, sol.base58, sol.base58)) }133            if let pda = SolanaPublicKey(bytes: rng.bytes(32)) { samples.append((.solana, nil, pda.base58, pda.base58)) }134            for network in BitcoinNetwork.allCases { for a in Self.utxoAddresses(&rng, network) { samples.append((.utxo, network, a, a)) } }135136            for sample in samples {137                for chain in ChainRegistry.all {138                    var result: AddressCheck?139                    var refusal: WalletError?140                    do { result = try await w.service.checkAddress(sample.text, chain: chain.id) } catch { refusal = error }141                    if chain.family != sample.family {142                        prop.check(result == nil, "\(sample.family) address \(sample.text) accepted on \(chain.id)")143                        if case .address(.wrongFamily)? = refusal { prop.check(true) } else {144                            // a text that is nothing recognisable on that chain may be "malformed"; it must still be an address refusal145                            if case .address? = refusal { prop.check(true) } else { prop.check(false, "\(sample.text) on \(chain.id): \(String(describing: refusal))") }146                        }147                        continue148                    }149                    switch chain.kind {150                    case .evm, .solana, .tron:151                        prop.check(result?.canonical == sample.canonical && result?.chain == chain.id && result?.isOwnAddress == false, "\(sample.text) on \(chain.id): \(String(describing: refusal))")152                        if case .evm = chain.kind {153                            let mixed = sample.text == sample.canonical && sample.text.dropFirst(2).contains(where: \.isLowercase) && sample.text.dropFirst(2).contains(where: \.isUppercase)154                            prop.check(mixed || !(result?.notes.isEmpty ?? true), "an EVM address without checksum carries no note")155                        }156                        if case .solana = chain.kind { prop.check(result?.notes.contains { $0.contains("no checksum") } == true, "the Solana note about the missing checksum") }157                    case .utxo(let network):158                        guard let origin = sample.network else { continue }159                        if network == origin {160                            // Bitcoin Cash shows CashAddr: the Base58 form made here is accepted with the legacy note161                            prop.check(result != nil && (result?.canonical == sample.canonical || network.cashAddrPrefix != nil), "\(sample.text) refused on its own network \(chain.id): \(String(describing: refusal))")162                        } else if result != nil {163                            if !network.isTest || !origin.isTest {164                                // across coins on a main network: only the Base58 form Bitcoin and Bitcoin Cash share, and then with a note165                                let shared = Set([network.coin, origin.coin]) == Set([UTXOCoin.bitcoin, .bitcoinCash]) && network.isTest == origin.isTest166                                prop.check(shared && (network.coin != .bitcoinCash || result?.notes.contains { $0.contains("legacy form") } == true),167                                           "\(origin) address \(sample.text) accepted on \(chain.id) without the shared-format note")168                            } else {169                                // test networks share version bytes (0x6f, 0xc4) or a prefix (tb1): the same text is an address of several test coins170                                crossTestCoins += 1171                                prop.check(true)172                            }173                        } else {174                            if case .address? = refusal { prop.check(true) } else { prop.check(false, "\(sample.text) on \(chain.id): \(String(describing: refusal))") }175                        }176                    }177                }178            }179            // an EVM address with one letter of the wrong case is a checksum failure, on every EVM network180            let text = evm.checksummed181            if let index = text.indices.dropFirst(2).first(where: { text[$0].isLetter }) {182                var flipped = text183                let c = text[index]184                flipped.replaceSubrange(index...index, with: c.isUppercase ? c.lowercased() : c.uppercased())185                let stillMixed = flipped.dropFirst(2).contains(where: \.isLowercase) && flipped.dropFirst(2).contains(where: \.isUppercase)186                if stillMixed {187                    let refusal = await MCWallet.error { try await w.service.checkAddress(flipped, chain: .ethereumSepolia) }188                    prop.check(refusal == .address(.invalidChecksum(chain: "Ethereum Sepolia")), "a wrong EIP-55 checksum gave \(String(describing: refusal))")189                }190            }191        }192        // fixed refusals: zero addresses, hexadecimal TRON form, an EVM address on TRON and the reverse, empty, too long193        let zeroEVM = "0x" + String(repeating: "0", count: 40)194        prop.check(await MCWallet.error { try await w.service.checkAddress(zeroEVM, chain: .baseSepolia) } == .address(.zeroAddress), "zero EVM address")195        prop.check(await MCWallet.error { try await w.service.checkAddress("", chain: .tronNile) } == .address(.empty), "empty text")196        prop.check(await MCWallet.error { try await w.service.checkAddress("   \n", chain: .solanaDevnet) } == .address(.empty), "blank text")197        if case .address(.malformed)? = await MCWallet.error({ try await w.service.checkAddress(String(repeating: "1", count: 121), chain: .bitcoinSignet) }) { prop.check(true) } else { prop.check(false, "a text of 121 characters") }198        prop.check(await MCWallet.error { try await w.service.checkAddress("x", chain: ChainID("no-such-chain")) } == .unknownChain("no-such-chain"), "unknown chain")199        let tronOfEVM = TronAddress(evm: EthereumAddress(bytes: Bytes(repeating: 0x11, count: 20))!)200        if case .address(.wrongFamily(_, let found))? = await MCWallet.error({ try await w.service.checkAddress("0x" + String(repeating: "11", count: 20), chain: .tronNile) }) {201            prop.check(found.contains("Ethereum"), "an EVM address on TRON is named")202        } else { prop.check(false, "an EVM address on TRON") }203        if case .address(.wrongFamily(_, let found))? = await MCWallet.error({ try await w.service.checkAddress(tronOfEVM.base58, chain: .ethereumSepolia) }) {204            prop.check(found.contains("TRON"), "a TRON address on an EVM network is named")205        } else { prop.check(false, "a TRON address on an EVM network") }206        if case .address(.unsupported)? = await MCWallet.error({ try await w.service.checkAddress(tronOfEVM.hex, chain: .tronNile) }) { prop.check(true) } else { prop.check(false, "the hexadecimal form of a TRON address") }207        // the wallet's own addresses are recognised on every family208        let profile = await w.service.currentProfile()209        prop.check((try? await w.service.checkAddress(profile.ethereumAddress?.checksummed ?? "", chain: .polygonAmoy))?.isOwnAddress == true, "own EVM address")210        prop.check((try? await w.service.checkAddress(profile.solanaAddress ?? "", chain: .solanaDevnet))?.isOwnAddress == true, "own Solana address")211        prop.check((try? await w.service.checkAddress(profile.tronAddress ?? "", chain: .tronNile))?.isOwnAddress == true, "own TRON address")212213        // arbitrary text on every chain: an answer or a refusal, never a trap, and never "valid" without a canonical form214        let alphabet = Array("0123456789abcdefABCDEFxXTtbc1qlmn:._- \n\u{00e9}\u{202e}\u{0000}zZ")215        var accepted = 0216        for _ in 0..<AuditMode.cases(quick: 80, full: 4_000) {217            let text: String218            switch rng.int(0...4) {219            case 0: text = String((0..<rng.int(0...130)).map { _ in rng.pick(alphabet) })220            case 1: text = "0x" + Hex.encode(rng.bytes(rng.int(0...24)))221            case 2: text = Base58.bitcoin.encode(rng.bytes(rng.pick([20, 21, 25, 32, 33, 64])))222            case 3: text = rng.pick(["bitcoincash:", "bchtest:", "bc1", "tb1", "ltc1", "tltc1", "T", "0X"]) + String((0..<rng.int(0...60)).map { _ in rng.pick(alphabet) })223            default: text = String(decoding: rng.bytes(rng.int(0...140)), as: UTF8.self)224            }225            for chain in ChainRegistry.all {226                if let check = try? await w.service.checkAddress(text, chain: chain.id) {227                    accepted += 1228                    prop.check(!check.canonical.isEmpty && check.canonical.utf8.count <= 120 && check.chain == chain.id, "accepted without a canonical form: \(text)")229                    // what was accepted is accepted again in its canonical form, as the same address230                    let again = try? await w.service.checkAddress(check.canonical, chain: chain.id)231                    prop.check(again?.canonical == check.canonical, "the canonical form \(check.canonical) is not stable on \(chain.id)")232                } else {233                    prop.check(true)234                }235            }236        }237        prop.check(w.transport.requests == 0, "address validation reached the network")238        prop.finish(note: "\(accepted) random texts accepted; \(crossTestCoins) addresses of one test coin accepted on another test coin (shared version bytes, test networks only)")239    }240}241242@Suite struct MultichainColdEnvelopeProperties {243    static func solanaPayload(owner: SolanaPublicKey, to: SolanaPublicKey, lamports: UInt64, blockhash: Bytes) throws -> String {244        try SolanaTransaction(message: SolanaMessage(feePayer: owner, instructions: [SolanaSystemProgram.transfer(from: owner, to: to, lamports: lamports)], recentBlockhash: blockhash)).base64()245    }246247    static func tronPayload(owner: TronAddress, to: TronAddress, sun: UInt64, now: Date) throws -> String {248        let number: UInt64 = 60_000_000249        let reference = try #require(TronBlockReference(number: number, id: Endian.be64(number) + Bytes(repeating: 0xab, count: 24), timestamp: UInt64(now.timeIntervalSince1970 * 1000)))250        let ms = UInt64(now.timeIntervalSince1970 * 1000)251        return Hex.encode(try TronTransaction.transfer(from: owner, to: to, amountSun: sun, reference: reference, timestamp: ms, expiration: ms + 1_800_000).rawData)252    }253254    @Test func theEnvelopeBindsFamilyNetworkAndPayload() async throws {255        let seed = AuditSeed.make("mc.cold-envelope")256        var rng = AuditRNG(seed: seed)257        var prop = Prop("qyvtx1|u/s|<chain>|<payload>: exactly four parts, a known and active chain, a canonical payload of that family signed by this account; the review is decoded from the payload", algorithm: "Cold-mode envelope", seed: seed)258        let w = try await MCWallet.make()259        defer { w.cleanup() }260        try await w.service.setColdMode(true)261        let profile = await w.service.currentProfile()262        let me = try #require(SolanaPublicKey(base58: profile.solanaAddress ?? "")), tronMe = try #require(TronAddress(profile.tronAddress ?? ""))263        let stranger = try SolanaKeys.publicKey(privateSeed: Bytes(repeating: 9, count: 32)), tronStranger = try #require(TronAddress(hash: Bytes(repeating: 0x33, count: 20)))264        let policyClosed = !MainnetPolicy.mainnetEnabled265266        for _ in 0..<AuditMode.cases(quick: 40, full: 400) {267            let lamports = UInt64(rng.int(1...2_000_000_000)), sun = UInt64(rng.int(1...5_000_000_000))268            let sol = try Self.solanaPayload(owner: me, to: stranger, lamports: lamports, blockhash: rng.bytes(32))269            let trx = try Self.tronPayload(owner: tronMe, to: tronStranger, sun: sun, now: Date())270271            // the right label: reviewed from the bytes272            let solReview = try? await w.service.reviewColdTransaction(["qyvtx1|u|solana-devnet|\(sol)"])273            prop.check(solReview?.chain.id == .solanaDevnet && solReview?.requiresBlindSigning == false, "a devnet transfer is not reviewed")274            if case .solana(let decoded)? = solReview?.body {275                prop.check(decoded.instructions.contains(.systemTransfer(from: me, to: stranger, lamports: lamports)), "the amount shown is not the amount in the payload")276            } else { prop.check(false, "no Solana body") }277            let trxReview = try? await w.service.reviewColdTransaction(["qyvtx1|u|tron-nile|\(trx)"])278            prop.check(trxReview?.chain.id == .tronNile, "a Nile transfer is not reviewed")279            if case .tron(let decoded)? = trxReview?.body, case .trxTransfer(_, let to, let amount) = decoded.action {280                prop.check(to == tronStranger && amount == sun, "the TRON amount shown is not the amount in the payload")281            } else { prop.check(false, "no TRON transfer body") }282283            // the wrong family, another network of the family, another family's label, a main network, an unknown label284            for (label, payload) in [("tron-nile", sol), ("solana-devnet", trx), ("ethereum-sepolia", sol), ("ethereum-sepolia", trx), ("bitcoin-signet", sol), ("litecoin-testnet", trx)] {285                if case .invalidPayload? = await MCWallet.error({ try await w.service.reviewColdTransaction(["qyvtx1|u|\(label)|\(payload)"]) }) { prop.check(true) } else { prop.check(false, "a payload under the label \(label) was not refused as invalid") }286                if case .invalidPayload? = await MCWallet.error({ try await w.service.signColdTransaction(["qyvtx1|u|\(label)|\(payload)"]) }) { prop.check(true) } else { prop.check(false, "a payload under the label \(label) was signed or refused for another reason") }287            }288            for (label, payload) in [("solana-testnet", sol), ("tron-shasta", trx)] {289                if case .chainNotActive? = await MCWallet.error({ try await w.service.signColdTransaction(["qyvtx1|u|\(label)|\(payload)"]) }) { prop.check(true) } else { prop.check(false, "\(label) is not the active test network") }290            }291            if policyClosed, !MainnetPolicy.mainnetEnabled {292                for (label, payload) in [("solana", sol), ("tron", trx)] {293                    let refusal = await MCWallet.error { try await w.service.signColdTransaction(["qyvtx1|u|\(label)|\(payload)"]) }294                    prop.check(refusal == .mainnetDisabled(WalletError.mainnetText) || MainnetPolicy.mainnetEnabled, "a main-network label was not refused by the gate: \(String(describing: refusal))")295                }296            }297            for label in ["", "solana-", "Solana-Devnet", "solana-devnet ", " solana-devnet", "solana-devnet\u{0000}", "../solana-devnet", "evm-sepolia", "utxo-signet"] {298                let refusal = await MCWallet.error { try await w.service.reviewColdTransaction(["qyvtx1|u|\(label)|\(sol)"]) }299                prop.check(refusal == .unknownChain(label), "label \"\(label)\": \(String(describing: refusal))")300            }301            // the shape: marker, number of parts, version302            for text in ["qyvtx1|x|solana-devnet|\(sol)", "qyvtx1|U|solana-devnet|\(sol)", "qyvtx1||solana-devnet|\(sol)", "qyvtx1|u|solana-devnet|\(sol)|", "qyvtx1|u|solana-devnet|\(sol)|x",303                         "qyvtx1|u|solana-devnet", "qyvtx1|u|", "qyvtx1|", "qyvtx1|u|solana-devnet|", "qyvtx1|u|solana-devnet| \(sol)", "qyvtx1|u|solana-devnet|\(sol)=", "qyvtx1|u|solana-devnet|\(sol)AAAA",304                         "qyvtx1|u|tron-nile|\(trx)00", "qyvtx1|u|tron-nile|0x\(trx)", "qyvtx1|u|tron-nile|\(trx.uppercased())x",305                         "qyvtx1|u|tron-nile|\(trx.dropLast())"] {306                if case .invalidPayload? = await MCWallet.error({ try await w.service.reviewColdTransaction([text]) }) { prop.check(true) } else { prop.check(false, "accepted or mis-refused: \(text.prefix(60))") }307            }308            // another version or spelling of the marker is not an envelope at all: the text is then read as a PSBT, and refused as one309            for text in ["qyvtx2|u|solana-devnet|\(sol)", "QYVTX1|u|solana-devnet|\(sol)", "qyvtx1 |u|solana-devnet|\(sol)", "qyvtx0|u|solana-devnet|\(sol)", "qyvtx|u|solana-devnet|\(sol)", "qyvtx11|u|solana-devnet|\(sol)"] {310                let refusal = await MCWallet.error { try await w.service.reviewColdTransaction([text]) }311                let signRefusal = await MCWallet.error { try await w.service.signColdTransaction([text]) }312                prop.check(refusal != nil && signRefusal != nil, "an envelope of another version was accepted: \(text.prefix(40))")313            }314            // a transaction of another account is not this wallet's to sign315            let foreignSol = try Self.solanaPayload(owner: stranger, to: me, lamports: lamports, blockhash: rng.bytes(32))316            let foreignTrx = try Self.tronPayload(owner: tronStranger, to: tronMe, sun: sun, now: Date())317            if case .invalidPayload? = await MCWallet.error({ try await w.service.signColdTransaction(["qyvtx1|u|solana-devnet|\(foreignSol)"]) }) { prop.check(true) } else { prop.check(false, "a Solana transaction of another account") }318            if case .invalidPayload? = await MCWallet.error({ try await w.service.signColdTransaction(["qyvtx1|u|tron-nile|\(foreignTrx)"]) }) { prop.check(true) } else { prop.check(false, "a TRON transaction of another account") }319        }320321        // signing: the signed envelope carries the same label and exactly the reviewed message, signed by this account322        let sol = try Self.solanaPayload(owner: me, to: stranger, lamports: 250_000_000, blockhash: rng.bytes(32))323        // QYV-APP-040: nothing in the payload names its network. Offline, an unaudited build reviews a test-network324        // Solana or TRON transaction and does not sign it, with or without the acknowledgement; no request is made.325        let trxOffline = try Self.tronPayload(owner: tronMe, to: tronStranger, sun: 1_000_000, now: Date())326        for (text, warning) in [("qyvtx1|u|solana-devnet|\(sol)", "solana.cross-cluster"), ("qyvtx1|u|tron-nile|\(trxOffline)", "tron.network-not-bound")] {327            let offlineReview = try? await w.service.reviewColdTransaction([text])328            prop.check(offlineReview?.signingRefusal != nil && offlineReview?.warnings.contains { $0.id == warning && $0.isCritical } == true, "the offline review does not state the refusal: \(warning)")329            if case .unauditedLimitUnverifiable? = await MCWallet.error({ try await w.service.signColdTransaction([text]) }) { prop.check(true) } else { prop.check(false, "an offline device signed \(warning)") }330            if case .unauditedLimitUnverifiable? = await MCWallet.error({ try await w.service.signColdTransaction([text], acknowledged: [warning]) }) { prop.check(true) } else { prop.check(false, "an offline device signed after the acknowledgement: \(warning)") }331        }332        prop.check(w.transport.requests == 0, "the cold device sent \(w.transport.requests) request(s) before any signature")333        // The signature itself is made by a device that is online, after it asked the main-network endpoints (that path334        // is exercised by the root package: MultiChainSendTests.coldSigningOnSolanaAndTronTouchesNoNetwork). This335        // harness has no network: the transaction is signed here by the service's signer directly, and the envelope a336        // signing device would return is rebuilt around it, to check what happens to it on the way back.337        let signedSolana = try await w.service.run { try await w.service.signSolana(try SolanaTransaction.decode(base64: sol), network: .devnet) }338        let signed = (export: (text: "qyvtx1|s|solana-devnet|\(try signedSolana.base64())", frames: [String]()), id: signedSolana.id ?? "")339        let requestsBeforeColdBroadcast = w.transport.requests340        let parts = signed.export.text.split(separator: "|", omittingEmptySubsequences: false).map(String.init)341        prop.check(parts.count == 4 && parts[0] == "qyvtx1" && parts[1] == "s" && parts[2] == "solana-devnet", "signed envelope shape")342        let signedTx = try SolanaTransaction.decode(base64: parts.count == 4 ? parts[3] : "")343        let unsignedTx = try SolanaTransaction.decode(base64: sol)344        prop.check(signedTx.message.serialize() == unsignedTx.message.serialize() && signedTx.isFullySigned && signedTx.verifySignatures() && signedTx.id == signed.id, "the signed transaction is not the reviewed one")345        // on the way back: an unsigned envelope is not broadcast, a signed one is not signed again, a damaged signature is refused before any request346        if case .invalidPayload? = await MCWallet.error({ try await w.service.broadcastSigned(["qyvtx1|u|solana-devnet|\(sol)"]) }) { prop.check(true) } else { prop.check(false, "an unsigned envelope reached the broadcast") }347        if case .invalidPayload? = await MCWallet.error({ try await w.service.signColdTransaction([signed.export.text]) }) { prop.check(true) } else { prop.check(false, "a signed envelope was signed again") }348        var damaged = try signedTx.serialize()349        damaged[1 + rng.int(0...63)] ^= 0x01350        if case .invalidPayload? = await MCWallet.error({ try await w.service.broadcastSigned(["qyvtx1|s|solana-devnet|\(SolanaBase64.encode(damaged))"]) }) { prop.check(true) } else { prop.check(false, "a damaged signature reached the broadcast") }351        // a signed transaction relabelled for another family or network352        for label in ["tron-nile", "ethereum-sepolia", "solana-testnet"] {353            let refusal = await MCWallet.error { try await w.service.broadcastSigned(["qyvtx1|s|\(label)|\(parts.count == 4 ? parts[3] : "")"]) }354            prop.check(refusal != nil && refusal != .offline, "a signed Solana transaction relabelled \(label): \(String(describing: refusal))")355        }356        // cold mode: the right envelope stops at the network, which is off357        let stopped = await MCWallet.error { try await w.service.broadcastSigned([signed.export.text]) }358        prop.check(stopped != nil, "a broadcast succeeded without a network")359        prop.check(w.transport.requests == requestsBeforeColdBroadcast, "the cold device sent \(w.transport.requests - requestsBeforeColdBroadcast) request(s)")360361        // length: a payload above the bound, and a megabyte of separators, are refused in bounded time362        let start = Date()363        for text in ["qyvtx1|u|solana-devnet|" + String(repeating: "A", count: 40_001), "qyvtx1|" + String(repeating: "|", count: 1_000_000), "qyvtx1|u|solana-devnet|" + String(repeating: "|x", count: 500_000),364                     String(repeating: "qyvtx1|", count: 150_000), "0x" + String(repeating: "f", count: 1_000_000), String(repeating: "A", count: 1_000_000)] {365            let refusal = await MCWallet.error { try await w.service.reviewColdTransaction([text]) }366            prop.check(refusal != nil, "a text of \(text.utf8.count) bytes was accepted")367        }368        prop.check(Date().timeIntervalSince(start) < 20, "six megabyte-sized envelopes took \(Date().timeIntervalSince(start)) s")369370        // random envelopes: never a trap, never a review371        let alphabet = Array("qyvtx1|us-abcdefghijklmnopqrstuvwxyzABCDEF0123456789+/=\n \u{00e9}")372        for _ in 0..<AuditMode.cases(quick: 1_500, full: 15_000) {373            var text = "qyvtx1|" + rng.pick(["u", "s", "x", ""]) + "|" + rng.pick(ChainRegistry.all.map(\.id.rawValue) + ["", "nope"]) + "|"374            switch rng.int(0...3) {375            case 0: text += SolanaBase64.encode(rng.bytes(rng.int(0...300)))376            case 1: text += Hex.encode(rng.bytes(rng.int(0...300)))377            case 2: text += String((0..<rng.int(0...200)).map { _ in rng.pick(alphabet) })378            default:379                var bytes = SolanaBase64.decode(sol) ?? []380                if !bytes.isEmpty { bytes[rng.int(0...(bytes.count - 1))] ^= UInt8(1 << rng.int(0...7)) }381                text += SolanaBase64.encode(bytes)382            }383            let review = try? await w.service.reviewColdTransaction([text])384            if let review {385                // a mutated Solana payload can still be a transaction of this account: then it is reviewed as what it is386                prop.check(review.chain.id == .solanaDevnet || review.chain.id == .tronNile, "a random envelope was reviewed on \(review.chain.id)")387            } else {388                prop.check(true)389            }390        }391        prop.finish()392    }393394    /// EVM: the transaction travels without envelope; the network is the chain identifier inside the bytes, never a label.395    @Test func anEVMPayloadNamesItsNetworkItself() async throws {396        var prop = Prop("the network of a cold EVM review is the one of the chain identifier in the payload; a chain that is not active, a non-canonical encoding, a legacy or typed-other transaction are refused", algorithm: "Cold EVM payload")397        let w = try await MCWallet.make()398        defer { w.cleanup() }399        try await w.service.setColdMode(true)400        let to = EthereumAddress(bytes: Bytes(repeating: 0x70, count: 20))401        for network in EthereumNetwork.allCases {402            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))403            let payload = "0x" + Hex.encode(tx.unsignedPayload)404            let review = try? await w.service.reviewColdTransaction([payload])405            let refusal = await MCWallet.error { try await w.service.reviewColdTransaction([payload]) }406            if network.isTest {407                prop.check(review?.chain.id == ChainRegistry.id(network) && review?.summary.first == "Network: \(network.displayName) (chain \(network.chainID))", "\(network): \(String(describing: refusal))")408                if case .evm(let inner)? = review?.body { prop.check(inner.transaction == tx && inner.network == network, "\(network): the review is not the payload") } else { prop.check(false, "\(network): no EVM body") }409                prop.check(review?.summary.contains { $0.contains("Not included: the L1 data fee") } == network.isOPStack, "\(network): the L1 fee statement")410                let signed = try? await w.service.signColdTransaction([payload])411                let raw = signed.flatMap { Hex.decode(String($0.export.text.dropFirst(2))) }.flatMap { try? SignedEIP1559Transaction.decode($0) }412                let profile = await w.service.currentProfile()413                prop.check(raw?.transaction == tx && (try? raw?.sender()) == profile.ethereumAddress && raw?.hashHex == signed?.id, "\(network): the signed transaction is not the reviewed one")414            } else if !MainnetPolicy.mainnetEnabled {415                prop.check(review == nil && refusal == .ethereum(.chainMismatch(expected: 11_155_111, found: network.chainID)), "\(network): a main-network payload gave \(String(describing: refusal))")416            }417        }418        let base = EIP1559Transaction(chainID: 11_155_111, nonce: 0, maxPriorityFeePerGas: UInt256(1), maxFeePerGas: UInt256(2), gasLimit: 21_000, to: to, value: UInt256(1))419        let good = base.unsignedPayload420        func refused(_ bytes: Bytes, _ what: String) async {421            let refusal = await MCWallet.error { try await w.service.signColdTransaction(["0x" + Hex.encode(bytes)]) }422            prop.check(refusal != nil, "\(what) was signed")423        }424        // other transaction types (legacy 0xf8…, EIP-2930 0x01, EIP-4844 0x03, EIP-7702 0x04), an unknown chain, trailing bytes425        for type in [0x00, 0x01, 0x03, 0x04, 0x7f, 0xc0, 0xf8] as [UInt8] { await refused([type] + good.dropFirst(), "type 0x\(String(type, radix: 16))") }426        await refused(Bytes(good.dropFirst()), "a legacy-shaped payload (no type byte)")427        await refused(good + [0x00], "a payload with a trailing byte")428        await refused(Bytes(good.dropLast()), "a truncated payload")429        var other = base430        for chain in [0, 2, 5, 17_000, UInt64.max] as [UInt64] {431            other.chainID = chain432            await refused(other.unsignedPayload, "chain \(chain)")433        }434        other = base435        other.to = nil436        await refused(other.unsignedPayload, "a contract creation")437        other = base438        other.maxPriorityFeePerGas = UInt256(3)439        await refused(other.unsignedPayload, "a priority fee above the maximum fee")440        other = base441        other.gasLimit = 20_999442        await refused(other.unsignedPayload, "a gas limit under 21 000")443        other = base444        other.data = [0xde, 0xad, 0xbe, 0xef]445        await refused(other.unsignedPayload, "call data that cannot be decoded, without the explicit permission")446        prop.check(w.transport.requests == 0, "the cold device sent a request")447        prop.finish()448    }449}450451@Suite struct MultichainWatchOnlyProperties {452    @Test func thePackageHoldsPublicMaterialOnlyAndIsReadStrictly() async throws {453        let seed = AuditSeed.make("mc.watch-only")454        var rng = AuditRNG(seed: seed)455        var prop = Prop("no private material in the package; a private key in a package is refused; chains cannot be enabled without an account; hostile packages never trap and never leave a wallet behind an error", algorithm: "Watch-only package v2", seed: seed)456        let cold = try await MCWallet.make()457        defer { cold.cleanup() }458        let export = try await cold.service.exportWatchOnlyPackage()459        let text = export.text460461        // nothing private: no private extended key, no key or seed bytes, no word of the phrase next to another462        let seedBytes = try BIP39.seed(mnemonic: MCWallet.phrase)463        let master = try ExtendedKey.master(seed: seedBytes)464        var secrets = [Hex.encode(seedBytes), Hex.encode(master.privateKey ?? []), Hex.encode(try master.derive(StandardPaths.ethereum()).privateKey ?? []),465                       Hex.encode(try master.derive(TronPaths.account()).privateKey ?? []), "abandon abandon", "abandon about"]466        for network in BitcoinNetwork.allCases {467            let account = try master.derive(WalletService.utxoAccountPath(network))468            secrets.append(Hex.encode(account.privateKey ?? []))469            for version in [ExtendedKey.Version.xprv, .tprv] { secrets.append(try account.serialized(version)) }470        }471        for secret in secrets where !secret.isEmpty { prop.check(!text.localizedCaseInsensitiveContains(secret), "the package contains private material") }472        for marker in ["xprv", "tprv", "zprv", "vprv", "yprv", "uprv", "\"seed\"", "\"mnemonic\"", "\"privateKey\"", "\"words\""] { prop.check(!text.contains(marker), "the package contains \(marker)") }473        for frame in export.frames { prop.check(!frame.contains("prv"), "a QR frame contains a private key marker") }474        let object = try #require(try JSONSerialization.jsonObject(with: Data(text.utf8)) as? [String: Any])475        prop.check(Set(object.keys).isSubset(of: ["format", "version", "bitcoin", "ethereumAddress", "solanaAddress", "tronAddress", "accounts", "enabledChains"]), "unexpected keys: \(object.keys.sorted())")476        let package = try JSONDecoder().decode(WatchOnlyPackage.self, from: Data(text.utf8))477        prop.check(package.version == 2 && package.format == "qyvora-watch-only", "format and version")478        prop.check((try? ExtendedKey.parse(package.bitcoin?.extendedPublicKey ?? ""))?.version.isPrivate == false, "the Bitcoin account key is a public key")479        for (name, account) in package.accounts ?? [:] {480            prop.check(BitcoinNetwork(rawValue: name) != nil && (try? ExtendedKey.parse(account.extendedPublicKey))?.version.isPrivate == false, "account \(name) is a public key of a known network")481        }482        prop.check(EthereumAddress(package.ethereumAddress ?? "") != nil && SolanaPublicKey(base58: package.solanaAddress ?? "") != nil && TronAddress(package.tronAddress ?? "") != nil, "the three account addresses")483        prop.check(Set(package.enabledChains ?? []).isSubset(of: Set(ChainRegistry.mainChains.map(\.id.rawValue))), "enabled chains are main-network identifiers")484        // the same public data as the wallet's profile: the package is what the cold device shows as its accounts485        let profile = await cold.service.currentProfile()486        prop.check(package.ethereumAddress == profile.ethereumAddress?.checksummed && package.solanaAddress == profile.solanaAddress && package.tronAddress == profile.tronAddress, "addresses are the profile's")487488        func encoded(_ p: WatchOnlyPackage) -> String { String(decoding: (try? JSONEncoder().encode(p)) ?? Data(), as: UTF8.self) }489        /// Imports into a new, empty installation; returns the error and whether a wallet exists afterwards.490        func attempt(_ text: String) async -> (error: WalletError?, profile: WalletProfile) {491            guard let w = try? await MCWallet.make(full: false) else { return (.storage("no fixture"), WalletProfile()) }492            defer { w.cleanup() }493            let error = await MCWallet.error { try await w.service.importWatchOnly(package: [text]) }494            return (error, await w.service.currentProfile())495        }496        // the untouched package imports, with the chains the cold device shows497        let plain = await attempt(text)498        prop.check(plain.error == nil && plain.profile.kind == .watchOnly, "the package does not import: \(String(describing: plain.error))")499        // the companion shows the chains of the cold device for which the package carries an account usable now: the account keys500        // of main networks are left out while mainnet is not enabled, so a coin whose test network has no account here is not shown501        prop.check(Set(plain.profile.enabledChains).isSubset(of: Set(profile.enabledChains)) && plain.profile.enabledChains.contains(.bitcoin) && plain.profile.enabledChains.contains(.ethereum)502            && plain.profile.enabledChains.contains(.solana) && plain.profile.enabledChains.contains(.tron), "enabled chains after import: \(plain.profile.enabledChains) from \(profile.enabledChains)")503        prop.check(plain.profile.ethereumAddress == profile.ethereumAddress && plain.profile.solanaAddress == profile.solanaAddress && plain.profile.tronAddress == profile.tronAddress, "imported addresses")504505        // private keys in the place of public ones506        let account = try master.derive(StandardPaths.bip84Account(.signet))507        var withPrivate = package508        withPrivate.bitcoin?.extendedPublicKey = try account.serialized(.tprv)509        var r = await attempt(encoded(withPrivate))510        prop.check(r.error != nil && r.profile.kind == nil, "a private Bitcoin account key was imported")511        withPrivate = package512        withPrivate.accounts?["litecoinTestnet"]?.extendedPublicKey = try master.derive(WalletService.utxoAccountPath(.litecoinTestnet)).serialized(.tprv)513        r = await attempt(encoded(withPrivate))514        prop.check(r.error != nil && r.profile.kind == nil, "a private Litecoin account key was imported")515516        // chains named without the account that goes with them are not enabled517        var noSolana = package518        noSolana.solanaAddress = nil519        noSolana.tronAddress = nil520        noSolana.accounts = nil521        r = await attempt(encoded(noSolana))522        prop.check(r.error == nil && !r.profile.enabledChains.contains(.solana) && !r.profile.enabledChains.contains(.tron) && !r.profile.enabledChains.contains(.litecoin), "a chain was enabled without an account: \(r.profile.enabledChains)")523        prop.check(r.profile.solanaAddress == nil && r.profile.tronAddress == nil, "an address appeared from nowhere")524        var many = package525        many.enabledChains = (0..<5_000).map { "chain-\($0)" } + ["solana", "../../x", "", "bitcoin-signet", "tron"]526        r = await attempt(encoded(many))527        prop.check(r.error == nil && Set(r.profile.enabledChains).isSubset(of: Set(profile.enabledChains)), "unknown chain names changed the enabled list")528529        // format, version, descriptor, addresses of the wrong kind530        var altered = package531        altered.format = "qyvora-watch-only-2"532        r = await attempt(encoded(altered))533        prop.check(r.error != nil && r.profile.kind == nil, "another format marker was accepted")534        for version in [0, -1, 3, Int.max] {535            altered = package536            altered.version = version537            r = await attempt(encoded(altered))538            prop.check(r.error != nil && r.profile.kind == nil, "version \(version) was accepted")539        }540        altered = package541        altered.bitcoin?.extendedPublicKey = try master.derive(StandardPaths.bip84Account(.signet, account: 1)).neutered.serialized(.tpub)542        r = await attempt(encoded(altered))543        prop.check(r.error != nil && r.profile.kind == nil, "an account key that does not match its descriptor was accepted")544        for (field, value) in [("ethereumAddress", package.tronAddress ?? ""), ("ethereumAddress", "0x" + String(repeating: "0", count: 40)), ("solanaAddress", package.ethereumAddress ?? ""),545                               ("solanaAddress", "11111111111111111111111111111111"), ("tronAddress", package.ethereumAddress ?? ""), ("tronAddress", package.solanaAddress ?? "")] {546            var o = object547            o[field] = value548            let data = try JSONSerialization.data(withJSONObject: o)549            r = await attempt(String(decoding: data, as: UTF8.self))550            prop.check(r.error != nil && r.profile.kind == nil, "\(field) = \(value) was accepted")551        }552        // version 1 (Bitcoin and Ethereum only) is still read, and enables nothing else553        var v1 = object554        v1["version"] = 1555        for key in ["solanaAddress", "tronAddress", "accounts", "enabledChains"] { v1[key] = nil }556        r = await attempt(String(decoding: try JSONSerialization.data(withJSONObject: v1), as: UTF8.self))557        prop.check(r.error == nil && r.profile.kind == .watchOnly && r.profile.solanaAddress == nil && r.profile.enabledChains.allSatisfy { ChainRegistry.descriptor($0)?.family == .utxo || ChainRegistry.descriptor($0)?.family == .evm },558                   "a version-1 package: \(String(describing: r.error)) \(r.profile.enabledChains)")559560        // damaged packages: an error and no wallet, or a wallet whose every account is well formed; never a trap561        let bytes = Bytes(text.utf8)562        var imported = 0563        for _ in 0..<AuditMode.cases(quick: 250, full: 2_500) {564            var b = bytes565            for _ in 0..<rng.int(1...3) where !b.isEmpty {566                let i = rng.int(0...(b.count - 1))567                switch rng.int(0...3) {568                case 0: b[i] ^= UInt8(1 << rng.int(0...7))569                case 1: b.remove(at: i)570                case 2: b.insert(rng.pick(Bytes("\"{}[],:0aZ ".utf8)), at: i)571                default: b[i] = rng.pick(Bytes("0123456789abcdefTx".utf8))572                }573            }574            let r = await attempt(String(decoding: b, as: UTF8.self))575            if r.error == nil {576                imported += 1577                prop.check(r.profile.kind == .watchOnly, "an import without error left no wallet")578                prop.check(r.profile.solanaAddress.map { SolanaPublicKey(base58: $0) != nil } ?? true, "a malformed Solana address was stored")579                prop.check(r.profile.tronAddress.map { TronAddress($0) != nil } ?? true, "a malformed TRON address was stored")580                prop.check(r.profile.bitcoinAccounts.values.allSatisfy { (try? ExtendedKey.parse($0.extendedPublicKey))?.version.isPrivate == false }, "a private or malformed account key was stored")581                prop.check(Set(r.profile.enabledChains).isSubset(of: Set(ChainRegistry.mainChains.map(\.id))) && !r.profile.enabledChains.isEmpty, "the enabled list is not a list of main chains")582                // a changed address that is still a valid address is a different account: what the fingerprint check of the interface is for (QYV-APP-080)583            } else {584                prop.check(r.profile.kind == nil, "an error and a wallet: \(String(describing: r.error))")585            }586        }587        prop.finish(note: "\(imported) damaged packages still imported (a changed character that leaves every field well formed)")588    }589}590591@Suite struct MultichainAccountBindingProperties {592    @Test func theBindingRecordIsReadStrictlyAndRepairsTheProfile() async throws {593        let seed = AuditSeed.make("mc.account-binding")594        var rng = AuditRNG(seed: seed)595        var prop = Prop("encode/decode identity; versions 1 and 2 only; a profile that differs from the vault's record is replaced by it at unlock, for every family", algorithm: "Vault account binding v2", seed: seed)596        let data = try WalletService.publicData(seed: try BIP39.seed(mnemonic: MCWallet.phrase))597        prop.check(data.isComplete && data.solana != nil && data.tron != nil && Set(data.accounts.keys) == WalletService.expectedAccountKeys, "public data of the phrase covers every family")598        let payload = WalletService.AccountBinding(data).encoded599        prop.check(WalletService.AccountBinding.decode(payload) == data, "round trip")600        prop.check(payload.count <= WalletService.AccountBinding.maximumBytes, "the record fits its bound")601        prop.check(!String(decoding: payload, as: UTF8.self).contains("prv"), "no private key in the record")602        let object = try #require(try JSONSerialization.jsonObject(with: Data(payload)) as? [String: Any])603        func decode(_ change: (inout [String: Any]) -> Void) -> WalletService.PublicData? {604            var o = object605            change(&o)606            return WalletService.AccountBinding.decode(Bytes((try? JSONSerialization.data(withJSONObject: o)) ?? Data()))607        }608        for version in [0, -1, 3, 1_000, Int.max] { prop.check(decode { $0["version"] = version } == nil, "version \(version) accepted") }609        prop.check(decode { $0["version"] = "2" } == nil && decode { $0["version"] = 2.5 } == nil && decode { $0["version"] = nil } == nil, "a version that is not an integer")610        prop.check(decode { $0["format"] = "x" } == nil && decode { $0["format"] = nil } == nil, "another format")611        prop.check(decode { $0["ethereumAddress"] = "0x00" } == nil && decode { $0["ethereumAddress"] = data.tron } == nil && decode { $0["ethereumAddress"] = nil } == nil, "a malformed EVM address")612        prop.check(decode { $0["bitcoinAccounts"] = "x" } == nil && decode { $0["bitcoinAccounts"] = nil } == nil, "malformed accounts")613        // a version-1 record (Bitcoin and Ethereum): read, and incomplete, so that the new families are derived again614        let v1 = decode { $0["version"] = 1; $0["solanaAddress"] = nil; $0["tronAddress"] = nil }615        prop.check(v1 != nil && v1?.isComplete == false && v1?.ethereum == data.ethereum && v1?.solana == nil, "a version-1 record")616        // an address that does not parse is as if absent (derived again), never taken as it is617        prop.check(decode { $0["solanaAddress"] = "not base58 !" }?.solana == nil && decode { $0["tronAddress"] = data.ethereum.checksummed }?.tron == nil, "a malformed address in the record")618        prop.check(WalletService.AccountBinding.decode(payload + Bytes(repeating: 0x20, count: WalletService.AccountBinding.maximumBytes)) == nil, "an oversized record")619        prop.check(WalletService.AccountBinding.decode([]) == nil && WalletService.AccountBinding.decode(Bytes("null".utf8)) == nil && WalletService.AccountBinding.decode(Bytes("[]".utf8)) == nil, "empty records")620        for _ in 0..<AuditMode.cases(quick: 3_000, full: 30_000) {621            var b = payload622            for _ in 0..<rng.int(1...4) where !b.isEmpty {623                let i = rng.int(0...(b.count - 1))624                if rng.bool() { b[i] ^= UInt8(1 << rng.int(0...7)) } else { b[i] = rng.pick(Bytes("\"{}[],:0aZ1T".utf8)) }625            }626            if rng.int(0...9) == 0 { b = Bytes(b.prefix(rng.int(0...b.count))) }627            if let decoded = WalletService.AccountBinding.decode(b) {628                prop.check(decoded.solana.map { SolanaPublicKey(base58: $0) != nil } ?? true, "a malformed Solana address came out of a damaged record")629                prop.check(decoded.tron.map { TronAddress($0) != nil } ?? true, "a malformed TRON address came out of a damaged record")630            } else {631                prop.check(true)632            }633        }634635        // the repair at unlock, family by family: the profile file names another account, the vault's record wins636        let w = try await MCWallet.make()637        defer { w.cleanup() }638        let stranger = WalletService.PublicData(accounts: data.accounts, ethereum: EthereumAddress(bytes: Bytes(repeating: 0x66, count: 20))!, solana: data.solana, tron: data.tron)639        var swapped = [stranger]640        var other = data641        other.solana = try SolanaKeys.publicKey(privateSeed: Bytes(repeating: 9, count: 32)).base58642        swapped.append(other)643        other = data644        other.tron = TronAddress(hash: Bytes(repeating: 0x33, count: 20))?.base58645        swapped.append(other)646        other = data647        let strangerMaster = try ExtendedKey.master(seed: Bytes(repeating: 0x5a, count: 64))648        other.accounts["litecoinTestnet"] = BitcoinAccountPublicData(extendedPublicKey: try strangerMaster.derive(WalletService.utxoAccountPath(.litecoinTestnet)).neutered.serialized(.tpub), masterFingerprint: nil)649        swapped.append(other)650        other = data651        other.accounts["test"] = BitcoinAccountPublicData(extendedPublicKey: try strangerMaster.derive(StandardPaths.bip84Account(.signet)).neutered.serialized(.tpub), masterFingerprint: nil)652        swapped.append(other)653        for (index, wrong) in swapped.enumerated() {654            await w.service.replaceAccountDataForTesting(wrong)655            prop.check(await w.service.currentProfile().publicData == wrong, "case \(index): the altered profile is in place")656            let repaired = await w.service.verifyAccountBinding()657            let now = await w.service.currentProfile().publicData658            prop.check(repaired && now == data, "case \(index): the profile was not restored from the vault")659            prop.check(await w.service.trustedPublicData() == data, "case \(index): the vault's record changed")660        }661        prop.check(await w.service.accountBindingRepairCount() == swapped.count, "the repairs are counted")662        prop.check(await w.service.verifyAccountBinding() == false, "an untouched profile is not a repair")663        prop.finish()664    }665}666667@Suite struct MultichainSnapshotProperties {668    /// Writes `object` as the persisted file `name` and returns what the loader of the service makes of it.669    static func write(_ object: [String: Any], _ name: String, _ store: FileStore) throws {670        try store.write(Bytes(try JSONSerialization.data(withJSONObject: object)), to: name, keepPrevious: false)671    }672673    @Test func persistedChainFilesAreValidatedBoundedAndTiedToTheirAccount() async throws {674        let seed = AuditSeed.make("mc.chain-snapshot")675        var rng = AuditRNG(seed: seed)676        var prop = Prop("a file of another account, network, endpoint list or version, or with a value out of range, is ignored and removed; what is restored is flagged as coming from a previous session; no trap", algorithm: "Chain snapshot persistence", parameterSet: "Solana, TRON and EVM files", seed: seed)677        let w = try await MCWallet.make()678        defer { w.cleanup() }679        let profile = await w.service.currentProfile()680        let store = w.store681682        // file names come from fixed tables, never from text of a file or of an endpoint683        var names = Set<String>()684        for n in SolanaNetwork.allCases { names.insert(SolanaChainRecord.fileName(n)) }685        for n in TronNetwork.allCases { names.insert(TronChainRecord.fileName(n)) }686        for n in EthereumNetwork.allCases { names.insert(EthereumSnapshotRecord.fileName(for: n)) }687        prop.check(names.count == 3 + 3 + 7 && names.allSatisfy { $0.hasSuffix(".json") && !$0.contains("/") && !$0.contains("..") && $0.utf8.allSatisfy { ($0 >= 0x61 && $0 <= 0x7a) || $0 == 0x2d || $0 == 0x2e } },688                   "file names: \(names.sorted())")689690        // --- Solana691        let solIdentity = try #require(WalletService.solanaIdentity(profile, network: .devnet)), solAddress = try #require(profile.solanaAddress)692        let token = ChainToken(chain: .solanaDevnet, address: solAddress, symbol: "TKN", name: "Token", decimals: 6, standard: .spl)693        let solRecord = SolanaChainRecord(identity: solIdentity, network: .devnet, address: solAddress, synchronizedAt: Date(timeIntervalSince1970: 1_800_000_000), slot: 5, lamports: 7,694                                          extras: SolanaExtras(accountExists: true, systemAccountRent: 890_880, tokenAccountRent: 2_039_280, token2022AccountRent: 2_074_080, tokenAccountCount: 1),695                                          holdings: [ChainHolding(token: token, amount: UInt256(5), reason: nil, warning: nil, listed: true)], history: [], historyReason: nil, hasOutgoing: false, notes: ["n"])696        let solObject = try #require(try JSONSerialization.jsonObject(with: try JSONEncoder().encode(solRecord)) as? [String: Any])697        let solName = SolanaChainRecord.fileName(.devnet)698        func solana(_ change: (inout [String: Any]) -> Void) throws -> SolanaChainRecord? {699            var o = solObject700            change(&o)701            try Self.write(o, solName, store)702            let restored = WalletService.restoredSolana(fileStore: store, profile: profile, network: .devnet)703            if restored == nil { prop.check(!store.exists(solName), "a refused Solana file was left on disk") }704            return restored705        }706        let good = try solana { _ in }707        prop.check(good?.isFromPreviousSession == true && good?.lamports == 7 && good?.holdings.count == 1, "a valid Solana file is not restored")708        let holding = try #require((solObject["holdings"] as? [[String: Any]])?.first)709        func holdingWith(_ change: (inout [String: Any]) -> Void) -> [String: Any] {710            var h = holding711            var t = h["token"] as? [String: Any] ?? [:]712            change(&t)713            h["token"] = t714            return h715        }716        let refusedSolana: [(String, (inout [String: Any]) -> Void)] = [717            ("another identity", { $0["identity"] = solIdentity + "x" }), ("another account", { $0["address"] = "11111111111111111111111111111111" }),718            ("another network", { $0["network"] = "testnet" }), ("the main network", { $0["network"] = "mainnet-beta" }), ("an unknown network", { $0["network"] = "../x" }),719            ("a future version", { $0["version"] = 2 }), ("version zero", { $0["version"] = 0 }), ("a negative version", { $0["version"] = -1 }),720            ("a negative balance", { $0["lamports"] = -1 }), ("a balance above 64 bits", { $0["lamports"] = 1e30 }), ("a fractional slot", { $0["slot"] = 1.5 }),721            ("too many holdings", { $0["holdings"] = Array(repeating: holding, count: 1_201) }), ("too many notes", { $0["notes"] = Array(repeating: "n", count: 51) }),722            ("decimals above 255", { $0["holdings"] = [holdingWith { $0["decimals"] = 256 }] }), ("negative decimals", { $0["holdings"] = [holdingWith { $0["decimals"] = -1 }] }),723            ("a token of another chain", { $0["holdings"] = [holdingWith { $0["chain"] = "tron-nile" }] }), ("a missing field", { $0["extras"] = nil }),724            ("a holding amount that is not a number", { o in725                var h = holding726                h["amount"] = "many"727                o["holdings"] = [h]728            }),729        ]730        for (what, change) in refusedSolana { prop.check(try solana(change) == nil, "Solana file with \(what) was restored") }731        try store.write(Bytes(repeating: 0x20, count: SolanaChainRecord.maximumBytes + 1), to: solName, keepPrevious: false)732        prop.check(WalletService.restoredSolana(fileStore: store, profile: profile, network: .devnet) == nil && !store.exists(solName), "an oversized Solana file")733        // the same valid file under another network's name, and for a wallet without that family734        try Self.write(solObject, SolanaChainRecord.fileName(.testnet), store)735        prop.check(WalletService.restoredSolana(fileStore: store, profile: profile, network: .testnet) == nil, "a devnet file restored as testnet")736        try Self.write(solObject, solName, store)737        var without = profile738        without.solanaAddress = nil739        prop.check(WalletService.restoredSolana(fileStore: store, profile: without, network: .devnet) == nil, "a Solana file restored without a Solana account")740        var otherEndpoints = profile741        otherEndpoints.solanaEndpoints.rpc["devnet"] = ["https://other.test"]742        try Self.write(solObject, solName, store)743        prop.check(WalletService.restoredSolana(fileStore: store, profile: otherEndpoints, network: .devnet) == nil, "a Solana file restored for other endpoints")744745        // --- TRON746        let tronIdentity = try #require(WalletService.tronIdentity(profile, network: .nile)), tronAddress = try #require(profile.tronAddress)747        let resources = TronChainRecord.Resources(TronResources(freeNetLimit: 600, freeNetUsed: 0, netLimit: 0, netUsed: 0, energyLimit: 0, energyUsed: 0))748        let parameters = TronChainRecord.Parameters(TronChainParameters(bandwidthPriceSun: 1_000, energyPriceSun: 100, accountActivationFeeSun: 1_000_000, createAccountFeeSun: 100_000,749                                                                        createAccountBandwidthRate: 1, maximumFeeLimitSun: 15_000_000_000, memoFeeSun: 1_000_000))750        let tronRecord = TronChainRecord(identity: tronIdentity, network: .nile, address: tronAddress, synchronizedAt: Date(timeIntervalSince1970: 1_800_000_000), blockNumber: 9, balanceSun: 11,751                                         isActivated: true, resources: resources, parameters: parameters, holdings: [], history: nil, historyReason: "x", hasOutgoing: nil, notes: [])752        let tronObject = try #require(try JSONSerialization.jsonObject(with: try JSONEncoder().encode(tronRecord)) as? [String: Any])753        let tronName = TronChainRecord.fileName(.nile)754        func tron(_ change: (inout [String: Any]) -> Void) throws -> TronChainRecord? {755            var o = tronObject756            change(&o)757            try Self.write(o, tronName, store)758            let restored = WalletService.restoredTron(fileStore: store, profile: profile, network: .nile)759            if restored == nil { prop.check(!store.exists(tronName), "a refused TRON file was left on disk") }760            return restored761        }762        prop.check(try tron { _ in }?.isFromPreviousSession == true, "a valid TRON file is not restored")763        let refusedTron: [(String, (inout [String: Any]) -> Void)] = [764            ("another identity", { $0["identity"] = "x" }), ("another account", { $0["address"] = "T9yD14Nj9j7xAB4dbGeiX9h8unkKHxuWwb" }), ("a malformed account", { $0["address"] = "x" }),765            ("another network", { $0["network"] = "shasta" }), ("the main network", { $0["network"] = "mainnet" }), ("a future version", { $0["version"] = 2 }), ("version zero", { $0["version"] = 0 }),766            ("a balance above 2^63", { $0["balanceSun"] = NSNumber(value: UInt64.max) }), ("a negative balance", { $0["balanceSun"] = -5 }), ("too many notes", { $0["notes"] = Array(repeating: "n", count: 51) }),767            ("a negative resource", { o in768                var r = o["resources"] as? [String: Any] ?? [:]769                r["energyLimit"] = -1770                o["resources"] = r771            }), ("parameters missing", { $0["parameters"] = nil }),772        ]773        for (what, change) in refusedTron { prop.check(try tron(change) == nil, "TRON file with \(what) was restored") }774775        // --- EVM: one file per chain; the record must be exactly this account on this network with these endpoints776        let evmNetwork = EthereumNetwork.baseSepolia777        let evmIdentity = try #require(WalletService.ethereumIdentity(profile, network: evmNetwork)), evmAddress = try #require(profile.ethereumAddress)778        let snapshot = EthereumSnapshot(network: evmNetwork, address: evmAddress, synchronizedAt: Date(timeIntervalSince1970: 1_800_000_000), blockNumber: 10, balance: UInt256(123), latestNonce: 2, pendingNonce: 2,779                                        tokens: [], detectedTokens: [TokenBalance(token: TokenInfo(network: evmNetwork, address: EthereumAddress(bytes: Bytes(repeating: 0xc3, count: 20))!, symbol: "DET", name: "Detected", decimals: 6, custom: true),780                                                                                  balance: .available(UInt256(9)))],781                                        history: .unavailable(reason: "x"), approvals: .notLoaded, notes: [])782        let evmObject = try #require(try JSONSerialization.jsonObject(with: try JSONEncoder().encode(EthereumSnapshotRecord(snapshot, identity: evmIdentity))) as? [String: Any])783        let evmName = EthereumSnapshotRecord.fileName(for: evmNetwork)784        func evm(_ change: (inout [String: Any]) -> Void, as network: EthereumNetwork = evmNetwork) throws -> EthereumSnapshot? {785            var o = evmObject786            change(&o)787            try Self.write(o, EthereumSnapshotRecord.fileName(for: network), store)788            let restored = WalletService.restoredEthereum(fileStore: store, profile: profile, network: network)789            if restored == nil { prop.check(!store.exists(EthereumSnapshotRecord.fileName(for: network)), "a refused EVM file was left on disk") }790            return restored791        }792        let restored = try evm { _ in }793        prop.check(restored?.isFromPreviousSession == true && restored?.balance == UInt256(123) && restored?.detectedTokens.count == 1, "a valid EVM file is not restored")794        let detected = try #require((evmObject["detectedTokens"] as? [[String: Any]])?.first)795        func detectedWith(_ change: (inout [String: Any]) -> Void) -> [String: Any] {796            var d = detected797            var t = d["token"] as? [String: Any] ?? [:]798            change(&t)799            d["token"] = t800            return d801        }802        let refusedEVM: [(String, (inout [String: Any]) -> Void)] = [803            ("another identity", { $0["identity"] = evmIdentity + ",https://x" }), ("another account", { $0["address"] = "0x" + String(repeating: "66", count: 20) }),804            ("another network", { $0["network"] = "sepolia" }), ("the main network of the chain", { $0["network"] = "base" }), ("a future version", { $0["version"] = 2 }), ("version zero", { $0["version"] = 0 }),805            ("a pending nonce under the latest", { $0["pendingNonce"] = 1 }), ("a pending nonce far above the latest", { $0["pendingNonce"] = 20_000 }),806            ("a balance of 2^256", { $0["balance"] = "115792089237316195423570985008687907853269984665640564039457584007913129639936" }), ("a negative balance", { $0["balance"] = "-1" }),807            ("token decimals above 36", { $0["detectedTokens"] = [detectedWith { $0["decimals"] = 37 }] }), ("negative token decimals", { $0["detectedTokens"] = [detectedWith { $0["decimals"] = -1 }] }),808            ("a token of another network", { $0["detectedTokens"] = [detectedWith { $0["network"] = "sepolia" }] }), ("a token at the zero address", { $0["detectedTokens"] = [detectedWith { $0["address"] = "0x" + String(repeating: "0", count: 40) }] }),809            ("an unknown balance state", { o in810                var d = detected811                d["state"] = "sure"812                o["detectedTokens"] = [d]813            }),814        ]815        for (what, change) in refusedEVM { prop.check(try evm(change) == nil, "EVM file with \(what) was restored") }816        prop.check(try evm({ _ in }, as: .base) == nil || MainnetPolicy.mainnetEnabled, "a test-network file restored as the main network of the chain")817818        // --- damaged files of the three kinds: nil or a record inside the bounds; never a trap819        let originals: [(String, Bytes)] = [(solName, Bytes(try JSONEncoder().encode(solRecord))), (tronName, Bytes(try JSONEncoder().encode(tronRecord))),820                                            (evmName, Bytes(try JSONEncoder().encode(EthereumSnapshotRecord(snapshot, identity: evmIdentity))))]821        var kept = 0822        for _ in 0..<AuditMode.cases(quick: 1_500, full: 15_000) {823            let (name, original) = rng.pick(originals)824            var b = original825            for _ in 0..<rng.int(1...4) where !b.isEmpty {826                let i = rng.int(0...(b.count - 1))827                switch rng.int(0...3) {828                case 0: b[i] ^= UInt8(1 << rng.int(0...7))829                case 1: b[i] = rng.pick(Bytes("0123456789-e.\"{}[],:".utf8))830                case 2: b.insert(contentsOf: rng.pick([Bytes("9999999999999999999999".utf8), Bytes("-".utf8), Bytes("1e999".utf8), Bytes("null".utf8)]), at: i)831                default: b = Bytes(b.prefix(i))832                }833            }834            try store.write(b, to: name, keepPrevious: false)835            if name == solName, let r = WalletService.restoredSolana(fileStore: store, profile: profile, network: .devnet) {836                kept += 1837                prop.check(r.address == solAddress && r.identity == solIdentity && r.network == .devnet && r.holdings.count <= 1_200 && r.isFromPreviousSession == true, "a damaged Solana file outside the bounds")838            } else if name == tronName, let r = WalletService.restoredTron(fileStore: store, profile: profile, network: .nile) {839                kept += 1840                prop.check(r.address == tronAddress && r.identity == tronIdentity && r.balanceSun <= UInt64(Int64.max) && r.isFromPreviousSession == true, "a damaged TRON file outside the bounds")841            } else if name == evmName, let r = WalletService.restoredEthereum(fileStore: store, profile: profile, network: evmNetwork) {842                kept += 1843                prop.check(r.address == evmAddress && r.network == evmNetwork && r.isFromPreviousSession && r.pendingNonce >= r.latestNonce && r.detectedTokens.allSatisfy { (0...36).contains($0.token.decimals) && $0.token.network == evmNetwork },844                           "a damaged EVM file outside the bounds")845            } else {846                prop.check(!store.exists(name), "a refused file was left on disk")847            }848        }849        prop.check(w.transport.requests == 0, "restoring files reached the network")850        prop.finish(note: "\(kept) damaged files still valid (a changed digit inside the accepted ranges)")851    }852}853
Files main
Menu

Theme