Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : security/tests/Tests/DifferentialAuditTests/EVMChainsDiffTests.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 QyvoraCore44import QyvoraMath45import QyvoraSecp256k146import Testing4748@testable import QyvoraEthereum4950// EVM networks against independent code (security/tests/oracles/mc/evm.py):51// signing eth-account signs the same EIP-1559 fields for every chain identifier of the network table and for52// boundary identifiers — unsigned payload (pyrlp), signing hash (pycryptodome and eth-account), r, s and53// yParity (libsecp256k1, RFC 6979), raw transaction, hash and sender must be byte-identical;54// replay a signature made for chain A, read as a signature for chain B, recovers another account, here and in eth-keys;55// table the chain identifiers exist in the registry shipped with eth-utils (ethereum-lists/chains);56// oracle call data of getL1Fee(bytes) against eth-abi, selectors against Keccak-256, return data against a strict ABI decoder;57// tokens every built-in contract address against the EIP-55 checksum of eth-utils.5859@Suite struct EVMChainsDifferential {60 static let script = "evm"61 static let boundaryChains: [UInt64] = [1, 10, 56, 137, 8_453, 42_161, 43_114, 1 << 31, 1 << 53, UInt64.max, 0, 2, 127, 128, 255, 256, 65_535, 65_536, (1 << 63) - 1, 1 << 63]6263 static func dec(_ v: UInt256) -> String { v.description }6465 static func randomUInt256(_ rng: inout AuditRNG, maxBytes: Int) -> UInt256 {66 UInt256(bigEndian: rng.bytes(rng.int(0...maxBytes)))!67 }6869 static func randomTransaction(_ rng: inout AuditRNG, chain: UInt64) -> EIP1559Transaction {70 let fee = randomUInt256(&rng, maxBytes: rng.pick([1, 5, 8, 16, 32]))71 var tip = randomUInt256(&rng, maxBytes: 32)72 if tip > fee { tip = rng.bool() ? fee : UInt256.zero }73 var access = [EIP1559Transaction.AccessListEntry]()74 if rng.int(0...3) == 0 {75 for _ in 0..<rng.int(1...3) {76 access.append(.init(address: EthereumAddress(bytes: rng.bytes(20))!,77 storageKeys: (0..<rng.int(0...3)).map { _ in rng.bytes(32, orEdge: [Bytes(repeating: 0, count: 32), Bytes(repeating: 0xff, count: 32)], oneIn: 5) }))78 }79 }80 return EIP1559Transaction(81 chainID: chain, nonce: rng.pick([0, 1, 127, 128, 255, 256, rng.next() >> 40, rng.next(), UInt64.max - 1, UInt64.max]),82 maxPriorityFeePerGas: tip, maxFeePerGas: fee, gasLimit: rng.pick([21_000, 0, 1, 100_000, 200_000, rng.next() >> 32, rng.next(), UInt64.max]),83 to: rng.int(0...5) == 0 ? nil : EthereumAddress(bytes: rng.bytes(20, orEdge: [Bytes(repeating: 0, count: 20), Bytes(repeating: 0xff, count: 20)], oneIn: 20))!,84 value: randomUInt256(&rng, maxBytes: rng.pick([0, 1, 8, 9, 32])),85 data: rng.bytes(rng.pick([0, 0, 1, 4, 36, 55, 56, 68, 300, 1_024]), orEdge: [[0], [0x7f], [0x80], [0xc0]], oneIn: 10), accessList: access)86 }8788 static func oracleCase(_ tx: EIP1559Transaction, key: Bytes) -> Case {89 [90 "chain": String(tx.chainID), "nonce": String(tx.nonce), "prio": dec(tx.maxPriorityFeePerGas), "fee": dec(tx.maxFeePerGas),91 "gas": String(tx.gasLimit), "to": tx.to.map { hex($0.bytes) } ?? "", "value": dec(tx.value), "data": hex(tx.data),92 "access": tx.accessList.map { [hex($0.address.bytes), $0.storageKeys.map(hex)] as [Any] }, "sk": hex(key),93 ]94 }9596 static func randomKey(_ rng: inout AuditRNG) -> Bytes {97 while true {98 let k = rng.bytes(32)99 if Secp256k1.isValidPrivateKey(k) { return k }100 }101 }102103 @Test func eip1559AcrossChainIdentifiers() throws {104 let name = "evm-eip1559-across-chain-ids"105 guard MCOracle.available(Self.script, campaign: name, needs: ["eth-account", "rlp", "pycryptodome", "coincurve"]) else { return }106 let seed = DiffSeed.make(name)107 var rng = AuditRNG(seed: seed)108 let chains = EthereumNetwork.allCases.map(\.chainID) + Self.boundaryChains109 var tally = DiffTally(name, algorithm: "EIP-1559 transaction on \(Set(chains).count) chain identifiers",110 parameterSet: "14 networks of the table + boundaries (0, 1, 2^31, 2^53, 2^63, 2^64−1…): unsigned payload, signing hash, r, s, yParity, raw, hash, sender",111 oracle: MCOracle.label(Self.script, "eth-account", "sign_transaction, recover_transaction") + ", " + MCOracle.label(Self.script, "rlp") + ", "112 + MCOracle.label(Self.script, "pycryptodome", "Keccak-256") + ", " + MCOracle.label(Self.script, "coincurve", "libsecp256k1 through eth-keys"), seed: seed)113 var inputs = [(tx: EIP1559Transaction, key: Bytes)]()114 let perChain = AuditMode.cases(quick: 40, full: 400)115 for chain in chains {116 for _ in 0..<perChain { inputs.append((Self.randomTransaction(&rng, chain: chain), Self.randomKey(&rng))) }117 }118 let answers = try MCOracle.batch(Self.script, "sign", inputs.map { Self.oracleCase($0.tx, key: $0.key) })119 for (i, a) in zip(inputs, answers) {120 guard a.oracleError == nil else {121 tally.check(false, "the reference refused chain=\(i.tx.chainID) tx=\(hex(i.tx.unsignedPayload)): \(a.oracleError ?? "")")122 continue123 }124 let signed = try? i.tx.sign(privateKey: i.key)125 var ok = i.tx.unsignedPayload == a.bytes("unsigned") && i.tx.signingHash == a.bytes("sighash") && a.bytes("sighash") == a.bytes("typed_hash")126 ok = ok && signed != nil && signed?.r == a.bytes("r") && signed?.s == a.bytes("s") && signed.map { Int($0.yParity) } == a["v"] as? Int127 ok = ok && signed?.raw == a.bytes("raw") && signed?.hash == a.bytes("hash") && a.bytes("hash") == a.bytes("keccak_raw")128 let sender = (try? signed?.sender())?.checksummed129 ok = ok && sender != nil && sender == a.string("sender") && sender == a.string("recovered")130 // the chain identifier is inside what was signed, and our decoders return the same transaction131 ok = ok && (try? EIP1559Transaction.decodeUnsigned(i.tx.unsignedPayload))?.chainID == i.tx.chainID132 ok = ok && signed.flatMap { try? SignedEIP1559Transaction.decode($0.raw) } == signed133 tally.check(ok, "chain=\(i.tx.chainID) tx=\(hex(i.tx.unsignedPayload)) private_key=\(hex(i.key)) ours_raw=\(signed.map { hex($0.raw) } ?? "nil") reference=\(a)")134 }135 // the reference decodes our raw bytes: sender, hash and chain identifier136 let recovered = try MCOracle.batch(Self.script, "recover", inputs.map { i in ["raw": hex((try? i.tx.sign(privateKey: i.key))?.raw ?? [])] })137 for (i, r) in zip(inputs, recovered) {138 let me = try? EthereumAddress(publicKey: Secp256k1.publicKey(privateKey: i.key, compressed: false))139 tally.check(r.string("sender") == me?.checksummed && r.string("chain") == String(i.tx.chainID) && r.string("nonce") == String(i.tx.nonce) && r.string("value") == Self.dec(i.tx.value),140 "recover chain=\(i.tx.chainID) tx=\(hex(i.tx.unsignedPayload)) reference=\(r)")141 }142 #expect(tally.finish() == 0)143 }144145 /// Replay protection: the chain identifier is part of the signed payload, so the same r, s and yParity attached to146 /// the same fields with another chain identifier recover another account (or no account at all).147 @Test func aSignatureDoesNotCarryOverToAnotherChain() throws {148 let name = "evm-cross-chain-replay"149 guard MCOracle.available(Self.script, campaign: name, needs: ["eth-keys", "rlp", "pycryptodome"]) else { return }150 let seed = DiffSeed.make(name)151 var rng = AuditRNG(seed: seed)152 var tally = DiffTally(name, algorithm: "EIP-155 / EIP-1559 replay protection", parameterSet: "every ordered pair of the 14 networks, random transactions: the relabelled signature never recovers the signer",153 oracle: MCOracle.label(Self.script, "eth-keys", "public key recovery") + ", " + MCOracle.label(Self.script, "rlp"), seed: seed)154 var cases = [Case]()155 var expectations = [(signer: String, from: UInt64, to: UInt64, relabelled: Bytes)]()156 let rounds = AuditMode.cases(quick: 2, full: 20)157 for _ in 0..<rounds {158 for a in EthereumNetwork.allCases {159 let key = Self.randomKey(&rng)160 let tx = Self.randomTransaction(&rng, chain: a.chainID)161 let signed = try tx.sign(privateKey: key)162 let signer = try signed.sender()163 for b in EthereumNetwork.allCases where b != a {164 var other = tx165 other.chainID = b.chainID166 let relabelled = SignedEIP1559Transaction(transaction: other, yParity: signed.yParity, r: signed.r, s: signed.s)167 // here: the relabelled bytes either do not decode (no valid signature) or name another sender168 let decoded = try? SignedEIP1559Transaction.decode(relabelled.raw)169 let sender = try? decoded?.sender()170 tally.check(sender != signer && (try? relabelled.sender()) != signer, "replay accepted here: \(a) → \(b) tx=\(hex(signed.raw))")171 tally.check(other.signingHash != tx.signingHash && other.unsignedPayload != tx.unsignedPayload, "the chain identifier is not in the signed payload: \(a) → \(b)")172 cases.append(["raw": hex(signed.raw), "chain": String(b.chainID)])173 expectations.append((signer.checksummed, a.chainID, b.chainID, relabelled.raw))174 }175 }176 }177 let answers = try MCOracle.batch(Self.script, "relabel", cases)178 for (e, a) in zip(expectations, answers) {179 tally.check(a.oracleError == nil && a.string("sender") != e.signer, "replay accepted by the reference: \(e.from) → \(e.to) reference=\(a)")180 // both sides built the same relabelled bytes: the comparison is about the same object181 if let raw = a.bytes("raw") { tally.check(raw == e.relabelled, "relabelled encoding differs: \(e.from) → \(e.to)") }182 }183 #expect(tally.finish() == 0)184 }185186 @Test func chainIdentifiersExistInTheRegistryOfEthUtils() throws {187 let name = "evm-network-table-registry"188 guard MCOracle.available(Self.script, campaign: name, needs: ["eth-utils"]) else { return }189 var tally = DiffTally(name, algorithm: "EVM network table", parameterSet: "chain identifier → network name in the registry shipped with eth-utils (ethereum-lists/chains)",190 oracle: MCOracle.label(Self.script, "eth-utils", "eth_utils.network"), seed: 0)191 // a word the registry's name of the network must contain192 let keyword: [EthereumNetwork: [String]] = [193 .mainnet: ["Ethereum"], .sepolia: ["Sepolia"], .base: ["Base"], .baseSepolia: ["Base", "Sepolia"], .arbitrum: ["Arbitrum"], .arbitrumSepolia: ["Arbitrum", "Sepolia"],194 .optimism: ["OP"], .optimismSepolia: ["OP", "Sepolia"], .polygon: ["Polygon"], .polygonAmoy: ["Amoy"], .bsc: ["BNB"], .bscTestnet: ["BNB", "Testnet"],195 .avalanche: ["Avalanche"], .avalancheFuji: ["Avalanche", "Fuji"],196 ]197 let answers = try MCOracle.batch(Self.script, "network", EthereumNetwork.allCases.map { ["chain": String($0.chainID)] })198 for (n, a) in zip(EthereumNetwork.allCases, answers) {199 let registryName = a.string("name") ?? ""200 tally.check(a.oracleError == nil && a.string("chain") == String(n.chainID), "\(n): chain \(n.chainID) is not in the registry: \(a)")201 tally.check((keyword[n] ?? ["?"]).allSatisfy { registryName.localizedCaseInsensitiveContains($0) }, "\(n): chain \(n.chainID) is \"\(registryName)\" in the registry, the table says \"\(n.displayName)\"")202 }203 #expect(tally.finish() == 0)204 }205206 @Test func opStackOracleCallAndReturnData() throws {207 let name = "evm-opstack-oracle-abi"208 guard MCOracle.available(Self.script, campaign: name, needs: ["eth-abi", "pycryptodome"]) else { return }209 let seed = DiffSeed.make(name)210 var rng = AuditRNG(seed: seed)211 var tally = DiffTally(name, algorithm: "OP-Stack GasPriceOracle getL1Fee(bytes)", parameterSet: "selector, call data, return data (one uint256)",212 oracle: MCOracle.label(Self.script, "eth-abi", "encode, strict decode") + ", " + MCOracle.label(Self.script, "pycryptodome", "Keccak-256"), seed: seed)213 // selectors and topics214 let signatures: [(String, Bytes)] = [215 ("getL1Fee(bytes)", OPStackGasOracle.getL1FeeSelector), ("transfer(address,uint256)", ERC20.transferSelector), ("approve(address,uint256)", ERC20.approveSelector),216 ("balanceOf(address)", ERC20.balanceOfSelector), ("allowance(address,address)", ERC20.allowanceSelector), ("decimals()", ERC20.decimalsSelector),217 ("symbol()", ERC20.symbolSelector), ("name()", ERC20.nameSelector),218 ]219 for ((signature, ours), a) in zip(signatures, try MCOracle.batch(Self.script, "selector", signatures.map { ["signature": $0.0] })) {220 tally.check(a.bytes("selector") == ours && ERC20.selector(signature) == ours, "selector of \(signature)")221 }222 for ((signature, ours), a) in zip([("Transfer(address,address,uint256)", ERC20.transferTopic), ("Approval(address,address,uint256)", ERC20.approvalTopic)],223 try MCOracle.batch(Self.script, "selector", [["signature": "Transfer(address,address,uint256)"], ["signature": "Approval(address,address,uint256)"]])) {224 tally.check(a.bytes("topic") == ours, "topic of \(signature)")225 }226 // call data: random payloads, and the unsigned payloads of random transactions227 var payloads = [Bytes]()228 for length in [0, 1, 2, 31, 32, 33, 63, 64, 65, 255, 256] { payloads.append(rng.bytes(length)) }229 for _ in 0..<AuditMode.cases(quick: 300, full: 3_000) {230 payloads.append(rng.bool() ? rng.bytes(rng.int(0...600)) : Self.randomTransaction(&rng, chain: rng.pick([10, 8_453, 84_532, 11_155_420])).unsignedPayload)231 }232 for (p, a) in zip(payloads, try MCOracle.batch(Self.script, "l1fee_call", payloads.map { ["payload": hex($0)] })) {233 let ours = OPStackGasOracle.getL1FeeCall(p)234 tally.check(ours == a.bytes("call") && ours.count % 32 == 4, "getL1Fee call data for \(p.count) bytes: ours=\(hex(Bytes(ours.prefix(80)))) reference=\(a)")235 }236 // return data: ours accepts exactly one word below the ceiling; the reference decoder (strict) accepts a word followed by anything237 var returns = [Bytes]()238 let ceiling = OPStackGasOracle.feeCeiling239 for word in [UInt256.zero, UInt256(1), ceiling - UInt256(1), ceiling, ceiling + UInt256(1), .max] { returns.append(word.bytes32) }240 for length in [0, 1, 31, 33, 63, 64, 65, 96] { returns.append(rng.bytes(length)) }241 for _ in 0..<AuditMode.cases(quick: 300, full: 3_000) {242 switch rng.int(0...3) {243 case 0: returns.append(Bytes(repeating: 0, count: 32 - 8) + rng.bytes(8))244 case 1: returns.append(rng.bytes(32))245 case 2: returns.append(Bytes(repeating: 0, count: 24) + rng.bytes(8) + rng.bytes(rng.int(1...40)))246 default: returns.append(rng.bytes(rng.int(0...80)))247 }248 }249 for (r, a) in zip(returns, try MCOracle.batch(Self.script, "abi_uint", returns.map { ["data": hex($0)] })) {250 let word = ERC20.decodeUInt(r), fee = OPStackGasOracle.decodeFee(r)251 if let value = a.string("value") {252 if r.count == 32 {253 tally.check(word?.description == value, "uint256 return data: ours=\(word?.description ?? "nil") reference=\(value)")254 tally.check(fee == (word.flatMap { $0 < ceiling ? $0 : nil }), "fee bound for \(value)")255 } else {256 // policy difference: trailing bytes after the word are refused here, accepted by the reference257 tally.check(word == nil && fee == nil, "return data of \(r.count) bytes accepted here")258 tally.verdict(false)259 }260 } else {261 tally.check(word == nil && fee == nil, "return data the reference refuses was accepted here: \(hex(r))")262 }263 }264 #expect(tally.finish() == 0)265 }266267 @Test func builtInTokenAddressesCarryTheirChecksum() throws {268 let name = "evm-built-in-token-checksums"269 guard MCOracle.available(Self.script, campaign: name, needs: ["eth-utils"]) else { return }270 var tally = DiffTally(name, algorithm: "EIP-55 checksum of the built-in token contracts and of the OP-Stack oracle", parameterSet: "every row of the seven lists",271 oracle: MCOracle.label(Self.script, "eth-utils", "to_checksum_address"), seed: 0)272 var rows = [(String, String)]()273 for network in EthereumNetwork.mainNetworks { for row in BuiltInTokens.table(for: network) { rows.append(("\(network) \(row.0)", row.3)) } }274 rows.append(("OP-Stack GasPriceOracle", EVMPredeploys.opStackGasPriceOracle))275 let answers = try MCOracle.batch(Self.script, "checksum", rows.map { ["address": String($0.1.dropFirst(2))] })276 for ((label, written), a) in zip(rows, answers) {277 tally.check(a.string("address") == written, "\(label): written \(written), checksum form \(a.string("address") ?? a.oracleError ?? "?")")278 tally.check(EthereumAddress(written)?.checksummed == a.string("address"), "\(label): our checksum differs from the reference")279 }280 #expect(tally.finish() == 0)281 }282}283