Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project : QYVORA7# File : security/tests/oracles/mc/evm.py8# 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# =============================================================================4041"""Independent references for the EVM multi-network audit tests (test environment only).4243 python3 -I evm.py <operation> JSON array of cases on stdin, JSON array of answers on stdout4445References:46 - eth-account (`Account.sign_transaction`, `Account.recover_transaction`, `TypedTransaction`): EIP-1559 signing,47 with eth-keys on libsecp256k1 (coincurve) for the RFC 6979 signature;48 - the `rlp` package (pyrlp) for an encoding of the unsigned payload that does not go through eth-account;49 - pycryptodome Keccak-256 for digests, selectors and EIP-55 checksums;50 - eth-abi for the call data of `getL1Fee(bytes)`;51 - eth-utils' network list (generated from ethereum-lists/chains) for chain identifiers and names.5253Numbers travel as decimal strings, bytes as hexadecimal without prefix. A case the reference refuses answers54{"error": "..."}.55"""5657import json58import sys59from importlib import metadata606162def keccak(data):63 from Crypto.Hash import keccak as k6465 return k.new(digest_bits=256, data=data).digest()666768def unhex(s):69 return bytes.fromhex(s or "")707172def int_be(n):73 return n.to_bytes((n.bit_length() + 7) // 8, "big") if n else b""747576def fields(case):77 """The nine fields of an EIP-1559 transaction as the `rlp` package encodes them (integers as minimal big endian)."""78 access = [[unhex(a), [unhex(k) for k in keys]] for a, keys in case.get("access", [])]79 return [80 int_be(int(case["chain"])), int_be(int(case["nonce"])), int_be(int(case["prio"])), int_be(int(case["fee"])),81 int_be(int(case["gas"])), unhex(case.get("to", "")), int_be(int(case["value"])), unhex(case.get("data", "")), access,82 ]838485def tx_dict(case):86 from eth_utils import to_checksum_address8788 d = {89 "type": 2,90 "chainId": int(case["chain"]),91 "nonce": int(case["nonce"]),92 "maxPriorityFeePerGas": int(case["prio"]),93 "maxFeePerGas": int(case["fee"]),94 "gas": int(case["gas"]),95 "value": int(case["value"]),96 "data": unhex(case.get("data", "")),97 "accessList": [98 {"address": to_checksum_address(unhex(a)), "storageKeys": ["0x" + k for k in keys]} for a, keys in case.get("access", [])99 ],100 }101 to = unhex(case.get("to", ""))102 d["to"] = to_checksum_address(to) if to else b""103 return d104105106def op_sign(case):107 import rlp108 from eth_account import Account109 from eth_account.typed_transactions import TypedTransaction110111 d = tx_dict(case)112 unsigned = b"\x02" + rlp.encode(fields(case))113 sighash = keccak(unsigned)114 typed_hash = bytes(TypedTransaction.from_dict(d).hash())115 signed = Account.sign_transaction(d, unhex(case["sk"]))116 raw = bytes(signed.raw_transaction)117 return {118 "unsigned": unsigned.hex(),119 "sighash": sighash.hex(),120 "typed_hash": typed_hash.hex(),121 "raw": raw.hex(),122 "hash": bytes(signed.hash).hex(),123 "keccak_raw": keccak(raw).hex(),124 "r": format(signed.r, "064x"),125 "s": format(signed.s, "064x"),126 "v": signed.v,127 "sender": Account.from_key(unhex(case["sk"])).address,128 "recovered": Account.recover_transaction(raw),129 }130131132def op_recover(case):133 import rlp134 from eth_account import Account135136 raw = unhex(case["raw"])137 if not raw or raw[0] != 2:138 return {"error": "not a type-2 transaction"}139 items = rlp.decode(raw[1:])140 if len(items) != 12:141 return {"error": "not 12 fields"}142 return {143 "sender": Account.recover_transaction(raw),144 "hash": keccak(raw).hex(),145 "chain": str(int.from_bytes(items[0], "big")),146 "nonce": str(int.from_bytes(items[1], "big")),147 "value": str(int.from_bytes(items[6], "big")),148 "to": items[5].hex(),149 }150151152def op_relabel(case):153 """The sender recovered when the signature of `raw` is read as a signature for another chain identifier."""154 import rlp155 from eth_keys import keys156157 raw = unhex(case["raw"])158 items = rlp.decode(raw[1:])159 if len(items) != 12:160 return {"error": "not 12 fields"}161 items[0] = int_be(int(case["chain"]))162 digest = keccak(b"\x02" + rlp.encode(items[:9]))163 v, r, s = (int.from_bytes(x, "big") for x in items[9:12])164 try:165 public = keys.Signature(vrs=(v, r, s)).recover_public_key_from_msg_hash(digest)166 except Exception as e: # noqa: BLE001 - the reference refusing is an answer167 return {"sender": "", "refused": type(e).__name__}168 return {"sender": public.to_checksum_address(), "raw": (b"\x02" + rlp.encode(items)).hex()}169170171def op_selector(case):172 digest = keccak(case["signature"].encode())173 return {"selector": digest[:4].hex(), "topic": digest.hex()}174175176def op_l1fee_call(case):177 from eth_abi import encode178179 payload = unhex(case["payload"])180 return {"call": (keccak(b"getL1Fee(bytes)")[:4] + encode(["bytes"], [payload])).hex()}181182183def op_abi_uint(case):184 """What a strict ABI decoder reads from the return data of a function returning one uint256."""185 from eth_abi import decode186187 data = unhex(case["data"])188 try:189 (value,) = decode(["uint256"], data, strict=True)190 except Exception as e: # noqa: BLE001191 return {"error": type(e).__name__}192 return {"value": str(value), "length": len(data)}193194195def op_checksum(case):196 from eth_utils import to_checksum_address197198 return {"address": to_checksum_address(unhex(case["address"]))}199200201def op_network(case):202 from eth_utils.network import network_from_chain_id203204 try:205 n = network_from_chain_id(int(case["chain"]))206 except Exception as e: # noqa: BLE001207 return {"error": type(e).__name__}208 return {"chain": str(n.chain_id), "name": n.name, "short": n.shortName}209210211def op_versions(_case):212 out = {}213 for name in ("eth-account", "eth-keys", "eth-utils", "eth-abi", "rlp", "coincurve", "pycryptodome", "eth-typing"):214 try:215 out[name] = metadata.version(name)216 except metadata.PackageNotFoundError:217 pass218 try:219 from eth_keys.backends import CoinCurveECCBackend # noqa: F401220 from eth_keys import keys221222 out["eth-keys-backend"] = type(keys.PrivateKey(b"\x01" * 32).backend).__name__ if hasattr(keys.PrivateKey(b"\x01" * 32), "backend") else "default"223 except Exception: # noqa: BLE001224 pass225 return out226227228OPS = {229 "sign": op_sign, "recover": op_recover, "relabel": op_relabel, "selector": op_selector, "l1fee_call": op_l1fee_call,230 "abi_uint": op_abi_uint, "checksum": op_checksum, "network": op_network, "versions": op_versions,231}232233234def main():235 op = OPS[sys.argv[1]]236 out = []237 for case in json.load(sys.stdin):238 try:239 out.append(op(case))240 except Exception as e: # noqa: BLE001 - one refused case must not stop the batch241 out.append({"error": f"{type(e).__name__}: {e}"[:300]})242 json.dump(out, sys.stdout)243244245if __name__ == "__main__":246 main()247