SPB Git

Repository Public

EVMChainsProperties.swift 35.2 KB 489 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : security/tests/Tests/PropertyAuditTests/EVMChainsProperties.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 QyvoraMath44import Testing4546@testable import QyvoraCore47@testable import QyvoraEthereum48@testable import QyvoraNetworking4950// Invariants of the EVM extension, whatever an endpoint answers: fee rules, the OP-Stack L1 fee, quantities, the51// indexer dialects and the endpoint configuration. Every figure an endpoint can supply is an argument here.5253/// A JSON-RPC endpoint whose answers are raw JSON texts by method; a method without entry answers an error.54final class EVMScriptedEndpoint: HTTPTransport, @unchecked Sendable {55    private let lock = NSLock()56    private var results: [String: String]57    private var counts = [String: Int]()58    var status = 2005960    init(_ results: [String: String]) { self.results = results }6162    func set(_ method: String, _ raw: String?) { lock.withLock { results[method] = raw } }63    func count(_ method: String) -> Int { lock.withLock { counts[method] ?? 0 } }64    var total: Int { lock.withLock { counts.values.reduce(0, +) } }6566    func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) {67        guard let url = request.url, let response = HTTPURLResponse(url: url, statusCode: status, httpVersion: "HTTP/1.1", headerFields: nil) else { throw NetworkError.invalidURL }68        let method = (try? JSONDecoder().decode(JSONValue.self, from: request.httpBody ?? Data()))?["method"]?.string ?? "GET " + url.path69        let raw: String? = lock.withLock {70            counts[method, default: 0] += 171            return results[method]72        }73        if request.httpMethod == "GET" { return (Data((raw ?? results["GET"] ?? "").utf8), response) }74        let body = raw.map { "{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":\($0)}" } ?? "{\"jsonrpc\":\"2.0\",\"id\":1,\"error\":{\"code\":-32601,\"message\":\"no such method\"}}"75        return (Data(body.utf8), response)76    }77}7879@Suite struct EVMFeeProperties {80    static let gwei = UInt256(1_000_000_000)8182    /// A figure as a hostile endpoint would give it: zero, one, around each ceiling, a power of two, the largest value.83    static func hostile(_ rng: inout AuditRNG) -> UInt256 {84        switch rng.int(0...9) {85        case 0: return .zero86        case 1: return UInt256(1)87        case 2: return EVMFeeRules.endpointFeePerGasCeiling88        case 3: return EVMFeeRules.endpointFeePerGasCeiling - UInt256(UInt64(rng.int(1...3)))89        case 4: return EVMFeeRules.maxFeePerGasCeiling - UInt256(UInt64(rng.int(0...3)))90        case 5: return .max91        case 6: return UInt256(bigEndian: rng.bytes(rng.int(0...32)))!92        case 7: return UInt256(rng.next() >> UInt64(rng.int(0...63)))93        case 8: return UInt256(30_000_000_000) - UInt256(UInt64(rng.int(0...2)))94        default: return UInt256(UInt64(rng.int(0...200))).multipliedReportingOverflow(by: gwei).095        }96    }9798    @Test func feeRulesHoldForEveryEndpointFigure() {99        let seed = AuditSeed.make("evm.fee-rules")100        var rng = AuditRNG(seed: seed)101        var prop = Prop("priority ≤ max fee, max fee = 2 × base + priority below 100 000 gwei, network floors respected, refused instead of overflowing", algorithm: "EVM fee rules", parameterSet: "14 networks × 3 speeds × hostile figures", seed: seed)102        var accepted = 0, refused = 0103        for _ in 0..<AuditMode.cases(quick: 20_000, full: 200_000) {104            let network = rng.pick(EthereumNetwork.allCases), speed = rng.pick(EVMFeeSpeed.allCases)105            let base = Self.hostile(&rng)106            let tip: UInt256? = rng.int(0...7) == 0 ? nil : Self.hostile(&rng)107            let price: UInt256? = rng.int(0...3) == 0 ? nil : Self.hostile(&rng)108            do {109                let fees = try EVMFeeRules.gasFees(network: network, baseFee: base, suggestedPriorityFee: tip, gasPrice: price, speed: speed)110                accepted += 1111                prop.check(fees.maxPriorityFeePerGas <= fees.maxFeePerGas, "priority above max fee")112                prop.check(!fees.maxFeePerGas.isZero && !fees.maxPriorityFeePerGas.isZero, "a zero price")113                prop.check(fees.maxFeePerGas < EVMFeeRules.maxFeePerGasCeiling, "max fee at or above the ceiling")114                prop.check(fees.baseFee == base && base < EVMFeeRules.endpointFeePerGasCeiling, "base fee above the endpoint ceiling accepted")115                prop.check((tip ?? EVMFeeRules.fallbackPriorityFee) < EVMFeeRules.endpointFeePerGasCeiling, "priority fee above the endpoint ceiling accepted")116                let (twice, o1) = base.multipliedReportingOverflow(by: 2)117                let (sum, o2) = twice.addingReportingOverflow(fees.maxPriorityFeePerGas)118                prop.check(!o1 && !o2 && sum == fees.maxFeePerGas, "max fee is not 2 × base + priority")119                prop.check(fees.maxPriorityFeePerGas >= network.minimumPriorityFee, "priority under the network's minimum")120                if network.hasZeroBaseFee {121                    prop.check(price != nil && !(price ?? .zero).isZero && (price ?? .max) < EVMFeeRules.endpointFeePerGasCeiling, "zero-base-fee network without a usable gas price")122                    prop.check(fees.maxPriorityFeePerGas >= (price ?? .max), "priority under the gas price floor")123                }124                // the speed only scales the priority fee, between half and twice the endpoint's figure (floors apart)125                let suggested = tip ?? EVMFeeRules.fallbackPriorityFee126                var floor = network.minimumPriorityFee127                if network.hasZeroBaseFee, let price, price > floor { floor = price }128                if floor < UInt256(1) { floor = UInt256(1) }129                let ceilingOfTip = suggested.multipliedReportingOverflow(by: 2).0130                prop.check(fees.maxPriorityFeePerGas <= (ceilingOfTip > floor ? ceilingOfTip : floor), "priority above twice the endpoint's figure and above the floor")131                // what a transfer can cost at most with these prices stays computable132                prop.check(EVMFeeRules.maximumFee(gasLimit: 200_000, maxFeePerGas: fees.maxFeePerGas) != nil, "maximum fee overflows at the gas ceiling")133            } catch {134                refused += 1135                let inRange = base < EVMFeeRules.endpointFeePerGasCeiling && (tip ?? .zero) < EVMFeeRules.endpointFeePerGasCeiling136                if error == .missingGasPrice {137                    prop.check(network.hasZeroBaseFee && (price == nil || (price ?? .zero).isZero) && inRange, "missingGasPrice without reason")138                } else {139                    prop.check(error == .outOfRange, "unexpected error")140                }141            }142        }143        // well-formed figures are never refused: the rules do not deny service on ordinary answers144        for network in EthereumNetwork.allCases {145            for speed in EVMFeeSpeed.allCases {146                let base = network.hasZeroBaseFee ? UInt256.zero : UInt256(25).multipliedReportingOverflow(by: Self.gwei).0147                let fees = try? EVMFeeRules.gasFees(network: network, baseFee: base, suggestedPriorityFee: Self.gwei, gasPrice: network.hasZeroBaseFee ? Self.gwei : nil, speed: speed)148                prop.check(fees != nil, "\(network) \(speed): ordinary figures refused")149            }150        }151        prop.finish(note: "\(accepted) accepted, \(refused) refused")152    }153154    @Test func costsAndSendMaxNeverExceedTheBalance() {155        let seed = AuditSeed.make("evm.send-max")156        var rng = AuditRNG(seed: seed)157        var prop = Prop("send-max value + gas limit × max fee + L1 fee = balance; nil instead of overflow or of a negative value; margin of one quarter", algorithm: "EVM cost arithmetic", seed: seed)158        for _ in 0..<AuditMode.cases(quick: 20_000, full: 200_000) {159            let balance = Self.hostile(&rng), maxFee = Self.hostile(&rng), l1 = rng.bool() ? UInt256.zero : Self.hostile(&rng)160            let gas = rng.pick([0, 1, 21_000, 200_000, 30_000_000, rng.next(), UInt64.max])161            let fee = EVMFeeRules.maximumFee(gasLimit: gas, maxFeePerGas: maxFee, l1DataFee: l1)162            if let value = EVMFeeRules.sendMaxValue(balance: balance, gasLimit: gas, maxFeePerGas: maxFee, l1DataFee: l1) {163                prop.check(fee != nil && !value.isZero, "send-max without a computable fee, or of nothing")164                if let fee {165                    let (total, overflow) = value.addingReportingOverflow(fee)166                    prop.check(!overflow && total == balance, "send-max + fees ≠ balance")167                    let tx = EIP1559Transaction(chainID: 10, nonce: 0, maxPriorityFeePerGas: .zero, maxFeePerGas: maxFee, gasLimit: gas, to: nil, value: value)168                    prop.check(EVMFeeRules.maximumCost(tx, l1DataFee: l1) == balance, "maximum cost of the send-max transaction ≠ balance")169                }170            } else {171                prop.check(fee == nil || balance <= (fee ?? .zero), "send-max refused although the balance covers the fees")172            }173            // the margin: at least the fee, at most 5/4 of it rounded down, saturating174            let margin = OPStackGasOracle.withMargin(l1)175            let quarter = l1.quotientAndRemainder(dividingBy: 4).0176            let (expected, overflow) = l1.addingReportingOverflow(quarter)177            prop.check(margin >= l1 && margin == (overflow ? .max : expected), "margin of the L1 fee")178        }179        prop.finish()180    }181182    @Test func oracleReturnDataIsStrict() {183        let seed = AuditSeed.make("evm.opstack-decode")184        var rng = AuditRNG(seed: seed)185        var prop = Prop("exactly one 32-byte word strictly below 0.1 ETH, anything else is no fee", algorithm: "OP-Stack L1 fee decoding", seed: seed)186        let ceiling = OPStackGasOracle.feeCeiling187        for _ in 0..<AuditMode.cases(quick: 20_000, full: 200_000) {188            let data: Bytes189            switch rng.int(0...5) {190            case 0: data = Self.hostile(&rng).bytes32191            case 1: data = Bytes(repeating: 0, count: 24) + rng.bytes(8)192            case 2: data = rng.bytes(rng.int(0...100))193            case 3: data = Self.hostile(&rng).bytes32 + rng.bytes(rng.int(1...64))194            case 4: data = Bytes(Self.hostile(&rng).bytes32.dropFirst(rng.int(1...31)))195            default: data = []196            }197            let fee = OPStackGasOracle.decodeFee(data)198            if data.count == 32, let word = UInt256(bigEndian: data), word < ceiling {199                prop.check(fee == word, "a valid fee was refused")200            } else {201                prop.check(fee == nil, "a fee was read from \(data.count) bytes")202            }203            if let fee { prop.check(OPStackGasOracle.withMargin(fee) < UInt256(125_000_000_000_000_000), "fee with margin at or above 0.125 ETH") }204        }205        prop.finish()206    }207208    @Test func quantitiesFromAnEndpointAreStrict() {209        let seed = AuditSeed.make("evm.quantities")210        var rng = AuditRNG(seed: seed)211        var prop = Prop("\"0x\" + 1…64 hexadecimal digits or refusal; never a trap; 2^256 and beyond refused", algorithm: "JSON-RPC quantities", seed: seed)212        let refused: [JSONValue] = [213            .null, .bool(true), .number(1), .number(-1), .number(1e300), .array([]), .object([:]), .string(""), .string("0x"), .string("0X1"), .string("1"), .string("-0x1"),214            .string("0x-1"), .string(" 0x1"), .string("0x1 "), .string("0xg"), .string("0x1g"), .string("0x" + String(repeating: "f", count: 65)), .string("0x1" + String(repeating: "0", count: 64)),215            .string("0x\u{0661}"), .string("0x1"), .string("0x1\u{0000}"), .string("0x+1"), .string("0x0x1"), .string("0x.1"), .string("0x1e3x"),216        ]217        for v in refused { prop.check((try? EthereumRPC.quantity(v, "x")) == nil, "accepted \(v)") }218        prop.check((try? EthereumRPC.quantity(.string("0x" + String(repeating: "f", count: 64)), "x")) == .max, "2^256 − 1 refused")219        prop.check((try? EthereumRPC.quantity(.string("0x0"), "x")) == .zero && (try? EthereumRPC.quantity(.string("0x00000a"), "x")) == UInt256(10), "plain quantities")220        prop.check((try? EthereumRPC.quantity(.string("0xABCdef"), "x")) == UInt256(0xabcdef), "mixed case digits")221        let alphabet = Array("0123456789abcdefABCDEFxX -+.gG\u{00e9}")222        for _ in 0..<AuditMode.cases(quick: 20_000, full: 200_000) {223            let text: String224            if rng.bool() {225                text = "0x" + Hex.encode(rng.bytes(rng.int(0...40)))226            } else {227                text = String((0..<rng.int(0...70)).map { _ in rng.pick(alphabet) })228            }229            let parsed = try? EthereumRPC.quantity(.string(text), "x")230            let digits = text.hasPrefix("0x") ? String(text.dropFirst(2)) : ""231            let wellFormed = text.hasPrefix("0x") && !digits.isEmpty && digits.count <= 64 && digits.allSatisfy { $0.isASCII && $0.isHexDigit }232            prop.check((parsed != nil) == wellFormed, "\"\(text)\" parsed=\(parsed != nil) well-formed=\(wellFormed)")233            if let parsed, wellFormed {234                // the value survives a round trip through its canonical form235                prop.check((try? EthereumRPC.quantity(.string(parsed.hexQuantity), "x")) == parsed, "round trip of \(text)")236                prop.check((try? EthereumRPC.data(.string(text), "x")) != nil || digits.count % 2 == 1, "data rule")237            }238        }239        prop.finish()240    }241}242243@Suite struct EVMEndpointProperties {244    static func configuration(_ network: EthereumNetwork, hosts: [String] = ["a.test"]) -> EndpointConfiguration {245        EndpointConfiguration(esplora: [:], ethereumRPC: [network.rawValue: hosts.map { "https://\($0)" }], ethereumIndexer: [network.rawValue: ["https://index.test", "https://scan.test/api"]], priceAPI: "")246    }247248    static func block(_ base: String?) -> String {249        "{\"number\":\"0x10\"" + (base.map { ",\"baseFeePerGas\":\($0)" } ?? "") + "}"250    }251252    /// What `feeData` returns under hostile answers is always inside the bounds the rules accept, on every network.253    @Test func feeDataIsBoundedOnEveryNetwork() async throws {254        let seed = AuditSeed.make("evm.fee-data")255        var rng = AuditRNG(seed: seed)256        var prop = Prop("base fee, priority fee and gas price below 10 000 gwei or refusal; BNB Smart Chain needs a non-zero gas price", algorithm: "eth_getBlockByNumber / eth_maxPriorityFeePerGas / eth_gasPrice", seed: seed)257        let texts = ["\"0x0\"", "\"0x1\"", "\"0x3b9aca00\"", "\"0x9184e729fff\"", "\"0x9184e72a000\"", "\"0x" + String(repeating: "f", count: 64) + "\"", "\"0x1" + String(repeating: "0", count: 64) + "\"",258                     "\"\"", "\"0x\"", "\"1000\"", "1000", "-1", "null", "[]", "{}", "\"0xzz\"", "1e400", "true"]259        for _ in 0..<AuditMode.cases(quick: 1_500, full: 15_000) {260            let network = rng.pick(EthereumNetwork.allCases)261            let base = rng.int(0...9) == 0 ? nil : rng.pick(texts)262            let endpoint = EVMScriptedEndpoint(["eth_getBlockByNumber": rng.int(0...19) == 0 ? rng.pick(texts) : Self.block(base)])263            if rng.int(0...4) != 0 { endpoint.set("eth_maxPriorityFeePerGas", rng.pick(texts)) }264            if rng.int(0...4) != 0 { endpoint.set("eth_gasPrice", rng.pick(texts)) }265            let rpc = EthereumRPC(network: network, configuration: Self.configuration(network), transport: endpoint)266            guard let data = try? await rpc.feeData() else {267                prop.check(true)268                continue269            }270            let ceiling = EVMFeeRules.endpointFeePerGasCeiling271            prop.check(data.network == network && data.baseFee < ceiling && data.priorityFee < ceiling, "fee data out of bounds on \(network)")272            prop.check(network.hasZeroBaseFee == (data.gasPrice != nil) && (data.gasPrice.map { !$0.isZero && $0 < ceiling } ?? true), "gas price rule on \(network)")273            prop.check(endpoint.count("eth_gasPrice") == (network.hasZeroBaseFee ? 1 : 0), "eth_gasPrice asked where it is not used")274            if let fees = try? data.gasFees(speed: rng.pick(EVMFeeSpeed.allCases)) {275                prop.check(fees.maxPriorityFeePerGas <= fees.maxFeePerGas && fees.maxFeePerGas < EVMFeeRules.maxFeePerGasCeiling, "prices out of bounds on \(network)")276                // the most a 21 000-gas transfer can cost with what one endpoint said: under 2.1 coins on any network277                let cost = EVMFeeRules.maximumFee(gasLimit: 21_000, maxFeePerGas: fees.maxFeePerGas) ?? .max278                prop.check(cost < UInt256(2_100_000_000_000_000_000), "a transfer above 2.1 coins of fee")279            }280            fuzzless(data.maxFee)281        }282        prop.finish()283    }284285    /// The L1 data fee: a failing or malformed oracle answer is an error, never a fee of zero; a network that charges286    /// none asks nothing.287    @Test func l1DataFeeIsNeverSilentlyZero() async throws {288        let seed = AuditSeed.make("evm.l1-fee")289        var rng = AuditRNG(seed: seed)290        var prop = Prop("OP-Stack: the oracle's word below 0.1 ETH or an error; other networks: zero without a request", algorithm: "L1 data fee", seed: seed)291        let payload = EIP1559Transaction(chainID: 10, nonce: 1, maxPriorityFeePerGas: UInt256(1), maxFeePerGas: UInt256(2), gasLimit: 21_000, to: nil, value: .zero).unsignedPayload292        func word(_ v: UInt256) -> String { "\"0x" + Hex.encode(v.bytes32) + "\"" }293        let ceiling = OPStackGasOracle.feeCeiling294        let answers: [(String?, UInt256?)] = [295            (word(.zero), .zero), (word(UInt256(1)), UInt256(1)), (word(UInt256(8_000_000_000)), UInt256(8_000_000_000)), (word(ceiling - UInt256(1)), ceiling - UInt256(1)),296            (word(ceiling), nil), (word(.max), nil), (nil, nil), ("\"0x\"", nil), ("null", nil), ("\"0x00\"", nil), ("\"0x" + String(repeating: "00", count: 33) + "\"", nil),297            ("\"0x" + String(repeating: "00", count: 31) + "\"", nil), ("\"0x" + String(repeating: "0", count: 63) + "\"", nil), ("0", nil), ("\"\"", nil), ("[]", nil),298            ("\"0x" + String(repeating: "00", count: 64) + "\"", nil), ("\"" + String(repeating: "00", count: 32) + "\"", nil),299        ]300        for network in EthereumNetwork.allCases {301            for (answer, expected) in answers {302                let endpoint = EVMScriptedEndpoint([:])303                endpoint.set("eth_call", answer)304                let rpc = EthereumRPC(network: network, configuration: Self.configuration(network), transport: endpoint)305                let fee = try? await rpc.l1DataFee(unsignedPayload: payload)306                if network.isOPStack {307                    prop.check(fee == expected, "\(network): answer \(answer ?? "error") gave \(fee?.description ?? "an error"), expected \(expected?.description ?? "an error")")308                    prop.check(endpoint.count("eth_call") == 1, "\(network): the oracle was not asked exactly once")309                } else {310                    prop.check(fee == .zero && endpoint.total == 0, "\(network): a network without L1 fee asked the oracle or returned a fee")311                }312            }313            // an HTTP failure is an error as well314            let down = EVMScriptedEndpoint([:])315            down.status = 503316            let fee = try? await EthereumRPC(network: network, configuration: Self.configuration(network), transport: down).l1DataFee(unsignedPayload: payload)317            prop.check(network.isOPStack ? fee == nil : fee == .zero, "\(network): endpoint down")318        }319        // the gas of a native transfer: a constant, or the endpoint's estimate inside [21 000, 30 000 000] on Arbitrum320        for network in EthereumNetwork.allCases {321            for _ in 0..<AuditMode.cases(quick: 30, full: 300) {322                let estimate = rng.pick([0, 1, 20_999, 21_000, 21_001, 600_000, 30_000_000, 30_000_001, rng.next(), UInt64.max])323                let endpoint = EVMScriptedEndpoint(["eth_estimateGas": "\"\(UInt256(estimate).hexQuantity)\""])324                let gas = try? await EthereumRPC(network: network, configuration: Self.configuration(network), transport: endpoint)325                    .nativeTransferGas(from: "0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAed", to: "0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAed", value: UInt256(1))326                if network.isArbitrum {327                    prop.check(gas == ((21_000...30_000_000).contains(estimate) ? estimate : nil), "\(network): estimate \(estimate) gave \(String(describing: gas))")328                } else {329                    prop.check(gas == 21_000 && endpoint.total == 0, "\(network): the gas of a transfer is a constant")330                }331            }332        }333        prop.finish()334    }335336    /// One lying endpoint among two: the chain identifier and the nonce need agreement; the first answer is taken for337    /// the balance, the fees and eth_call. The test states exactly that, so that a change of policy is noticed.338    @Test func whatOneEndpointDecidesAlone() async throws {339        var prop = Prop("chain id and nonce: every endpoint must agree; balance, fee data, eth_call, gas estimate: first endpoint that answers", algorithm: "EVM endpoint policy", parameterSet: "two endpoints, one lying")340        final class Pair: HTTPTransport, @unchecked Sendable {341            let honest: EVMScriptedEndpoint, liar: EVMScriptedEndpoint342            let liarHost: String343            init(honest: EVMScriptedEndpoint, liar: EVMScriptedEndpoint, liarHost: String) {344                self.honest = honest345                self.liar = liar346                self.liarHost = liarHost347            }348            func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) {349                try await (request.url?.host == liarHost ? liar : honest).send(request)350            }351        }352        let truth: [String: String] = [353            "eth_chainId": "\"0x1\"", "eth_getTransactionCount": "\"0x5\"", "eth_getBalance": "\"0xde0b6b3a7640000\"", "eth_blockNumber": "\"0x100\"",354            "eth_getBlockByNumber": Self.block("\"0x3b9aca00\""), "eth_maxPriorityFeePerGas": "\"0x3b9aca00\"", "eth_estimateGas": "\"0x5208\"",355            "eth_call": "\"0x" + String(repeating: "00", count: 31) + "06\"", "eth_getCode": "\"0x\"",356        ]357        var lies = truth358        lies["eth_chainId"] = "\"0x89\""359        lies["eth_getTransactionCount"] = "\"0x9\""360        lies["eth_getBalance"] = "\"0x0\""361        lies["eth_call"] = "\"0x" + String(repeating: "00", count: 31) + "12\""362        lies["eth_getBlockByNumber"] = Self.block("\"0x9184e729fff\"")363        let address = "0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAed"364        for liarFirst in [true, false] {365            let pair = Pair(honest: EVMScriptedEndpoint(truth), liar: EVMScriptedEndpoint(lies), liarHost: liarFirst ? "a.test" : "b.test")366            let rpc = EthereumRPC(network: .mainnet, configuration: Self.configuration(.mainnet, hosts: ["a.test", "b.test"]), transport: pair)367            // agreement required368            do {369                try await rpc.verifyChain()370                prop.check(false, "a chain identifier the endpoints do not agree on was accepted")371            } catch let e as NetworkError {372                if case .disagreement = e { prop.check(true) } else { prop.check(false, "chain id: \(e)") }373            }374            do {375                _ = try await rpc.transactionCount(of: address, tag: "latest")376                prop.check(false, "a nonce the endpoints do not agree on was accepted")377            } catch let e as NetworkError {378                if case .disagreement = e { prop.check(true) } else { prop.check(false, "nonce: \(e)") }379            }380            let counts = try await rpc.transactionCounts(of: address, tag: "latest")381            prop.check(Set(counts.map(\.count)) == [5, 9] && counts.count == 2, "both nonces are reported to the caller")382            // first answer wins: recorded as it is383            let balance = try await rpc.balance(of: address)384            prop.check(balance == (liarFirst ? .zero : UInt256(1_000_000_000_000_000_000)), "balance comes from the first endpoint")385            let fees = try await rpc.feeData()386            prop.check(fees.baseFee == (liarFirst ? UInt256(9_999_999_999_999) : UInt256(1_000_000_000)), "base fee comes from the first endpoint")387            let decimals = ERC20.decodeUInt(try await rpc.ethCall(to: address, data: ERC20.decimalsSelector))388            prop.check(decimals == UInt256(liarFirst ? 18 : 6), "eth_call comes from the first endpoint")389            // and even the worst accepted fee figures stay bounded390            let worst = try? fees.gasFees(speed: .fast)391            prop.check(worst == nil || (worst?.maxFeePerGas ?? .max) < EVMFeeRules.maxFeePerGasCeiling, "fee bound")392        }393        prop.finish(note: "policy recorded: balance, fee data, eth_call, eth_estimateGas, eth_getCode are not cross-checked between endpoints")394    }395396    @Test func indexerDialectsAreBounded() async throws {397        let seed = AuditSeed.make("evm.indexer-dialects")398        var rng = AuditRNG(seed: seed)399        var prop = Prop("rows of both dialects: bounded text, decimals in 0…36, addresses well formed (Etherscan dialect), no trap on any JSON", algorithm: "EVM indexer dialects (Blockscout API v2, Etherscan-compatible)", seed: seed)400        let address = "0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAed"401        prop.check(EthereumIndexer.dialect(of: URL(string: "https://x.test")!) == .blockscout && EthereumIndexer.dialect(of: URL(string: "https://x.test/")!) == .blockscout, "dialect of a host")402        prop.check(EthereumIndexer.dialect(of: URL(string: "https://x.test/api")!) == .etherscan && EthereumIndexer.dialect(of: URL(string: "https://x.test/v2/evm/43114/etherscan/api/")!) == .etherscan, "dialect of an /api base")403        prop.check(EthereumIndexer.dialect(of: URL(string: "https://x.test/api/v2")!) == .blockscout && EthereumIndexer.dialect(of: URL(string: "https://x.test/apix")!) == .blockscout, "dialect of other paths")404        let values = ["\"1\"", "\"0\"", "\"-1\"", "\"115792089237316195423570985008687907853269984665640564039457584007913129639936\"", "1", "-1", "1e400", "null", "\"\"", "\"0x10\"", "18446744073709551616", "\"18446744073709551616\"", "37", "\"36\"", "\"255\"", "[]", "{}", "true",405                      "\"\(address)\"", "\"0x\"", "\"" + String(repeating: "A", count: 300) + "\"", "\"2026-11-30T12:00:00Z\"", "\"99999999999\"", "\"1700000000\""]406        let keys = ["hash", "from", "to", "value", "timeStamp", "blockNumber", "isError", "txreceipt_status", "gasUsed", "gasPrice", "functionName", "contractAddress", "tokenSymbol", "tokenDecimal",407                    "TokenAddress", "TokenDivisor", "TokenQuantity", "TokenSymbol", "TokenName", "transaction_hash", "total", "token", "timestamp", "block_number", "status", "fee", "method", "decimals", "symbol", "name", "address_hash"]408        func object(_ depth: Int) -> String {409            let n = rng.int(0...10)410            return "{" + (0..<n).map { _ in "\"\(rng.pick(keys))\":" + (depth < 2 && rng.int(0...3) == 0 ? object(depth + 1) : rng.pick(values)) }.joined(separator: ",") + "}"411        }412        for _ in 0..<AuditMode.cases(quick: 1_500, full: 15_000) {413            let rows = "[" + (0..<rng.int(0...6)).map { _ in object(0) }.joined(separator: ",") + "]"414            let etherscan = rng.bool()415            let body = etherscan ? "{\"status\":\(rng.pick(["\"1\"", "\"0\"", "1", "null"])),\"message\":\"OK\",\"result\":\(rng.int(0...9) == 0 ? rng.pick(values) : rows)}" : "{\"items\":\(rng.int(0...9) == 0 ? rng.pick(values) : rows)}"416            let endpoint = EVMScriptedEndpoint(["GET": body])417            let config = EndpointConfiguration(esplora: [:], ethereumRPC: [:], ethereumIndexer: ["mainnet": [etherscan ? "https://scan.test/api" : "https://index.test"]], priceAPI: "")418            let indexer = EthereumIndexer(network: .mainnet, configuration: config, transport: endpoint)419            let native = (try? await indexer.transactions(of: address)) ?? []420            let tokenRows = (try? await indexer.tokenTransfers(of: address)) ?? []421            for t in native + tokenRows {422                prop.check((t.tokenDecimals ?? 0) >= 0 && (t.method ?? "").count <= 300, "transfer row out of bounds")423                if etherscan {424                    prop.check(t.from.utf8.count == 42 && (t.to.isEmpty || t.to.utf8.count == 42) && (t.tokenAddress ?? address).utf8.count == 42, "an Etherscan row with a malformed address")425                    prop.check((t.method ?? "").count <= 64, "method name too long")426                }427            }428            for h in (try? await indexer.tokenHoldings(of: address)) ?? [] {429                prop.check((0...36).contains(h.decimals) && h.symbol.count <= 16 && h.name.count <= 48 && h.address.utf8.count == 42, "token holding out of bounds")430            }431            prop.check(true)432        }433        // an account address that is not one is never put in a URL434        for bad in ["", "0x", address + "/../x", address + "?module=x", "0x" + String(repeating: "g", count: 40), " " + address] {435            let endpoint = EVMScriptedEndpoint(["GET": "{\"items\":[]}"])436            let indexer = EthereumIndexer(network: .mainnet, configuration: EndpointConfiguration(esplora: [:], ethereumRPC: [:], ethereumIndexer: ["mainnet": ["https://index.test"]], priceAPI: ""), transport: endpoint)437            let transactions = try? await indexer.transactions(of: bad), transfers = try? await indexer.tokenTransfers(of: bad), holdings = try? await indexer.tokenHoldings(of: bad)438            prop.check(transactions == nil && transfers == nil && holdings == nil && endpoint.total == 0, "a malformed account reached the network: \(bad)")439        }440        prop.finish()441    }442443    @Test func endpointConfigurationDecoding() throws {444        let seed = AuditSeed.make("evm.endpoint-configuration")445        var rng = AuditRNG(seed: seed)446        var prop = Prop("decode(encode(c)) = c; a stored value never gains an endpoint it did not name (schema 2); schema 1 gains the defaults of the networks it could not know; unacceptable URLs are never used", algorithm: "Endpoint configuration", seed: seed)447        let names = EthereumNetwork.allCases.map(\.rawValue) + BitcoinNetwork.allCases.map(\.rawValue) + ["unknown", "", "MAINNET", "../x"]448        let urls = ["https://a.test", "https://b.test/api", "http://localhost:8545", "http://evil.test", "ftp://x", "https://user:pw@x.test", "", "not a url", "http://10.0.0.1", "https://" + String(repeating: "a", count: 400) + ".test"]449        func table() -> [String: [String]] {450            var out = [String: [String]]()451            for _ in 0..<rng.int(0...6) { out[rng.pick(names)] = (0..<rng.int(0...3)).map { _ in rng.pick(urls) } }452            return out453        }454        for _ in 0..<AuditMode.cases(quick: 3_000, full: 30_000) {455            let c = EndpointConfiguration(esplora: table(), blockbook: table(), bitcore: table(), ethereumRPC: table(), ethereumIndexer: table(), priceAPI: rng.pick(urls))456            let data = try JSONEncoder().encode(c)457            let decoded = try? JSONDecoder().decode(EndpointConfiguration.self, from: data)458            prop.check(decoded == c, "round trip")459            prop.check((try? JSONEncoder().encode(decoded ?? c)).map { (try? JSONDecoder().decode(EndpointConfiguration.self, from: $0)) == c } ?? false, "second round trip")460            // what the clients keep: acceptable URLs only, in order, for the network asked and no other461            for network in EthereumNetwork.allCases {462                let rpc = EthereumRPC(network: network, configuration: c, transport: EVMScriptedEndpoint([:]))463                let kept = (c.ethereumRPC[network.rawValue] ?? []).filter(EndpointConfiguration.isAcceptable)464                prop.check(rpc.endpoints.map(\.absoluteString) == kept.compactMap { URL(string: $0)?.absoluteString } && rpc.isConfigured == !kept.isEmpty, "endpoints kept for \(network)")465                prop.check(rpc.endpoints.allSatisfy { $0.user == nil && $0.password == nil && ($0.scheme == "https" || $0.scheme == "http") }, "an endpoint with credentials or another scheme was kept")466            }467        }468        // schema 1 (QYVORA 1.0): networks it does not name receive their defaults; the ones it names keep exactly what was stored469        let legacy = Data("{\"esplora\":{\"signet\":[\"https://my.node/api\"]},\"ethereumRPC\":{\"sepolia\":[],\"mainnet\":[\"https://my.rpc\"]},\"ethereumIndexer\":{},\"priceAPI\":\"\"}".utf8)470        let old = try JSONDecoder().decode(EndpointConfiguration.self, from: legacy)471        prop.check(old.ethereumRPC["sepolia"] == [] && old.ethereumRPC["mainnet"] == ["https://my.rpc"] && old.ethereumRPC["base"] == EVMEndpointDefaults.rpc["base"], "schema 1 EVM lists")472        prop.check(old.esplora["signet"] == ["https://my.node/api"] && old.esplora["litecoin"] == EndpointConfiguration.default.esplora["litecoin"] && old.priceAPI.isEmpty, "schema 1 UTXO lists")473        // schema 2: taken as it is474        let current = Data("{\"schema\":2,\"esplora\":{},\"blockbook\":{},\"bitcore\":{},\"ethereumRPC\":{\"base\":[\"https://only.this\"]},\"ethereumIndexer\":{},\"priceAPI\":\"\"}".utf8)475        let now = try JSONDecoder().decode(EndpointConfiguration.self, from: current)476        prop.check(now.ethereumRPC == ["base": ["https://only.this"]] && now.esplora.isEmpty && now.blockbook.isEmpty, "schema 2 is complete as stored")477        // hostile documents: refused or decoded, never a trap478        for text in ["", "null", "[]", "{}", "{\"schema\":\"x\"}", "{\"schema\":-1}", "{\"schema\":9223372036854775807}", "{\"schema\":1e400}", "{\"ethereumRPC\":[]}", "{\"ethereumRPC\":{\"mainnet\":\"x\"}}",479                     "{\"ethereumRPC\":{\"mainnet\":[1]}}", "{\"priceAPI\":1}", "{\"schema\":2,\"ethereumRPC\":{\"mainnet\":[null]}}", "{\"schema\":3}", "{\"schema\":0}"] {480            let decoded = try? JSONDecoder().decode(EndpointConfiguration.self, from: Data(text.utf8))481            prop.check(decoded == nil || decoded.map { (try? JSONEncoder().encode($0)) != nil } == true, "hostile document \(text)")482        }483        prop.finish()484    }485}486487/// Keeps a value alive without a fuzz harness (the optimiser must not drop the computation that produced it).488@inline(never) func fuzzless<T>(_ value: T) { withExtendedLifetime(value) {} }489
Files main
Menu

Theme