SPB Git

Repository Public

EVMChainsAuditRegressionTests.swift 7.7 KB 131 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Tests/QyvoraNetworkingTests/EVMChainsAuditRegressionTests.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 Foundation42import Testing43import QyvoraMath44import QyvoraCore45import QyvoraEthereum46@testable import QyvoraNetworking4748/// Regression tests of the multi-chain security audit, area "EVM networks" (finding QYV-SVC-083), and the checks of49/// the endpoint rules the review relied on.50@Suite struct EVMChainsAuditRegressionTests {51    /// QYV-SVC-083. `FeeData` has a public initializer; `maxFee` fell back to `baseFee + baseFee + priorityFee` with52    /// the trapping operator when the fee rules refused the figures, so a value built from large figures stopped the53    /// process instead of giving a number.54    @Test func feeDataMaxFeeNeverTraps() {55        let huge = EthereumRPC.FeeData(network: .sepolia, baseFee: .max, priorityFee: .max)56        #expect(huge.maxFee == .max)57        #expect((try? huge.gasFees()) == nil)58        let half = UInt256(bigEndian: [0x80] + Bytes(repeating: 0, count: 31))!59        #expect(EthereumRPC.FeeData(network: .polygon, baseFee: half, priorityFee: .zero).maxFee == .max)60        #expect(EthereumRPC.FeeData(network: .bsc, baseFee: .zero, priorityFee: .max, gasPrice: nil).maxFee == .max)61        // BNB Smart Chain without a gas price: the rules refuse, the display figure is the plain formula62        #expect(EthereumRPC.FeeData(network: .bsc, baseFee: .zero, priorityFee: UInt256(7), gasPrice: nil).maxFee == UInt256(7))63        // ordinary figures: the rules apply64        let normal = EthereumRPC.FeeData(network: .sepolia, baseFee: UInt256(10_000_000_000), priorityFee: UInt256(1_000_000_000))65        #expect(normal.maxFee == UInt256(21_000_000_000))66        for network in EthereumNetwork.allCases {67            for base in [UInt256.zero, UInt256(1), UInt256(9_999_999_999_999), UInt256(10_000_000_000_000), .max] {68                for tip in [UInt256.zero, UInt256(1), UInt256(9_999_999_999_999), UInt256(10_000_000_000_000), .max] {69                    for price in [nil, UInt256.zero, UInt256(1), UInt256.max] as [UInt256?] {70                        let data = EthereumRPC.FeeData(network: network, baseFee: base, priorityFee: tip, gasPrice: price)71                        let display = data.maxFee72                        if let fees = try? data.gasFees() {73                            #expect(display == fees.maxFeePerGas && fees.maxPriorityFeePerGas <= fees.maxFeePerGas && fees.maxFeePerGas < EVMFeeRules.maxFeePerGasCeiling)74                        }75                    }76                }77            }78        }79    }8081    /// The endpoint acceptance rule, as the review recorded it: https anywhere; http only to the device itself, a82    /// private IPv4 range, `.local` or `.onion`; never credentials in the URL; nothing that is not a URL.83    @Test func endpointAcceptanceRule() {84        let accepted = [85            "https://rpc.example.org", "https://rpc.example.org:8545/path?x=1", "http://localhost:8545", "http://127.0.0.1:8545", "http://10.0.0.7",86            "http://192.168.1.20:3000/api", "http://172.16.0.1", "http://172.31.255.255", "http://node.local", "http://abcdefghijklmnop.onion/api",87        ]88        let refused = [89            "", "rpc.example.org", "http://rpc.example.org", "ftp://rpc.example.org", "ws://localhost:8545", "wss://rpc.example.org", "file:///etc/hosts",90            "https://user:secret@rpc.example.org", "https://user@rpc.example.org", "http://user:secret@localhost", "http://10.example.com", "http://172.32.0.1",91            "http://172.15.0.1", "http://192.169.0.1", "http://11.0.0.1", "http://256.0.0.1", "http://1.2.3", "http://010.0.0.1.5", "http://0x7f.0.0.1",92            "http://localhost.example.org", "http://evil.local.example.org", "javascript:alert(1)", "https://", "http://[::1]:8545",93        ]94        for url in accepted { #expect(EndpointConfiguration.isAcceptable(url), "\(url)") }95        for url in refused { #expect(!EndpointConfiguration.isAcceptable(url), "\(url)") }96    }9798    /// A network configured with an endpoint of another chain: every EVM network refuses every other chain identifier,99    /// and two endpoints that do not name the same chain are a disagreement whatever they name.100    @Test func chainIdentityIsCheckedForEveryPairOfNetworks() async throws {101        for configured in EthereumNetwork.allCases {102            for served in EthereumNetwork.allCases {103                let transport = ScriptedRPCTransport { _, method, _ in method == "eth_chainId" ? .string(UInt256(served.chainID).hexQuantity) : nil }104                let rpc = EthereumRPC(network: configured, configuration: Self.configuration(configured, hosts: ["a.test"]), transport: transport)105                if configured == served {106                    try await rpc.verifyChain()107                } else {108                    await #expect(throws: NetworkError.self) { try await rpc.verifyChain() }109                }110            }111            // one honest endpoint and one of another chain112            let transport = ScriptedRPCTransport { host, method, _ in113                guard method == "eth_chainId" else { return nil }114                return .string(UInt256(host == "a.test" ? configured.chainID : configured.chainID + 1).hexQuantity)115            }116            let rpc = EthereumRPC(network: configured, configuration: Self.configuration(configured, hosts: ["a.test", "b.test"]), transport: transport)117            await #expect(throws: NetworkError.self) { try await rpc.verifyChain() }118        }119        // answers that are not a chain identifier120        for answer in [JSONValue.null, .string(""), .string("0x"), .string("1"), .number(1), .string("0x1" + String(repeating: "0", count: 64)), .string("0xzz"), .array([]), .bool(true)] {121            let transport = ScriptedRPCTransport { _, method, _ in method == "eth_chainId" ? answer : nil }122            let rpc = EthereumRPC(network: .mainnet, configuration: Self.configuration(.mainnet, hosts: ["a.test"]), transport: transport)123            await #expect(throws: NetworkError.self) { try await rpc.verifyChain() }124        }125    }126127    static func configuration(_ network: EthereumNetwork, hosts: [String]) -> EndpointConfiguration {128        EndpointConfiguration(esplora: [:], ethereumRPC: [network.rawValue: hosts.map { "https://\($0)" }], ethereumIndexer: [:], priceAPI: "")129    }130}131
Files main
Menu

Theme