SPB Git

Repository Public

Targets+EVMChains.swift 24.1 KB 334 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : security/tests/Sources/FuzzTargets/Targets+EVMChains.swift8// Module           : Tests9// Repository       : https://git.spboucher.ai/qyvora10// Project Website  : Not specified11// Created          : 2026-12-0412// Last Modified    : 2026-12-0513//14// Author           : Simon-Pierre Boucher15// Position         : Professor of Finance16// Institution      : Université du Québec en Outaouais (UQO)17// Organization     : SP Boucher18// Website          : https://spboucher.ai19// Git              : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development      : dev@spboucher.ai23// Support          : support@spboucher.ai24// Security/Admin   : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License          : None specified (no license file in this repository)33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import AuditSupport42import Foundation43import QyvoraMath44@testable import QyvoraCore45@testable import QyvoraEthereum46@testable import QyvoraNetworking47@testable import QyvoraWallet4849// The EVM extension under untrusted input: fee figures of an endpoint, the return data of the OP-Stack fee oracle,50// the two indexer dialects, the endpoint configuration and every lookup of the network table that takes text.5152/// A JSON-RPC stub: one raw `result` for every method.53struct EVMResultTransport: HTTPTransport {54    let result: String55    func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) {56        guard let url = request.url, let response = HTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: nil) else { throw NetworkError.invalidURL }57        return (Data("{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":\(result)}".utf8), response)58    }59}6061func evmFeeQuoteSeeds() -> [Bytes] {62    func word(_ v: UInt64) -> Bytes { UInt256(v).bytes32 }63    func seed(_ network: UInt8, _ speed: UInt8, _ flags: UInt8, _ base: UInt64, _ tip: UInt64, _ price: UInt64, gas: UInt64 = 21_000, balance: UInt64 = 1_000_000_000_000_000_000, l1: UInt64 = 0) -> Bytes {64        [network, speed, flags] + word(base) + word(tip) + word(price) + Endian.be64(gas) + word(balance) + word(l1)65    }66    return [67        seed(0, 1, 3, 10_000_000_000, 1_000_000_000, 0), seed(8, 0, 3, 100_000_000_000, 25_000_000_000, 0), seed(10, 2, 3, 0, 1_000_000_000, 3_000_000_000),68        seed(10, 1, 1, 0, 1_000_000_000, 0), seed(2, 1, 0, 5_000_000, 0, 0, l1: 8_000_000_000), seed(4, 1, 3, 10_000_000, 0, 0, gas: 600_000),69        seed(6, 2, 3, 9_999_999_999_999, 9_999_999_999_999, 0), seed(0, 1, 3, 10_000_000_000_000, 1, 0),70        [0, 1, 3] + Bytes(repeating: 0xff, count: 96) + Endian.be64(.max) + Bytes(repeating: 0xff, count: 64),71    ]72}7374func evmIndexerDialectSeeds() -> [Bytes] {75    let a = sampleAddress, h = "0x" + sampleTxid76    let blockscoutTx = "{\"items\":[{\"hash\":\"\(h)\",\"from\":{\"hash\":\"\(a)\"},\"to\":{\"hash\":\"\(a)\"},\"value\":\"1000000000000000\",\"timestamp\":\"2026-11-30T12:00:00.000000Z\",\"block_number\":123,\"status\":\"ok\",\"fee\":{\"value\":\"21000\"},\"method\":\"transfer\"}]}"77    let blockscoutTransfer = "{\"items\":[{\"transaction_hash\":\"\(h)\",\"from\":{\"hash\":\"\(a)\"},\"to\":{\"hash\":\"\(a)\"},\"total\":{\"value\":\"5\",\"decimals\":\"6\"},\"token\":{\"address_hash\":\"\(a)\",\"symbol\":\"USDC\",\"decimals\":\"6\"},\"timestamp\":\"2026-11-30T12:00:00Z\",\"block_number\":\"124\"}]}"78    let blockscoutHolding = "{\"items\":[{\"token\":{\"address_hash\":\"\(a)\",\"symbol\":\"USDC\",\"decimals\":\"6\",\"name\":\"USD Coin\"},\"value\":\"250000\"}]}"79    let etherscanTx = "{\"status\":\"1\",\"message\":\"OK\",\"result\":[{\"blockNumber\":\"123\",\"timeStamp\":\"1764504000\",\"hash\":\"\(h)\",\"from\":\"\(a.lowercased())\",\"to\":\"\(a.lowercased())\",\"value\":\"1000000000000000\",\"gasPrice\":\"25000000000\",\"gasUsed\":\"21000\",\"isError\":\"0\",\"txreceipt_status\":\"1\",\"functionName\":\"transfer(address,uint256)\"}]}"80    let etherscanTransfer = "{\"status\":\"1\",\"message\":\"OK\",\"result\":[{\"blockNumber\":\"124\",\"timeStamp\":\"1764504000\",\"hash\":\"\(h)\",\"from\":\"\(a.lowercased())\",\"contractAddress\":\"\(a.lowercased())\",\"to\":\"\(a.lowercased())\",\"value\":\"5\",\"tokenName\":\"USD Coin\",\"tokenSymbol\":\"USDC\",\"tokenDecimal\":\"6\"}]}"81    let etherscanHolding = "{\"status\":\"1\",\"message\":\"OK\",\"result\":[{\"TokenAddress\":\"\(a.lowercased())\",\"TokenName\":\"USD Coin\",\"TokenSymbol\":\"USDC\",\"TokenQuantity\":\"250000\",\"TokenDivisor\":\"6\"}]}"82    let empty = "{\"status\":\"0\",\"message\":\"No transactions found\",\"result\":[]}"83    let refused = "{\"status\":\"0\",\"message\":\"NOTOK\",\"result\":\"Max rate limit reached\"}"84    return ["a" + blockscoutTx, "b" + blockscoutTransfer, "c" + blockscoutHolding, "d" + etherscanTx, "e" + etherscanTransfer, "f" + etherscanHolding, "d" + empty, "e" + refused].map { Bytes($0.utf8) }85}8687func endpointConfigSeeds() -> [Bytes] {88    var out = [Bytes]()89    let encoder = JSONEncoder()90    encoder.outputFormatting = [.sortedKeys]91    if let d = try? encoder.encode(EndpointConfiguration.default) { out.append(Bytes("a".utf8) + Bytes(d)) }92    out.append(Bytes("a{\"esplora\":{\"signet\":[\"https://my.node/api\"]},\"ethereumRPC\":{\"sepolia\":[],\"mainnet\":[\"https://my.rpc\"]},\"ethereumIndexer\":{},\"priceAPI\":\"\"}".utf8))93    out.append(Bytes("a{\"schema\":2,\"esplora\":{},\"blockbook\":{},\"bitcore\":{},\"ethereumRPC\":{\"base\":[\"https://only.this\",\"http://localhost:8545\"]},\"ethereumIndexer\":{\"base\":[\"https://scan.test/api\"]},\"priceAPI\":\"https://prices.test/api/v3\"}".utf8))94    for url in ["https://rpc.example.org:8545/path?x=1", "http://localhost:8545", "http://192.168.1.20:3000/api", "http://node.local", "http://abcdefghijklmnop.onion", "https://user:secret@rpc.example.org",95                "http://10.example.com", "http://172.32.0.1", "ftp://x.test", "http://[::1]:8545"] {96        out.append(Bytes(("b" + url).utf8))97    }98    return out99}100101func networkTableSeeds() -> [Bytes] {102    var texts = EthereumNetwork.allCases.map { "a" + $0.rawValue } + EthereumNetwork.allCases.map { "b" + String($0.chainID) } + ChainRegistry.all.map { "c" + $0.id.rawValue }103    texts += ["d0x" + sampleTxid, "e" + sampleAddress, "f" + sampleTxid, "d0x" + sampleTxid + "/../../x?y=#z", "b18446744073709551616", "b-1", "b0x1", "ctron-nile", "cevm-mainnet"]104    return texts.map { Bytes($0.utf8) }105}106107let evmChainTargets: [FuzzTarget] = [108    FuzzTarget(109        "evm-fee-quotes", "EVM fee rules on figures of a hostile endpoint: priority ≤ max fee, ceilings, network floors, cost and send-max arithmetic without overflow",110        maxLength: 211, tokens: [UInt256(10_000_000_000_000).bytes32, UInt256(100_000_000_000_000).bytes32, UInt256(30_000_000_000).bytes32, Bytes(repeating: 0xff, count: 32), Bytes(repeating: 0, count: 32)],111        seeds: evmFeeQuoteSeeds112    ) { input in113        var r = FuzzInput(input)114        let network = EthereumNetwork.allCases[Int(r.byte()) % EthereumNetwork.allCases.count]115        let speed = EVMFeeSpeed.allCases[Int(r.byte()) % 3]116        let flags = r.byte()117        guard let base = UInt256(bigEndian: r.take(32)), let tipWord = UInt256(bigEndian: r.take(32)), let priceWord = UInt256(bigEndian: r.take(32)) else { return }118        let tip: UInt256? = flags & 1 == 1 ? tipWord : nil, price: UInt256? = flags & 2 == 2 ? priceWord : nil119        let gas = r.take(8).reduce(UInt64(0)) { $0 << 8 | UInt64($1) }120        guard let balance = UInt256(bigEndian: r.take(32)), let l1 = UInt256(bigEndian: r.take(32)) else { return }121        let ceiling = EVMFeeRules.endpointFeePerGasCeiling122        do {123            let fees = try EVMFeeRules.gasFees(network: network, baseFee: base, suggestedPriorityFee: tip, gasPrice: price, speed: speed)124            FuzzOutcome.note("fees")125            fuzzCheck(fees.maxPriorityFeePerGas <= fees.maxFeePerGas && !fees.maxPriorityFeePerGas.isZero, "priority above the maximum fee, or zero")126            fuzzCheck(fees.maxFeePerGas < EVMFeeRules.maxFeePerGasCeiling && base < ceiling && (tip ?? .zero) < ceiling, "a figure at or above its ceiling was accepted")127            fuzzCheck(fees.maxPriorityFeePerGas >= network.minimumPriorityFee, "priority under the minimum of the network")128            if network.hasZeroBaseFee {129                guard let price else { fuzzFail("zero-base-fee network without a gas price") }130                fuzzCheck(!price.isZero && price < ceiling && fees.maxPriorityFeePerGas >= price, "gas price floor")131            }132            let (twice, o1) = base.multipliedReportingOverflow(by: 2)133            let (sum, o2) = twice.addingReportingOverflow(fees.maxPriorityFeePerGas)134            fuzzCheck(!o1 && !o2 && sum == fees.maxFeePerGas, "max fee is not 2 × base + priority")135            // a transaction built with these prices signs (the fee order rule) and its cost is computable up to the gas ceiling136            let tx = EIP1559Transaction(chainID: network.chainID, nonce: 0, maxPriorityFeePerGas: fees.maxPriorityFeePerGas, maxFeePerGas: fees.maxFeePerGas, gasLimit: min(gas, 200_000), to: nil, value: .zero)137            fuzzCheck(tx.maximumCost != nil && EVMFeeRules.maximumCost(tx, l1DataFee: OPStackGasOracle.withMargin(l1 < OPStackGasOracle.feeCeiling ? l1 : .zero)) != nil, "cost overflow inside the accepted ranges")138            // through the client type: the same figures, the same answer139            let data = EthereumRPC.FeeData(network: network, baseFee: base, priorityFee: tip ?? EVMFeeRules.fallbackPriorityFee, gasPrice: price)140            fuzzCheck((try? data.gasFees(speed: speed)) == fees, "FeeData and the rules disagree")141            if speed == .normal { fuzzCheck(data.maxFee == fees.maxFeePerGas, "FeeData.maxFee") }142        } catch {143            FuzzOutcome.note(error: error)144            fuzzUse(EthereumRPC.FeeData(network: network, baseFee: base, priorityFee: tip ?? EVMFeeRules.fallbackPriorityFee, gasPrice: price).maxFee)145        }146        // cost arithmetic on raw figures: nil instead of overflow, and send-max never above the balance147        let fee = EVMFeeRules.maximumFee(gasLimit: gas, maxFeePerGas: tipWord, l1DataFee: l1)148        if let value = EVMFeeRules.sendMaxValue(balance: balance, gasLimit: gas, maxFeePerGas: tipWord, l1DataFee: l1) {149            guard let fee else { fuzzFail("send-max without a computable fee") }150            let (total, overflow) = value.addingReportingOverflow(fee)151            fuzzCheck(!overflow && total == balance && !value.isZero, "send-max + fees ≠ balance")152            FuzzOutcome.note("sendmax")153        } else {154            fuzzCheck(fee == nil || balance <= (fee ?? .zero), "send-max refused although the balance covers the fees")155        }156        let margin = OPStackGasOracle.withMargin(l1)157        fuzzCheck(margin >= l1, "the margin lowered the fee")158        for ceilingKind in [MainnetPolicy.nativeValueCeiling(for: network), MainnetPolicy.feeCeiling(for: network)] {159            fuzzUse(ceilingKind.allows(wei: balance, usdPrice: Double(gas) / 1e6))160            fuzzCheck(ceilingKind.allows(wei: balance, usdPrice: nil) != nil || ceilingKind.needsPrice, "a native ceiling that cannot be checked without a price")161        }162    },163164    FuzzTarget(165        "opstack-oracle", "OP-Stack GasPriceOracle: getL1Fee call data for any payload, return data decoded strictly, through the JSON-RPC client",166        maxLength: 600, tokens: [UInt256(100_000_000_000_000_000).bytes32, UInt256(99_999_999_999_999_999).bytes32, Bytes(repeating: 0, count: 32), Bytes(repeating: 0xff, count: 32)],167        seeds: {168            [UInt256(8_000_000_000).bytes32, UInt256.zero.bytes32, UInt256(99_999_999_999_999_999).bytes32, UInt256(100_000_000_000_000_000).bytes32, Bytes(repeating: 0xff, count: 32),169             UInt256(5).bytes32 + [0], Bytes(UInt256(5).bytes32.dropFirst()), [], [0x02, 0xc0], EIP1559Transaction(chainID: 10, nonce: 1, maxPriorityFeePerGas: UInt256(1), maxFeePerGas: UInt256(2), gasLimit: 21_000, to: nil, value: .zero).unsignedPayload]170        }171    ) { input in172        // as return data173        let fee = OPStackGasOracle.decodeFee(input)174        if let fee {175            FuzzOutcome.note("fee")176            fuzzCheck(input.count == 32 && fee.bytes32 == input && fee < OPStackGasOracle.feeCeiling, "a fee read from data that is not one canonical word under the ceiling")177            fuzzCheck(OPStackGasOracle.withMargin(fee) < UInt256(125_000_000_000_000_000) && OPStackGasOracle.withMargin(fee) >= fee, "margin out of range")178        } else {179            fuzzCheck(input.count != 32 || (UInt256(bigEndian: input) ?? .max) >= OPStackGasOracle.feeCeiling, "a valid fee was refused")180        }181        // as the payload of the call: selector, offset 32, length, the bytes, zero padding to a word182        let call = OPStackGasOracle.getL1FeeCall(input)183        fuzzCheck(call.count == 4 + 64 + (input.count + 31) / 32 * 32 && Bytes(call[0..<4]) == [0x49, 0x94, 0x8e, 0x0e], "call data shape")184        fuzzCheck(UInt256(bigEndian: Bytes(call[4..<36])) == UInt256(32) && UInt256(bigEndian: Bytes(call[36..<68])) == UInt256(UInt64(input.count)), "call data head")185        fuzzCheck(Bytes(call[68..<(68 + input.count)]) == input && call[(68 + input.count)...].allSatisfy { $0 == 0 }, "call data body")186        // through the client, on a network that charges the fee and on one that does not187        let result = "\"0x" + Hex.encode(input) + "\""188        fuzzAwait {189            let op = try? await EthereumRPC(network: .base, transport: EVMResultTransport(result: result)).l1DataFee(unsignedPayload: [0x02, 0xc0])190            fuzzCheck(op == fee, "the client and the decoder disagree on the L1 fee")191            let other = try? await EthereumRPC(network: .arbitrum, transport: EVMResultTransport(result: result)).l1DataFee(unsignedPayload: [0x02, 0xc0])192            fuzzCheck(other == .zero, "a network without L1 fee returned one")193        }194    },195196    FuzzTarget(197        "json-evm-indexer-dialects", "EVM indexers, both dialects (Blockscout API v2, Etherscan-compatible): transactions, token transfers, token holdings", maxLength: 4096, text: true,198        dictionary: ["\"items\":", "\"result\":", "\"status\":\"1\"", "\"status\":\"0\"", "\"hash\":", "\"from\":", "\"to\":", "\"value\":", "\"timeStamp\":", "\"blockNumber\":", "\"gasUsed\":", "\"gasPrice\":",199                     "\"tokenDecimal\":", "\"TokenDivisor\":", "\"TokenQuantity\":", "\"TokenAddress\":", "\"contractAddress\":", "\"functionName\":", "\"decimals\":", "\"address_hash\":", "\"total\":", "\"token\":",200                     "115792089237316195423570985008687907853269984665640564039457584007913129639935", "18446744073709551616", "-1", "1e999", "37", "null", "[", "]", "{", "}"],201        seeds: evmIndexerDialectSeeds202    ) { input in203        guard let selector = input.first else { return }204        let which = fuzzSelector(selector, 6)205        let etherscan = which >= 3206        let transport = StubTransport(body: Data(input.dropFirst()), status: 200)207        let configuration = EndpointConfiguration(esplora: [:], ethereumRPC: [:], ethereumIndexer: ["avalanche": [etherscan ? "https://scan.test/v2/evm/43114/etherscan/api" : "https://index.test"]], priceAPI: "")208        let indexer = EthereumIndexer(network: .avalanche, configuration: configuration, transport: transport)209        @Sendable func wellFormed(_ a: String) -> Bool { a.utf8.count == 42 && a.hasPrefix("0x") }210        fuzzAwait {211            do {212                switch which % 3 {213                case 0:214                    let rows = try await indexer.transactions(of: sampleAddress)215                    for t in rows {216                        fuzzCheck(t.kind == .native && t.tokenAddress == nil && t.tokenDecimals == nil, "a native row with token fields")217                        if etherscan { fuzzCheck(wellFormed(t.from) && (t.to.isEmpty || wellFormed(t.to)) && (t.method ?? "").count <= 64, "Etherscan transaction row out of bounds") }218                        fuzzUse(t.id.utf8.count)219                    }220                    FuzzOutcome.note("tx\(min(rows.count, 2))")221                case 1:222                    let rows = try await indexer.tokenTransfers(of: sampleAddress)223                    for t in rows {224                        fuzzCheck(t.kind == .token && t.tokenAddress != nil && (t.tokenDecimals ?? 0) >= 0 && t.fee == nil, "a token row out of bounds")225                        if etherscan { fuzzCheck(wellFormed(t.from) && wellFormed(t.to) && wellFormed(t.tokenAddress ?? ""), "Etherscan token row with a malformed address") }226                        fuzzUse(t.id.utf8.count)227                    }228                    FuzzOutcome.note("transfer\(min(rows.count, 2))")229                default:230                    let rows = try await indexer.tokenHoldings(of: sampleAddress)231                    for h in rows { fuzzCheck((0...36).contains(h.decimals) && h.symbol.count <= 16 && h.name.count <= 48 && wellFormed(h.address), "token holding out of bounds") }232                    FuzzOutcome.note("holding\(min(rows.count, 2))")233                }234            } catch {235                FuzzOutcome.note("error\(which)")236            }237        }238    },239240    FuzzTarget(241        "endpoint-config", "Endpoint configuration: decoding of a stored or imported value (schemas 1 and 2), stable re-encoding, and the URL acceptance rule", maxLength: 4096, text: true,242        dictionary: ["\"schema\":", "\"esplora\":", "\"blockbook\":", "\"bitcore\":", "\"ethereumRPC\":", "\"ethereumIndexer\":", "\"priceAPI\":", "\"mainnet\":", "\"base\":", "\"litecoin\":", "https://", "http://",243                     "localhost", "127.0.0.1", "10.", "192.168.", "172.16.", ".local", ".onion", "@", ":", "/api", "[", "]", "{", "}", "null", "2", "1"],244        seeds: endpointConfigSeeds245    ) { input in246        guard let selector = input.first else { return }247        let text = fuzzString(Bytes(input.dropFirst()))248        if fuzzSelector(selector, 2) == 1 {249            // one URL: accepted means https, or http to this device or a private network, and never credentials250            guard EndpointConfiguration.isAcceptable(text) else {251                FuzzOutcome.note("refused")252                return253            }254            guard let url = URL(string: text), let host = url.host?.lowercased() else { fuzzFail("an accepted endpoint is not a URL with a host") }255            fuzzCheck(url.user == nil && url.password == nil && (url.scheme == "https" || url.scheme == "http"), "credentials or another scheme accepted")256            if url.scheme == "http" {257                let octets = host.split(separator: ".").compactMap { Int($0) }258                let privateIP = octets.count == 4 && (octets[0] == 127 || octets[0] == 10 || (octets[0] == 192 && octets[1] == 168) || (octets[0] == 172 && (16...31).contains(octets[1])))259                fuzzCheck(host == "localhost" || host.hasSuffix(".local") || host.hasSuffix(".onion") || privateIP, "plain http accepted for a public host: \(host)")260            }261            FuzzOutcome.note(url.scheme ?? "")262            return263        }264        guard let decoded = try? JSONDecoder().decode(EndpointConfiguration.self, from: Data(text.utf8)) else {265            FuzzOutcome.note("undecodable")266            return267        }268        FuzzOutcome.note("decoded")269        // re-encoding is stable: what is stored decodes to the same value, with nothing added270        guard let again = try? JSONEncoder().encode(decoded), let second = try? JSONDecoder().decode(EndpointConfiguration.self, from: again) else { fuzzFail("a decoded configuration does not encode") }271        fuzzCheck(second == decoded, "re-encoding changed the configuration")272        // what the clients keep for every network: acceptable URLs of that network's list only273        for network in EthereumNetwork.allCases {274            let rpc = EthereumRPC(network: network, configuration: decoded, transport: StubTransport(body: Data(), status: 200))275            let listed = decoded.ethereumRPC[network.rawValue] ?? []276            fuzzCheck(rpc.endpoints.count <= listed.count && rpc.endpoints.allSatisfy { $0.user == nil && ($0.scheme == "https" || $0.scheme == "http") }, "an endpoint that was not listed or not acceptable is used")277            fuzzUse(EthereumIndexer(network: network, configuration: decoded, transport: StubTransport(body: Data(), status: 200)).isConfigured)278        }279        for network in BitcoinNetwork.allCases { fuzzUse(decoded.utxoEndpoints(network).count) }280        fuzzUse(decoded.utxoIndexerURLs.count)281        fuzzUse(PriceClient(configuration: decoded, transport: StubTransport(body: Data(), status: 200)).isConfigured)282    },283284    FuzzTarget(285        "network-table", "Lookups of the network table that take text or numbers: network names, chain identifiers, chain ids of the registry, explorer links", maxLength: 300, text: true,286        dictionary: EthereumNetwork.allCases.map(\.rawValue) + ["ethereum", "base-sepolia", "solana-devnet", "tron-nile", "bitcoin-cash", "0x", "/", "..", "?", "#", "@", "%2f", "18446744073709551615", "8453", "11155111"],287        seeds: networkTableSeeds288    ) { input in289        guard let selector = input.first else { return }290        let text = fuzzString(Bytes(input.dropFirst()))291        switch fuzzSelector(selector, 6) {292        case 0:293            if let network = EthereumNetwork(rawValue: text) {294                FuzzOutcome.note("network")295                fuzzCheck(network.rawValue == text && EthereumNetwork(chainID: network.chainID) == network, "network name lookup")296            }297            fuzzUse(BitcoinNetwork(rawValue: text)?.coinType)298        case 1:299            guard let id = UInt64(text) else { return }300            if let network = EthereumNetwork(chainID: id) {301                FuzzOutcome.note("chain")302                fuzzCheck(network.chainID == id, "chain identifier lookup")303            }304        case 2:305            let id = ChainID(text)306            let descriptor = ChainRegistry.descriptor(id)307            fuzzCheck((descriptor != nil) == (ChainRegistry.kind(id) != nil), "descriptor and kind disagree")308            if let descriptor {309                FuzzOutcome.note("descriptor")310                fuzzCheck(descriptor.id.rawValue == text && ChainRegistry.descriptor(descriptor.mainCounterpart)?.isTest == false, "descriptor lookup")311                fuzzCheck(descriptor.testCounterparts.allSatisfy { ChainRegistry.descriptor($0)?.isTest == true }, "test counterparts")312            }313        default:314            // explorer links: a link exists only for a well-formed identifier, and always points at the explorer's own host315            for descriptor in ChainRegistry.all {316                let urls = [descriptor.explorerTransactionURL(text), descriptor.explorerAddressURL(text)].compactMap { $0 }317                for url in urls {318                    FuzzOutcome.note("link")319                    let host = url.host ?? ""320                    let expected: [String]321                    switch descriptor.kind {322                    case .evm(let n): expected = [URL(string: n.explorerBaseURL)?.host ?? "?"]323                    case .utxo(let n): expected = [URL(string: n.explorerBaseURL ?? "")?.host ?? "?"]324                    case .solana: expected = ["explorer.solana.com"]325                    case .tron: expected = ["tronscan.org", "nile.tronscan.org", "shasta.tronscan.org"]326                    }327                    fuzzCheck(expected.contains(host) && url.scheme == "https" && url.user == nil, "an explorer link points at \(host)")328                    fuzzCheck(text.utf8.count <= 120 && !text.contains("/") && !text.contains("?") && !text.contains("#") && !text.contains(" "), "a link was built from a text with URL syntax")329                }330            }331        }332    },333]334
Files main
Menu

Theme