SPB Git

Repository Public

Targets+Network.swift 15.5 KB 258 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : security/tests/Sources/FuzzTargets/Targets+Network.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 QyvoraEthereum46import QyvoraMath47import QyvoraNetworking48import QyvoraRecovery49@testable import QyvoraWallet5051// Responses of untrusted servers: the JSON handled by the Esplora client, the Ethereum JSON-RPC52// client, the Ethereum indexer and the price client, and the checks the wallet service applies to53// them. The transport is a stub that returns the fuzz input; nothing reaches the network.5455struct StubTransport: HTTPTransport {56    let body: Data57    let status: Int5859    func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) {60        guard let url = request.url, let response = HTTPURLResponse(url: url, statusCode: status, httpVersion: "HTTP/1.1", headerFields: nil) else {61            throw NetworkError.invalidURL62        }63        return (body, response)64    }65}6667let sampleTxid = String(repeating: "ab", count: 32)68let sampleAddress = "0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAed"6970func esploraSeeds() -> [Bytes] {71    let tx = """72        {"txid":"\(sampleTxid)","version":2,"locktime":0,"vin":[{"txid":"\(String(repeating: "cd", count: 32))","vout":1,"prevout":{"scriptpubkey":"0014751e76e8199196d454941c45d1b3a323f1433bd6","scriptpubkey_type":"v0_p2wpkh","scriptpubkey_address":"tb1qw508d6qejxtdg4y5r3zarvary0c5xw7kxpjzsx","value":100000},"scriptsig":"","witness":["3044","02"],"is_coinbase":false,"sequence":4294967293}],"vout":[{"scriptpubkey":"0014751e76e8199196d454941c45d1b3a323f1433bd6","scriptpubkey_type":"v0_p2wpkh","value":90000}],"size":110,"weight":440,"fee":10000,"status":{"confirmed":true,"block_height":2500000,"block_hash":"\(String(repeating: "00", count: 32))","block_time":1700000000}}73        """74    let texts = [75        "0" + tx, "0[" + tx + "]",76        "1[{\"txid\":\"\(sampleTxid)\",\"vout\":0,\"status\":{\"confirmed\":true,\"block_height\":2500000,\"block_time\":1700000000},\"value\":12345}]",77        "2{\"address\":\"tb1qw508d6qejxtdg4y5r3zarvary0c5xw7kxpjzsx\",\"chain_stats\":{\"funded_txo_count\":2,\"funded_txo_sum\":3,\"spent_txo_count\":1,\"spent_txo_sum\":1,\"tx_count\":3},\"mempool_stats\":{\"funded_txo_count\":0,\"funded_txo_sum\":0,\"spent_txo_count\":0,\"spent_txo_sum\":0,\"tx_count\":0}}",78        "3{\"1\":87.882,\"6\":12.5,\"144\":1.027,\"1008\":1.0}", "42500000", "5\(sampleTxid)", "6000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943",79    ]80    return texts.map { Bytes(letterSelector($0).utf8) }81}8283func rpcSeeds() -> [Bytes] {84    let receipt = "{\"status\":\"0x1\",\"blockNumber\":\"0x10\",\"gasUsed\":\"0x5208\",\"effectiveGasPrice\":\"0x3b9aca00\",\"transactionHash\":\"0x\(sampleTxid)\",\"contractAddress\":null,\"logs\":[]}"85    let log = "{\"address\":\"\(sampleAddress)\",\"topics\":[\"0x\(sampleTxid)\",\"0x\(sampleTxid)\"],\"data\":\"0x\(String(repeating: "00", count: 32))\",\"blockNumber\":\"0x10\",\"transactionHash\":\"0x\(sampleTxid)\",\"logIndex\":\"0x0\"}"86    let results = [87        "0\"0xaa36a7\"", "1\"0x10d4f\"", "2\"0xde0b6b3a7640000\"", "3\"0x7\"", "4\"0x6080\"", "5\"0x\(String(repeating: "00", count: 31))12\"", "6\"0x5208\"",88        "7{\"baseFeePerGas\":[\"0x3b9aca00\",\"0x3b9aca01\"],\"gasUsedRatio\":[0.5],\"oldestBlock\":\"0x10\",\"reward\":[[\"0x3b9aca00\",\"0x77359400\"]]}",89        "8" + receipt, "9[" + log + "]", "a\"0x\(sampleTxid)\"", "bnull",90    ]91    return results.map { r in92        let selector = r.prefix(1)93        return Bytes(letterSelector(selector + "{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":" + r.dropFirst() + "}").utf8)94    } + [Bytes("a{\"jsonrpc\":\"2.0\",\"id\":1,\"error\":{\"code\":-32000,\"message\":\"nope\"}}".utf8)]95}9697func indexerSeeds() -> [Bytes] {98    let t = "{\"hash\":\"0x\(sampleTxid)\",\"from\":{\"hash\":\"\(sampleAddress)\"},\"to\":{\"hash\":\"\(sampleAddress)\"},\"value\":\"1000000000000000\",\"timestamp\":\"2026-11-30T12:00:00.000000Z\",\"block_number\":123,\"status\":\"ok\",\"fee\":{\"value\":\"21000\"},\"method\":null}"99    let tt = "{\"transaction_hash\":\"0x\(sampleTxid)\",\"from\":{\"hash\":\"\(sampleAddress)\"},\"to\":{\"hash\":\"\(sampleAddress)\"},\"total\":{\"value\":\"5\",\"decimals\":\"6\"},\"token\":{\"address_hash\":\"\(sampleAddress)\",\"symbol\":\"USDC\",\"decimals\":\"6\",\"name\":\"USD Coin\"},\"timestamp\":\"2026-11-30T12:00:00Z\",\"block_number\":\"124\"}"100    let h = "{\"token\":{\"address_hash\":\"\(sampleAddress)\",\"symbol\":\"USDC\",\"decimals\":\"6\",\"name\":\"USD Coin\"},\"value\":\"250000\"}"101    return [102        "0{\"items\":[" + t + "]}", "1{\"items\":[" + tt + "]}", "2{\"items\":[" + h + "]}",103        "3[{\"id\":\"bitcoin\",\"current_price\":97000.5,\"price_change_percentage_24h_in_currency\":-1.2,\"price_change_percentage_7d_in_currency\":3.4,\"sparkline_in_7d\":{\"price\":[1.0,2.0,3.5]}}]",104        "4{\"prices\":[[1700000000000,97000.1],[1700000360000,97010.2]]}",105        // the second price source (QYV-SVC-087): one ticker with ask, bid and last trade106        "5{\"error\":[],\"result\":{\"SOLUSD\":{\"a\":[\"56.62000\",\"1\",\"1.000\"],\"b\":[\"56.60000\",\"1\",\"1.000\"],\"c\":[\"56.59000\",\"0.5\"]}}}",107    ].map { Bytes(letterSelector($0).utf8) }108}109110let networkTargets: [FuzzTarget] = [111    FuzzTarget(112        "json-esplora", "Esplora responses: transactions, UTXOs, address statistics, fee estimates, tip, plus the wallet's transaction check",113        maxLength: 4096, text: true,114        dictionary: ["\"txid\":", "\"vout\":", "\"value\":", "18446744073709551615", "-1", "1e999", "null", "\"prevout\":", "\"confirmed\":true", "\"block_height\":", "2100000000000000", "9223372036854775807", "[", "]", "{", "}"],115        seeds: esploraSeeds116    ) { input in117        guard let selector = input.first else { return }118        let body = Data(input.dropFirst())119        let client = EsploraClient(network: .testnet, transport: StubTransport(body: body, status: 200))120        let address = "tb1qw508d6qejxtdg4y5r3zarvary0c5xw7kxpjzsx"121        fuzzAwait {122            do {123                switch fuzzSelector(selector, 8) {124                case 0:125                    let list: [EsploraTransaction]126                    if body.first == UInt8(ascii: "[") { list = try await client.transactions(address) } else { list = [try await client.transaction(sampleTxid)] }127                    for t in list.prefix(8) {128                        do {129                            let checked = try WalletService.check(t, tip: 3_000_000)130                            FuzzOutcome.note("checked")131                            fuzzCheck(checked.outputs.count == t.vout.count && checked.inputs.count == t.vin.count, "checked transaction lost entries")132                            fuzzCheck(checked.outputs.allSatisfy { $0.value <= BitcoinLimits.maxMoney }, "checked output above the monetary range")133                        } catch {134                            FuzzOutcome.note("rejected")135                        }136                    }137                case 1:138                    let utxos = try await client.utxos(address)139                    FuzzOutcome.note("utxos\(min(utxos.count, 3))")140                case 2:141                    let stats = try await client.addressStats(address)142                    FuzzOutcome.note(stats.isUsed ? "used" : "unused")143                    FuzzOutcome.note(stats.hasSpent ? "spent" : "unspent")144                case 3: fuzzUse(try await client.feeEstimates().count)145                case 4: fuzzUse(try await client.tipHeight())146                case 5: fuzzUse(try await client.broadcast(rawHex: "00"))147                case 6: try await client.verifyChain()148                default: fuzzUse(try await client.transactionHex(sampleTxid))149                }150                FuzzOutcome.note("ok\(fuzzSelector(selector, 8))")151            } catch {152                FuzzOutcome.note("error\(fuzzSelector(selector, 8))")153            }154        }155    },156157    FuzzTarget(158        "json-ethereum-rpc", "Ethereum JSON-RPC responses: quantities, data, fee history, receipts, logs", maxLength: 4096, text: true,159        dictionary: ["\"result\":", "\"0x", "\"0x0\"", "\"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\"", "null", "\"baseFeePerGas\":", "\"reward\":", "\"status\":\"0x1\"", "\"logs\":", "\"error\":", "[", "]", "{", "}"],160        seeds: rpcSeeds161    ) { input in162        guard let selector = input.first else { return }163        let body = Data(input.dropFirst())164        let rpc = EthereumRPC(network: .sepolia, transport: StubTransport(body: body, status: 200))165        fuzzAwait {166            do {167                switch fuzzSelector(selector, 12) {168                case 0: try await rpc.verifyChain()169                case 1: fuzzUse(try await rpc.blockNumber())170                case 2: fuzzUse(try await rpc.balance(of: sampleAddress))171                case 3: fuzzUse(try await rpc.transactionCount(of: sampleAddress, tag: "pending"))172                case 4: fuzzUse(try await rpc.code(at: sampleAddress))173                case 5:174                    let returned = try await rpc.ethCall(to: sampleAddress, data: [0x31, 0x3c, 0xe5, 0x67])175                    fuzzUse(ERC20.decodeUInt(returned))176                    fuzzUse(ERC20.decodeString(returned))177                case 6: fuzzUse(try await rpc.estimateGas(from: sampleAddress, to: sampleAddress, value: .zero, data: []))178                case 7: fuzzUse(try await rpc.feeData())179                case 8: fuzzUse(try await rpc.receipt("0x" + sampleTxid))180                case 9: fuzzUse(try await rpc.logs(addresses: [sampleAddress], topics: [nil], fromBlock: 0, toBlock: 10).count)181                case 10: fuzzUse(try await rpc.sendRawTransaction([0x02]))182                default: fuzzUse(try await rpc.quorum("eth_chainId"))183                }184                FuzzOutcome.note("ok\(fuzzSelector(selector, 12))")185            } catch {186                FuzzOutcome.note("error\(fuzzSelector(selector, 12))")187            }188        }189    },190191    FuzzTarget(192        "json-indexer", "Ethereum indexer and price API responses, second price source included", maxLength: 4096, text: true,193        dictionary: ["\"items\":", "\"value\":", "\"decimals\":", "\"hash\":", "1e999", "-0", "18446744073709551616", "\"prices\":", "NaN", "null", "[", "]", "{", "}",194                     "\"error\":[]", "\"result\":", "\"a\":[", "\"b\":[", "\"c\":[", "0.000001", "999999999999"],195        seeds: indexerSeeds196    ) { input in197        guard let selector = input.first else { return }198        let body = Data(input.dropFirst())199        let transport = StubTransport(body: body, status: 200)200        let indexer = EthereumIndexer(network: .sepolia, transport: transport)201        let prices = PriceClient(transport: transport)202        fuzzAwait {203            do {204                switch fuzzSelector(selector, 6) {205                case 0: fuzzUse(try await indexer.transactions(of: sampleAddress).count)206                case 1:207                    for t in try await indexer.tokenTransfers(of: sampleAddress) { fuzzCheck((t.tokenDecimals ?? 0) >= 0, "negative token decimals") }208                case 2:209                    for h in try await indexer.tokenHoldings(of: sampleAddress) { fuzzCheck((0...36).contains(h.decimals) && h.symbol.count <= 16, "token holding out of bounds") }210                case 3:211                    for (_, q) in try await prices.quotes(ids: ["bitcoin", "ethereum"]) { fuzzCheck(q.price.isFinite && q.price >= 0, "price out of range") }212                case 4: fuzzUse(try await prices.chart(id: "bitcoin", days: 7).count)213                default:214                    // a price of the second source is a positive finite number below 10^12, or nothing215                    if let price = try await prices.checkPrice(id: "solana") {216                        FuzzOutcome.note("check-price")217                        fuzzCheck(price.isFinite && price > 0 && price < 1e12, "second-source price out of range")218                    }219                }220                FuzzOutcome.note("ok\(fuzzSelector(selector, 6))")221            } catch {222                FuzzOutcome.note("error\(fuzzSelector(selector, 6))")223            }224        }225    },226227    FuzzTarget(228        "wallet-payloads", "Payloads the wallet service accepts from outside: QR frames or text, watch-only package JSON, recovery sheet JSON",229        maxLength: 4096, text: true,230        dictionary: ["qyv1:", "1/1:", "1/2:", "2/2:", "\n", "\"format\":\"qyvora-watch-only\"", "\"version\":1", "\"bitcoin\":", "\"network\":\"testnet\"", "\"descriptor\":", "\"extendedPublicKey\":", "0x02"],231        seeds: {232            var out = [Bytes]()233            if let frames = try? QRChunker.split(Bytes("0x02f86b".utf8) + fixtureBytes("payload", 80).hex.utf8, chunkSize: 64) { out.append(Bytes(frames.joined(separator: "\n").utf8)) }234            out.append(Bytes("  cHNidP8BAHECAAAAAQ==  ".utf8))235            out.append(Bytes("{\"format\":\"qyvora-watch-only\",\"version\":1,\"ethereum\":[]}".utf8))236            if let sheet = try? RecoverySheet.make(mnemonic: BIP39.words(from: abandon), ethereumAddressCount: 1), let json = try? sheet.json() { out.append(Bytes(json)) }237            return out238        }239    ) { input in240        let text = fuzzString(input)241        let frames = text.split(separator: "\n", omittingEmptySubsequences: true).map(String.init)242        do {243            let payload = try QRExport.text(from: frames)244            FuzzOutcome.note("text")245            if let export = try? QRExport.make(text: payload) {246                if let again = try? QRExport.text(from: export.frames) { fuzzCheck(again == payload, "QR frames do not carry the text back") }247            }248        } catch {249            FuzzOutcome.note("no-text")250        }251        if (try? JSONDecoder().decode(WatchOnlyPackage.self, from: Data(input))) != nil { FuzzOutcome.note("watch-only") }252        if (try? RecoverySheet.fromJSON(Data(input))) != nil { FuzzOutcome.note("sheet") }253        if (try? JSONDecoder().decode(JSONValue.self, from: Data(input))) != nil { FuzzOutcome.note("json") }254        if (try? JSONDecoder().decode(EndpointConfiguration.self, from: Data(input))) != nil { FuzzOutcome.note("endpoints") }255        fuzzUse(EndpointConfiguration.isAcceptable(text))256    },257]258
Files main
Menu

Theme