Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : security/tests/Sources/FuzzTargets/Targets+Wallet.swift8// Module : Tests9// Repository : https://git.spboucher.ai/qyvora10// Project Website : Not specified11// Created : 2026-12-0412// Last Modified : 2026-12-0413//14// Author : Simon-Pierre Boucher15// Position : Professor of Finance16// Institution : Université du Québec en Outaouais (UQO)17// Organization : SP Boucher18// Website : https://spboucher.ai19// Git : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development : dev@spboucher.ai23// Support : support@spboucher.ai24// Security/Admin : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License : None specified (no license file in this repository)33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import AuditSupport42import Foundation43import QyvoraBitcoin44import QyvoraCore45import QyvoraMath46import QyvoraEthereum47import QyvoraNetworking48import QyvoraSolana49import QyvoraStorage50import QyvoraTron51import QyvoraVault52@testable import QyvoraWallet5354// The wallet service itself, synchronising against hostile endpoints. One wallet (the BIP-39 test phrase, tiny key55// derivation, temporary directory) is created per process; every execution installs a new set of server answers56// in a routing stub and runs a synchronisation. Nothing reaches the network.57//58// Input: text, one section per line —59// 0 mode ("a" Bitcoin sync, "b" Ethereum sync, "c" Bitcoin sync + fee options + a send plan, "d" market refresh)60// 1 tip height 2 history of the first address 3 unspent outputs of the first address61// 4 statistics of the first address 5 fee estimates62// 6 eth_getBalance result 7 eth_getTransactionCount result 8 eth_feeHistory result 9 eth_call result63// 10 result of any other JSON-RPC method 11 indexer transactions 12 indexer token transfers64// 13 indexer token holdings 14 price markets 15 price chart65// Multi-chain modes ("e" Solana devnet, "f" TRON Nile, "g" Litecoin testnet, "h" Base Sepolia; each synchronises the66// chain through `synchronize(chain:)` and then prepares a payment of the native coin):67// 16 Solana: "<method>=<JSON result>" replaces the answer of that JSON-RPC method (devnet endpoint, and the main-cluster68// endpoint the wallet asks whether a blockhash is one of its own before it signs a test transaction)69// 17 TRON: "<path suffix>=<body>" replaces the answer of the node or history paths ending with that suffix70// 18 Litecoin indexer (Esplora dialect): "<path fragment>=<body>" replaces the answer of the paths containing it71// 19 Base Sepolia: result of the eth_call to the GasPriceOracle (L1 data fee)72// 20 Base Sepolia: result of eth_getBlockByNumber (base fee)73// Sections 6, 7, 9 and 10 also apply to the Base Sepolia endpoint, 11 to 13 to its indexer.74// An empty or missing section gets a well-formed default, so one hostile field is tested against a healthy rest.7576final class RoutingTransport: HTTPTransport, @unchecked Sendable {77 private let lock = NSLock()78 private var sections = [String]()79 var firstAddress = ""8081 static let zeroStatistics =82 "{\"address\":\"x\",\"chain_stats\":{\"funded_txo_count\":0,\"funded_txo_sum\":0,\"spent_txo_count\":0,\"spent_txo_sum\":0,\"tx_count\":0},\"mempool_stats\":{\"funded_txo_count\":0,\"funded_txo_sum\":0,\"spent_txo_count\":0,\"spent_txo_sum\":0,\"tx_count\":0}}"83 static let rpcDefaults: [String: String] = [84 "eth_blockNumber": "\"0x4c4b40\"", "eth_getBalance": "\"0xde0b6b3a7640000\"", "eth_getTransactionCount": "\"0x1\"",85 "eth_feeHistory": "{\"baseFeePerGas\":[\"0x3b9aca00\",\"0x3b9aca00\"],\"gasUsedRatio\":[0.5],\"oldestBlock\":\"0x10\",\"reward\":[[\"0x3b9aca00\"]]}",86 "eth_maxPriorityFeePerGas": "\"0x3b9aca00\"", "eth_gasPrice": "\"0x3b9aca00\"", "eth_getCode": "\"0x\"",87 "eth_call": "\"0x0000000000000000000000000000000000000000000000000000000000000000\"", "eth_estimateGas": "\"0x5208\"", "eth_getLogs": "[]",88 ]8990 static let solanaDefaults: [String: String] = [91 "getGenesisHash": "\"\(SolanaNetwork.devnet.genesisHash)\"", "getSlot": "5000", "getBlockHeight": "4000",92 "getBalance": "{\"context\":{\"slot\":5000},\"value\":2000000000}", "getMinimumBalanceForRentExemption": "890880",93 "getLatestBlockhash": "{\"context\":{\"slot\":5000},\"value\":{\"blockhash\":\"\(Base58.bitcoin.encode(Bytes(repeating: 7, count: 32)))\",\"lastValidBlockHeight\":4150}}",94 "getAccountInfo": "{\"context\":{\"slot\":5000},\"value\":{\"data\":[\"\",\"base64\"],\"executable\":false,\"lamports\":2000000000,\"owner\":\"11111111111111111111111111111111\",\"space\":0}}",95 "getTokenAccountsByOwner": "{\"context\":{\"slot\":5000},\"value\":[]}", "getRecentPrioritizationFees": "[]", "getSignaturesForAddress": "[]", "getTransaction": "null",96 "getFeeForMessage": "{\"context\":{\"slot\":5000},\"value\":5000}",97 "simulateTransaction": "{\"context\":{\"slot\":5000},\"value\":{\"err\":null,\"logs\":[\"Program log: simulated\"],\"unitsConsumed\":450}}",98 "getSignatureStatuses": "{\"context\":{\"slot\":5000},\"value\":[null]}",99 // asked of the main cluster before a test transaction is signed: the blockhash is not one of its own100 "isBlockhashValid": "{\"context\":{\"slot\":5000},\"value\":false}",101 ]102 static let tronParameters =103 "{\"chainParameter\":[{\"key\":\"getCreateAccountFee\",\"value\":100000},{\"key\":\"getTransactionFee\",\"value\":1000},{\"key\":\"getCreateNewAccountFeeInSystemContract\",\"value\":1000000},{\"key\":\"getCreateNewAccountBandwidthRate\",\"value\":1},{\"key\":\"getEnergyFee\",\"value\":100},{\"key\":\"getMaxFeeLimit\",\"value\":15000000000},{\"key\":\"getMemoFee\",\"value\":1000000}]}"104 var tronAddressHex = ""105106 func install(_ s: [String]) { lock.withLock { sections = s } }107108 /// "<key>=<value>" of a section, when the section has that form.109 private func keyed(_ index: Int) -> (key: String, value: String)? {110 let text = section(index, "")111 guard let cut = text.firstIndex(of: "="), cut != text.startIndex else { return nil }112 return (String(text[..<cut]), String(text[text.index(after: cut)...]))113 }114115 private func tronBlock(_ number: UInt64, filler: UInt8 = 0xab) -> String {116 let id = Hex.encode(Endian.be64(number) + Bytes(repeating: filler, count: 24))117 return "{\"blockID\":\"\(id)\",\"block_header\":{\"raw_data\":{\"timestamp\":\(UInt64(Date().timeIntervalSince1970 * 1000)),\"number\":\(number)}}}"118 }119120 private func section(_ index: Int, _ fallback: String) -> String {121 lock.withLock { index < sections.count && !sections[index].isEmpty ? sections[index] : fallback }122 }123124 func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) {125 guard let url = request.url, let host = url.host, let response = HTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: nil)126 else { throw NetworkError.invalidURL }127 let path = url.path128 var body = ""129 switch host {130 case "esplora.test":131 if path.hasSuffix("/block-height/0") {132 body = BitcoinNetwork.signet.genesisHash133 } else if path.hasSuffix("/blocks/tip/height") {134 body = section(1, "200")135 } else if path.hasSuffix("/fee-estimates") {136 body = section(5, "{\"1\":25.3,\"6\":10.1,\"144\":1.0}")137 } else if path.contains("/address/") {138 let first = !firstAddress.isEmpty && path.contains(firstAddress)139 if path.hasSuffix("/utxo") {140 body = first ? section(3, "[]") : "[]"141 } else if path.contains("/txs") {142 body = first && !path.contains("/txs/chain/") ? section(2, "[]") : "[]"143 } else {144 body = first ? section(4, Self.zeroStatistics) : Self.zeroStatistics145 }146 } else {147 body = section(10, "")148 }149 case "rpc.test":150 let method = (try? JSONDecoder().decode(JSONValue.self, from: request.httpBody ?? Data()))?["method"]?.string ?? ""151 let result: String152 switch method {153 case "eth_chainId": result = "\"0xaa36a7\""154 case "eth_getBalance": result = section(6, Self.rpcDefaults[method] ?? "null")155 case "eth_getTransactionCount": result = section(7, Self.rpcDefaults[method] ?? "null")156 case "eth_feeHistory": result = section(8, Self.rpcDefaults[method] ?? "null")157 case "eth_call": result = section(9, Self.rpcDefaults[method] ?? "null")158 default: result = section(10, Self.rpcDefaults[method] ?? "null")159 }160 body = "{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":\(result)}"161 case "indexer.test":162 if path.hasSuffix("/transactions") {163 body = section(11, "{\"items\":[]}")164 } else if path.hasSuffix("/token-transfers") {165 body = section(12, "{\"items\":[]}")166 } else {167 body = section(13, "{\"items\":[]}")168 }169 case "prices.test":170 body = path.hasSuffix("/market_chart") ? section(15, "{\"prices\":[]}") : section(14, "[]")171 case "sol.test", "solmain.test":172 let method = (try? JSONDecoder().decode(JSONValue.self, from: request.httpBody ?? Data()))?["method"]?.string ?? ""173 if let hostile = keyed(16), hostile.key == method {174 body = "{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":\(hostile.value)}"175 } else if let result = Self.solanaDefaults[method] {176 body = "{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":\(result)}"177 } else {178 body = "{\"jsonrpc\":\"2.0\",\"id\":1,\"error\":{\"code\":-32601,\"message\":\"Method not found\"}}"179 }180 case "tron.test", "tronindex.test", "tronmain.test":181 // "tronmain.test" is a node of the main network: the wallet asks it whether the reference block of a test182 // transaction is one of its own blocks (its blocks differ from Nile's by default)183 let main = host == "tronmain.test"184 let filler: UInt8 = main ? 0xcd : 0xab185 if let hostile = keyed(17), path.hasSuffix(hostile.key) {186 body = hostile.value187 } else if request.httpMethod == "GET" {188 body = "{\"data\":[],\"success\":true,\"meta\":{\"page_size\":0}}"189 } else {190 switch path {191 case "/wallet/getblockbynum", "/walletsolidity/getblockbynum":192 let asked = (try? JSONDecoder().decode(JSONValue.self, from: request.httpBody ?? Data()))?["num"]193 var number: UInt64 = 0194 if case .number(let n)? = asked, n >= 0, n < 1e15 { number = UInt64(n) }195 let genesis = (main ? TronNetwork.mainnet : TronNetwork.nile).genesisBlockID196 body = number == 0 ? "{\"blockID\":\"\(genesis)\",\"block_header\":{\"raw_data\":{\"txTrieRoot\":\"00\"}},\"transactions\":[]}" : tronBlock(number, filler: filler)197 case "/wallet/getblock": body = tronBlock(main ? 70_000_000 : 60_000_000, filler: filler)198 case "/walletsolidity/getblock": body = tronBlock(main ? 69_999_981 : 59_999_981, filler: filler)199 case "/wallet/getaccount":200 // a node answers with the address it was asked about201 let asked = (try? JSONDecoder().decode(JSONValue.self, from: request.httpBody ?? Data()))?["address"]?.string ?? tronAddressHex202 body = "{\"address\":\"\(asked.prefix(64).filter { $0.isHexDigit })\",\"balance\":50000000}"203 case "/wallet/getaccountresource": body = "{\"freeNetLimit\":600,\"freeNetUsed\":0}"204 case "/wallet/getchainparameters": body = Self.tronParameters205 case "/wallet/triggerconstantcontract": body = "{\"result\":{\"code\":\"CONTRACT_VALIDATE_ERROR\",\"message\":\"Smart contract is not exist.\"}}"206 default: body = "{}"207 }208 }209 case "ltc.test":210 if let hostile = keyed(18), path.contains(hostile.key) {211 body = hostile.value212 } else if path.hasSuffix("/block-height/0") {213 body = BitcoinNetwork.litecoinTestnet.genesisHash214 } else if path.hasSuffix("/blocks/tip/height") {215 body = "200"216 } else if path.hasSuffix("/fee-estimates") {217 body = "{\"1\":25.3,\"6\":10.1,\"144\":1.0}"218 } else if path.contains("/address/") {219 body = path.hasSuffix("/utxo") || path.contains("/txs") ? "[]" : Self.zeroStatistics220 } else {221 body = ""222 }223 case "l2.test":224 let json = try? JSONDecoder().decode(JSONValue.self, from: request.httpBody ?? Data())225 let method = json?["method"]?.string ?? ""226 let result: String227 switch method {228 case "eth_chainId": result = "\"0x14a34\""229 case "eth_getBalance": result = section(6, Self.rpcDefaults[method] ?? "null")230 case "eth_getTransactionCount": result = section(7, Self.rpcDefaults[method] ?? "null")231 case "eth_getBlockByNumber": result = section(20, "{\"number\":\"0x4c4b40\",\"baseFeePerGas\":\"0x5f5e100\"}")232 case "eth_call":233 let to = json?["params"]?.array?.first?["to"]?.string?.lowercased() ?? ""234 result = to == "0x420000000000000000000000000000000000000f" ? section(19, "\"0x\(Hex.encode(UInt256(8_000_000_000).bytes32))\"") : section(9, Self.rpcDefaults[method] ?? "null")235 default: result = section(10, Self.rpcDefaults[method] ?? "null")236 }237 body = "{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":\(result)}"238 default:239 throw NetworkError.invalidURL240 }241 return (Data(body.utf8), response)242 }243}244245struct WalletFixture: Sendable {246 let service: WalletService247 let router: RoutingTransport248 let firstAddress: String249250 static let endpoints = EndpointConfiguration(251 esplora: ["signet": ["https://esplora.test/api"], "testnet": ["https://esplora.test/api"], "mainnet": ["https://esplora.test/api"], "litecoinTestnet": ["https://ltc.test/api"]],252 ethereumRPC: ["sepolia": ["https://rpc.test"], "mainnet": ["https://rpc.test"], "baseSepolia": ["https://l2.test"]],253 ethereumIndexer: ["sepolia": ["https://indexer.test"], "mainnet": ["https://indexer.test"], "baseSepolia": ["https://indexer.test"]], priceAPI: "https://prices.test/api/v3")254 /// Endpoints of every family the multi-chain modes synchronise, all on the routing stub.255 static let chainEndpoints = ChainEndpoints(256 core: endpoints, solana: SolanaEndpoints(rpc: ["devnet": ["https://sol.test"], "mainnet-beta": ["https://solmain.test"]]),257 tron: TronEndpoints(fullNodes: ["nile": ["https://tron.test"], "mainnet": ["https://tronmain.test"]], history: ["nile": ["https://tronindex.test"]]))258 static let multiChains: [ChainID] = [.bitcoin, .ethereum, .base, .litecoin, .solana, .tron]259260 /// The wallet of this process, or nil when it could not be created (the harness then does nothing).261 static let shared: WalletFixture? = make("shared")262263 /// A wallet of its own (directory, vault, routing stub): the harness tests use one that no replay touches.264 static func make(_ tag: String) -> WalletFixture? {265 let dir = FileManager.default.temporaryDirectory.appendingPathComponent("qyfuzz-wallet-\(tag)-\(getpid())")266 try? FileManager.default.removeItem(at: dir)267 guard let store = try? FileStore(root: dir) else { return nil }268 let vault = Vault(fileStore: store, keychain: InMemoryKeychainStore(), configuration: .init(kdf: .insecureForTesting))269 let router = RoutingTransport()270 guard let service = try? WalletService(vault: vault, fileStore: store, transport: router, sleep: { _ in }, transactionSeed: 7, backupKDF: .insecureForTesting,271 tronPacing: .unthrottled)272 else { return nil }273 nonisolated(unsafe) var address: String?274 fuzzAwait {275 do {276 try await service.setChainEndpoints(chainEndpoints)277 try await service.importWallet(words: BIP39.words(from: abandon), password: "correct horse battery staple 42")278 try await service.setEnabledChains(multiChains)279 address = try await service.bitcoinAddresses(chain: .receive, range: 0..<1).first280 router.tronAddressHex = TronAddress(await service.currentProfile().tronAddress ?? "")?.hex ?? ""281 } catch {}282 }283 guard let address else { return nil }284 router.firstAddress = address285 return WalletFixture(service: service, router: router, firstAddress: address)286 }287}288289func walletSyncSeeds() -> [Bytes] {290 guard let fixture = WalletFixture.shared, let script = try? BitcoinAddress(fixture.firstAddress, network: .signet).scriptPubKey else { return [] }291 let a0 = fixture.firstAddress292 let txid = String(repeating: "cd", count: 32)293 let tx =294 "[{\"txid\":\"\(txid)\",\"version\":2,\"locktime\":0,\"vin\":[{\"txid\":\"\(String(repeating: "ef", count: 32))\",\"vout\":0,\"prevout\":{\"scriptpubkey\":\"0014\(String(repeating: "ee", count: 20))\",\"value\":900000},\"sequence\":4294967293}],\"vout\":[{\"scriptpubkey\":\"\(Hex.encode(script))\",\"scriptpubkey_type\":\"v0_p2wpkh\",\"scriptpubkey_address\":\"\(a0)\",\"value\":50000}],\"fee\":500,\"weight\":561,\"status\":{\"confirmed\":true,\"block_height\":100,\"block_time\":1700000000}}]"295 let utxo = "[{\"txid\":\"\(txid)\",\"vout\":0,\"value\":50000,\"status\":{\"confirmed\":true,\"block_height\":100,\"block_time\":1700000000}}]"296 let stats =297 "{\"address\":\"\(a0)\",\"chain_stats\":{\"funded_txo_count\":1,\"funded_txo_sum\":50000,\"spent_txo_count\":0,\"spent_txo_sum\":0,\"tx_count\":1},\"mempool_stats\":{\"funded_txo_count\":0,\"funded_txo_sum\":0,\"spent_txo_count\":0,\"spent_txo_sum\":0,\"tx_count\":0}}"298 let fees = "{\"1\":25.3,\"2\":20.0,\"6\":10.1,\"144\":1.0}"299 let indexerTx =300 "{\"items\":[{\"hash\":\"0x\(txid)\",\"from\":{\"hash\":\"\(sampleAddress)\"},\"to\":{\"hash\":\"\(sampleAddress)\"},\"value\":\"1000000000000000\",\"timestamp\":\"2026-11-30T12:00:00.000000Z\",\"block_number\":123,\"status\":\"ok\",\"fee\":{\"value\":\"21000\"}}]}"301 let holdings = "{\"items\":[{\"token\":{\"address_hash\":\"\(sampleAddress)\",\"symbol\":\"USDC\",\"decimals\":\"6\",\"name\":\"USD Coin\"},\"value\":\"250000\"}]}"302 let markets = "[{\"id\":\"bitcoin\",\"current_price\":97000.5,\"price_change_percentage_24h_in_currency\":-1.2,\"sparkline_in_7d\":{\"price\":[1.0,2.0]}},{\"id\":\"ethereum\",\"current_price\":3500.1}]"303 let feeHistory = RoutingTransport.rpcDefaults["eth_feeHistory"] ?? ""304 func lines(_ mode: String, _ sections: [Int: String]) -> Bytes {305 let last = sections.keys.max() ?? 0306 return Bytes(([mode] + (1...max(1, last)).map { sections[$0] ?? "" }).joined(separator: "\n").utf8)307 }308 return [309 lines("a", [1: "200", 2: tx, 3: utxo, 4: stats, 5: fees]), lines("c", [1: "200", 2: tx, 3: utxo, 4: stats, 5: fees]),310 lines("a", [2: tx]), lines("a", [1: "200"]),311 lines("b", [6: "\"0xde0b6b3a7640000\"", 7: "\"0x7\"", 8: feeHistory, 9: "\"0x\(String(repeating: "00", count: 31))06\"", 11: indexerTx, 13: holdings]),312 lines("b", [6: "\"0x0\""]), lines("d", [14: markets, 15: "{\"prices\":[[1700000000000,97000.1]]}"]),313 ] + multiChainSyncSeeds(lines)314}315316/// Seeds of the multi-chain modes: a healthy synchronisation of each family, then one hostile answer per family.317func multiChainSyncSeeds(_ lines: (String, [Int: String]) -> Bytes) -> [Bytes] {318 let context = "{\"context\":{\"slot\":5000},\"value\":"319 let mint = Base58.bitcoin.encode(Bytes(repeating: 3, count: 32)), account = Base58.bitcoin.encode(Bytes(repeating: 4, count: 32))320 let owner = "HAgk14JpMQLgt6rVgv7cBQFJWFto5Dqxi472uT3DKpqk"321 let tokenAccount =322 "{\"account\":{\"data\":{\"parsed\":{\"info\":{\"isNative\":false,\"mint\":\"\(mint)\",\"owner\":\"\(owner)\",\"state\":\"initialized\",\"tokenAmount\":{\"amount\":\"700\",\"decimals\":2,\"uiAmountString\":\"7\"}},\"type\":\"account\"},\"program\":\"spl-token\",\"space\":165},\"executable\":false,\"lamports\":2039280,\"owner\":\"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA\",\"space\":165},\"pubkey\":\"\(account)\"}"323 let signatures = "[{\"signature\":\"\(Base58.bitcoin.encode(Bytes(repeating: 5, count: 64)))\",\"slot\":4990,\"err\":null,\"blockTime\":1764504000,\"confirmationStatus\":\"finalized\"}]"324 let trc20 =325 "{\"data\":[{\"transaction_id\":\"\(sampleTxid)\",\"token_info\":{\"symbol\":\"USDT\",\"address\":\"TXYZopYRdj2D9XRtbG411XZZ3kM5VkAeBf\",\"decimals\":6,\"name\":\"Tether USD\"},\"block_timestamp\":1764504000000,\"from\":\"TUEZSdKsoDHQMeZwihtdoBiN46zxhGWYdH\",\"to\":\"TUEZSdKsoDHQMeZwihtdoBiN46zxhGWYdH\",\"type\":\"Transfer\",\"value\":\"5000000\"}],\"success\":true,\"meta\":{\"at\":1764504000000,\"page_size\":1}}"326 let ltcUtxo = "[{\"txid\":\"\(sampleTxid)\",\"vout\":0,\"value\":50000,\"status\":{\"confirmed\":true,\"block_height\":100,\"block_time\":1700000000}}]"327 let word = { (v: UInt64) in "\"0x\(Hex.encode(UInt256(v).bytes32))\"" }328 return [329 lines("e", [1: "200"]), lines("e", [16: "getBalance=" + context + "18446744073709551615}"]), lines("e", [16: "getTokenAccountsByOwner=" + context + "[" + tokenAccount + "]}"]),330 lines("e", [16: "getSignaturesForAddress=" + signatures]), lines("e", [16: "getMinimumBalanceForRentExemption=18446744073709551615"]),331 lines("e", [16: "isBlockhashValid=" + context + "true}"]), lines("e", [16: "isBlockhashValid=null"]),332 lines("e", [16: "getLatestBlockhash=" + context + "{\"blockhash\":\"1\",\"lastValidBlockHeight\":0}}"]), lines("e", [16: "getGenesisHash=\"\(SolanaNetwork.mainnetBeta.genesisHash)\""]),333 lines("f", [1: "200"]), lines("f", [17: "/wallet/getaccount={\"address\":\"41\",\"balance\":9223372036854775808}"]), lines("f", [17: "/transactions/trc20=" + trc20]),334 lines("f", [17: "/wallet/getaccountresource={\"freeNetLimit\":18446744073709551615,\"freeNetUsed\":-1,\"EnergyLimit\":1e30}"]),335 lines("f", [17: "/wallet/getchainparameters={\"chainParameter\":[{\"key\":\"getEnergyFee\",\"value\":18446744073709551615}]}"]),336 lines("f", [17: "/wallet/getblock={\"blockID\":\"00\",\"block_header\":{\"raw_data\":{\"timestamp\":-1,\"number\":18446744073709551615}}}"]),337 lines("g", [1: "200"]), lines("g", [18: "/utxo=" + ltcUtxo]), lines("g", [18: "/blocks/tip/height=18446744073709551615"]), lines("g", [18: "/fee-estimates={\"1\":1e308,\"2\":-1}"]),338 lines("h", [1: "200"]), lines("h", [19: word(99_999_999_999_999_999)]), lines("h", [19: word(100_000_000_000_000_000)]), lines("h", [19: "\"0x\""]), lines("h", [19: "\"0x00\""]),339 lines("h", [20: "{\"number\":\"0x10\",\"baseFeePerGas\":\"0x9184e729fff\"}"]), lines("h", [6: "\"0x" + String(repeating: "f", count: 64) + "\"", 19: word(1)]),340 lines("h", [6: "\"0x2386f26fc10000\"", 19: word(8_000_000_000), 20: "{\"number\":\"0x10\",\"baseFeePerGas\":\"0x0\"}"]),341 ]342}343344/// One multi-chain mode: synchronise the chain through the uniform entry point, check the bounds of what the wallet345/// keeps, then prepare a payment of the native coin from what the endpoints said.346func multiChainSync(_ service: WalletService, mode: Int) async {347 let chain: ChainID = [ChainID.solanaDevnet, .tronNile, .litecoinTestnet, .baseSepolia][mode - 4]348 let recipient: String349 switch mode {350 case 4: recipient = (try? SolanaKeys.publicKey(privateSeed: Bytes(repeating: 9, count: 32)).base58) ?? ""351 case 5: recipient = TronAddress(hash: Bytes(repeating: 0x33, count: 20))?.base58 ?? ""352 case 6: recipient = (try? BitcoinAddress(scriptPubKey: BitcoinScript.p2wpkh(publicKeyHash: Bytes(repeating: 0x5a, count: 20)), network: .litecoinTestnet).string) ?? ""353 default: recipient = sampleAddress354 }355 do {356 try await service.synchronize(chain: chain)357 FuzzOutcome.note("sync-ok\(mode)")358 } catch {359 FuzzOutcome.note("sync\(mode):" + String(describing: error))360 }361 if let snapshot = await service.chainSnapshot(chain) {362 fuzzCheck(snapshot.chain.id == chain && snapshot.chain.isTest, "the snapshot of another network was returned")363 if let data = snapshot.data.value {364 // what the wallet keeps of a synchronisation is bounded, whatever the endpoints sent365 fuzzCheck(data.tokens.count <= 1_500 && data.detectedTokens.count <= 1_500 && data.notes.count <= 60, "token lists or notes out of bounds")366 fuzzCheck((data.history.value?.count ?? 0) <= 20_000, "history out of bounds")367 fuzzCheck((data.tokens + data.detectedTokens).allSatisfy { (0...255).contains($0.token.decimals) && $0.token.symbol.utf8.count <= 64 && $0.token.name.utf8.count <= 256 }, "token metadata out of bounds")368 fuzzCheck(data.native.decimals == snapshot.chain.nativeDecimals && data.native.symbol == snapshot.chain.nativeSymbol, "native coin description changed")369 fuzzUse(String(describing: data).utf8.count)370 }371 fuzzUse(snapshot.syncError?.utf8.count)372 }373 do {374 let review = try await service.prepareSend(chain: chain, asset: .native, to: recipient, amount: UInt256(mode == 6 ? 10_000 : 1_000))375 FuzzOutcome.note("review\(mode)")376 fuzzCheck(review.chain.id == chain && !review.isMainnet && review.limits == nil && review.amount == UInt256(mode == 6 ? 10_000 : 1_000), "the review is not the payment asked")377 fuzzCheck(review.fee.expected <= review.fee.maximum, "expected fee above the maximum fee")378 if case .evm(let inner) = review.body {379 // Base Sepolia: the L1 data fee is in the maximum fee and in the total, and the transaction is bounded380 let tx = inner.transaction381 fuzzCheck(tx.chainID == 84_532 && tx.maxPriorityFeePerGas <= tx.maxFeePerGas && tx.maxFeePerGas < EVMFeeRules.maxFeePerGasCeiling && tx.gasLimit <= WalletService.ethereumGasLimitCeiling, "transaction out of bounds")382 fuzzCheck(inner.l1DataFee < UInt256(125_000_000_000_000_000), "L1 data fee above the bound")383 fuzzCheck(EVMFeeRules.maximumFee(gasLimit: tx.gasLimit, maxFeePerGas: tx.maxFeePerGas, l1DataFee: inner.l1DataFee) == inner.maximumFee, "the L1 data fee is not in the maximum fee")384 fuzzCheck(EVMFeeRules.maximumCost(tx, l1DataFee: inner.l1DataFee) == inner.maximumTotalCost && review.totalNative == inner.maximumTotalCost && review.fee.maximum == inner.maximumFee, "the total is not value + fees")385 fuzzCheck(tx.value == UInt256(1_000) && tx.to?.checksummed == sampleAddress && tx.data.isEmpty, "the transaction is not the payment asked")386 }387 fuzzUse(String(describing: review).utf8.count)388 } catch {389 FuzzOutcome.note("send\(mode):" + String(describing: error))390 }391}392393let walletTargets: [FuzzTarget] = [394 FuzzTarget(395 "wallet-sync", "Wallet service synchronised against hostile Esplora, JSON-RPC, indexer, price, Solana, TRON, Litecoin indexer and OP-Stack answers (routing stub, one wallet per process)",396 maxLength: 6000, text: true,397 dictionary: [398 "getBalance=", "isBlockhashValid=", "getAccountInfo=", "getTokenAccountsByOwner=", "getSignaturesForAddress=", "getTransaction=", "getLatestBlockhash=", "getMinimumBalanceForRentExemption=", "getSlot=", "getGenesisHash=",399 "simulateTransaction=", "getRecentPrioritizationFees=", "getFeeForMessage=", "/wallet/getaccount=", "/wallet/getaccountresource=", "/wallet/getchainparameters=", "/wallet/getblock=", "/walletsolidity/getblock=",400 "/wallet/getblockbynum=", "/transactions=", "/transactions/trc20=", "/wallet/triggerconstantcontract=", "/utxo=", "/txs=", "/address/=", "/blocks/tip/height=", "/fee-estimates=", "/block-height/=",401 "{\"context\":{\"slot\":5000},\"value\":", "\"lamports\":", "\"tokenAmount\":", "\"blockhash\":", "\"balance\":", "\"chainParameter\":", "\"baseFeePerGas\":",402 "\"0x000000000000000000000000000000000000000000000000016345785d8a0000\"",403 "\n", "\"value\":", "\"vout\":", "\"txid\":", "\"prevout\":", "\"status\":", "\"confirmed\":true", "\"confirmed\":false", "\"block_height\":", "\"tx_count\":",404 "\"spent_txo_count\":", "\"0x", "\"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\"", "null", "[]", "{}", "\"items\":", "\"decimals\":",405 "2100000000000000", "18446744073709551615", "9223372036854775807",406 ],407 seeds: walletSyncSeeds408 ) { input in409 guard let fixture = WalletFixture.shared else { return }410 let sections = fuzzString(input).split(separator: "\n", omittingEmptySubsequences: false).map(String.init)411 fixture.router.install(sections)412 let mode = fuzzSelector(sections.first?.utf8.first ?? 0x61, 8)413 let service = fixture.service414 fuzzAwait {415 switch mode {416 case 4, 5, 6, 7:417 await multiChainSync(service, mode: mode)418 case 0, 2:419 do {420 let snapshot = try await service.syncBitcoin()421 FuzzOutcome.note("btc-ok")422 fuzzUse(String(describing: snapshot).utf8.count)423 } catch {424 FuzzOutcome.note("btc:" + String(describing: error))425 }426 if mode == 2 {427 if let options = try? await service.bitcoinFeeOptions() { fuzzUse(String(describing: options).utf8.count) }428 do {429 let plan = try await service.prepareBitcoinSend(to: "tb1qw508d6qejxtdg4y5r3zarvary0c5xw7kxpjzsx", amount: 10_000, feeRate: FeeRate(satPerVByte: 2))430 FuzzOutcome.note("plan")431 fuzzUse(String(describing: plan).utf8.count)432 } catch {433 FuzzOutcome.note("plan:" + String(describing: error))434 }435 }436 case 1:437 do {438 let snapshot = try await service.syncEthereum()439 FuzzOutcome.note("eth-ok")440 fuzzUse(String(describing: snapshot).utf8.count)441 } catch {442 FuzzOutcome.note("eth:" + String(describing: error))443 }444 default:445 do {446 let market = try await service.refreshMarket()447 FuzzOutcome.note("market-ok")448 fuzzUse(String(describing: market).utf8.count)449 } catch {450 FuzzOutcome.note("market:" + String(describing: error))451 }452 }453 }454 }455]456