From bdcb8313e8548a9b03efc3c35e8d9a8368349920 Mon Sep 17 00:00:00 2001 From: panos Date: Mon, 9 Nov 2026 16:33:15 +0800 Subject: [PATCH 01/16] update reth dep --- Cargo.lock | 2197 ++++++++++++++--------------- Cargo.toml | 193 +-- bin/morph-statetest/Cargo.toml | 4 +- crates/chainspec/Cargo.toml | 3 +- crates/chainspec/src/hardfork.rs | 59 +- crates/chainspec/src/spec.rs | 7 - crates/consensus/Cargo.toml | 2 +- crates/evm/Cargo.toml | 9 +- crates/payload/builder/Cargo.toml | 7 +- crates/proofs/Cargo.toml | 3 +- crates/revm/Cargo.toml | 3 +- crates/rpc/Cargo.toml | 6 +- crates/txpool/Cargo.toml | 4 +- 13 files changed, 1237 insertions(+), 1260 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index cb3caa41..40986564 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -101,9 +101,9 @@ dependencies = [ [[package]] name = "alloy-consensus" -version = "2.4.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12a542fe1e6a48cfd010a9e8eba1235436de58ee0f1415e588c27d5d556e98df" +checksum = "727016fed834c2392d014dd697ea473f3e47bcec31ba31ccffa9c1d18ed904e5" dependencies = [ "alloy-eips", "alloy-primitives", @@ -117,21 +117,21 @@ dependencies = [ "c-kzg", "derive_more", "either", - "k256", + "k256 0.13.4", "once_cell", "rand 0.8.6", "secp256k1 0.30.0", "serde", "serde_json", "serde_with", - "thiserror 2.0.18", + "thiserror 2.0.21", ] [[package]] name = "alloy-consensus-any" -version = "2.4.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05ac1559726a5e71d6dbab59cbd8ad0988c762105d2ae41ae4f3241a3166262d" +checksum = "6ea5ae60bbb3ce9dc52685a70a3755ad4432045fd38079b763cfe5127c706134" dependencies = [ "alloy-consensus", "alloy-eips", @@ -171,14 +171,14 @@ dependencies = [ "crc", "rand 0.8.6", "serde", - "thiserror 2.0.18", + "thiserror 2.0.21", ] [[package]] name = "alloy-eip2930" -version = "0.2.3" +version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9441120fa82df73e8959ae0e4ab8ade03de2aaae61be313fbf5746277847ce25" +checksum = "e64579d931b3f8eacc7c9ab0b220e87e9c4816e5c724ede1947b55c2f8e92ae5" dependencies = [ "alloy-primitives", "alloy-rlp", @@ -198,18 +198,18 @@ dependencies = [ "alloy-rlp", "arbitrary", "borsh", - "k256", + "k256 0.13.4", "rand 0.8.6", "serde", "serde_with", - "thiserror 2.0.18", + "thiserror 2.0.21", ] [[package]] name = "alloy-eip7928" -version = "0.4.5" +version = "0.4.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b3b12337f74cbfa451cb04dac173974814a6ff463079e1793aa09600ba8813ab" +checksum = "6a12e1dc70236cfb8e79b96dd8544aed47c39e2f45dc6b51c3703e969e052faa" dependencies = [ "alloy-primitives", "alloy-rlp", @@ -217,19 +217,34 @@ dependencies = [ "borsh", "once_cell", "serde", - "thiserror 2.0.18", + "thiserror 2.0.21", +] + +[[package]] +name = "alloy-eip8141" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36422c14bd57dcd638e276c8c9d7ac09eb16598e3a9dbd34e4b55267d4565b5e" +dependencies = [ + "alloy-primitives", + "alloy-rlp", + "arbitrary", + "borsh", + "serde", + "thiserror 2.0.21", ] [[package]] name = "alloy-eips" -version = "2.4.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d40246adf7468b430fce87945ece8a54ef27fa760dd9f670f5162a412007bdb2" +checksum = "e01905444bd2fc330673f11d2466c0f54e8488f7ce3132b6a5e6497916fca765" dependencies = [ "alloy-eip2124", "alloy-eip2930", "alloy-eip7702", "alloy-eip7928", + "alloy-eip8141", "alloy-primitives", "alloy-rlp", "alloy-serde", @@ -246,31 +261,11 @@ dependencies = [ "sha2 0.10.9", ] -[[package]] -name = "alloy-evm" -version = "0.38.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b307a52f91f7f3aad56b5cb4f54e5eb17dd0b3f4b2c82823301499fe1c6fdaf" -dependencies = [ - "alloy-consensus", - "alloy-eips", - "alloy-hardforks", - "alloy-primitives", - "alloy-rpc-types-engine", - "alloy-rpc-types-eth", - "alloy-sol-types", - "auto_impl", - "derive_more", - "revm", - "thiserror 2.0.18", - "tracing", -] - [[package]] name = "alloy-genesis" -version = "2.4.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4951473e6ff25cdf82eb87b6a1a5fbb4af9c97528398a4a62fbf516198ec5028" +checksum = "53cfa407c1d874cb306187996e30eb551bd98025e60e913e69e298ed2c8ea045" dependencies = [ "alloy-eips", "alloy-primitives", @@ -283,9 +278,9 @@ dependencies = [ [[package]] name = "alloy-hardforks" -version = "0.4.7" +version = "0.4.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "83ba208044232d14d4adbfa77e57d6329f51bc1acc21f5667bb7db72d88a0831" +checksum = "7f03efb8382bf3b19f0bd0b3cdfaa59cb13e57a3a6650f75fae47645873723d5" dependencies = [ "alloy-chains", "alloy-eip2124", @@ -309,24 +304,24 @@ dependencies = [ [[package]] name = "alloy-json-rpc" -version = "2.4.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e5722ea29a9a85ecdba2516c58f50d71e77cd25f8ce7e9f4ee8570ddeee6df1" +checksum = "fff9cb760601d352d1e59aab5803c3fb6dc99824b6883f5c7a781aacd4b54c66" dependencies = [ "alloy-primitives", "alloy-sol-types", "http", "serde", "serde_json", - "thiserror 2.0.18", + "thiserror 2.0.21", "tracing", ] [[package]] name = "alloy-network" -version = "2.4.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2e4d278913f00ab611f5367448a3a800fed173ab791c3cc67b7a1b0d7afd305" +checksum = "e11dfba13dac9e54576bf41e1b7461491367e0bce6a2a4293b9e40ffa3ebd5e9" dependencies = [ "alloy-consensus", "alloy-consensus-any", @@ -345,14 +340,14 @@ dependencies = [ "futures-utils-wasm", "serde", "serde_json", - "thiserror 2.0.18", + "thiserror 2.0.21", ] [[package]] name = "alloy-network-primitives" -version = "2.4.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e4e52ae56d1acaa6b46e9d7015b8ae6c10f3d1c213a32ae70b17426a03ae6729" +checksum = "3819bf6794d25f679d42c3f2b168e12cae08c56bb41d393cb6249b55e6d5933e" dependencies = [ "alloy-consensus", "alloy-eips", @@ -379,7 +374,7 @@ dependencies = [ "hashbrown 0.17.0", "indexmap 2.14.0", "itoa", - "k256", + "k256 0.13.4", "keccak-asm", "paste", "proptest", @@ -395,9 +390,9 @@ dependencies = [ [[package]] name = "alloy-provider" -version = "2.4.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "386124639a5c386329b9f2ef2b42969badbf7bba40422b513e3e5739c516dc34" +checksum = "9f8250dbbc93fab5b00fe0d3c1db3ede67d2a5fdbae8255de70b34ae39da244b" dependencies = [ "alloy-chains", "alloy-consensus", @@ -424,13 +419,14 @@ dependencies = [ "either", "futures", "futures-utils-wasm", + "http", "lru 0.18.4", "parking_lot", "pin-project", "reqwest", "serde", "serde_json", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "tracing", "url", @@ -439,9 +435,9 @@ dependencies = [ [[package]] name = "alloy-pubsub" -version = "2.4.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca2c32b323d8001b6e883444b7433804be0e6d55e4dbfd64e3bd2ba025282b77" +checksum = "fcf12a49e488baefa21619f3ec2ce39f20857153aa1e91619fb5c1ce4d69d893" dependencies = [ "alloy-json-rpc", "alloy-primitives", @@ -483,9 +479,9 @@ dependencies = [ [[package]] name = "alloy-rpc-client" -version = "2.4.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3dfd3ebc1756426a6a9e17979d4467632aff01f359136c50e5320ac6e32d6b8d" +checksum = "1f73519dc8f4ab73dafe90ac47aec4b9055c421c762d770d911eed83fcbef28d" dependencies = [ "alloy-json-rpc", "alloy-primitives", @@ -509,9 +505,9 @@ dependencies = [ [[package]] name = "alloy-rpc-types" -version = "2.4.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "417dc664965e36fc43a4f9c8eb8b2d14067a29c430e23470d2c923c1c977bac7" +checksum = "e30da7fc40ff208becb4ebe462a149045c8613f60ee84f65731a522c67c351fd" dependencies = [ "alloy-primitives", "alloy-rpc-types-engine", @@ -522,9 +518,9 @@ dependencies = [ [[package]] name = "alloy-rpc-types-admin" -version = "2.4.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8bfdc2a2cde178ad3a79594b4fabbc0f2f11be5a98a3363083e91575fc95335c" +checksum = "8d217ca58fed01c4c96d66767af04af39d57ee0d3af016aaf686a2d600aa66d0" dependencies = [ "alloy-genesis", "alloy-primitives", @@ -534,9 +530,9 @@ dependencies = [ [[package]] name = "alloy-rpc-types-anvil" -version = "2.4.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a07bb602ee07767e393b5862f719a1d061deca15e617fbb1f7af49cd49576e4" +checksum = "ad4774d898cc10846f65c426a385071f3e2872876d7f0e7836f1f75ffa54d448" dependencies = [ "alloy-primitives", "alloy-rpc-types-eth", @@ -546,9 +542,9 @@ dependencies = [ [[package]] name = "alloy-rpc-types-any" -version = "2.4.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd0a6cce3f97e5d9c0048081b5d173e0e406c2056c52c012e578a1d451ff0cdc" +checksum = "9c5d320312e4a9481b18185429e57fa161dbf9468414ba5667aff4ebe7bd37e7" dependencies = [ "alloy-consensus-any", "alloy-network-primitives", @@ -561,9 +557,9 @@ dependencies = [ [[package]] name = "alloy-rpc-types-beacon" -version = "2.4.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "905e705ef91d2ed6cf08afbec0f9d79318175785eb146656441e8c644786ee5f" +checksum = "01f0837510a7e7789f99cf86bc0d0e3b54cfa663f25de803dad613364eef9fd3" dependencies = [ "alloy-eips", "alloy-primitives", @@ -574,16 +570,16 @@ dependencies = [ "serde", "serde_json", "serde_with", - "thiserror 2.0.18", + "thiserror 2.0.21", "tree_hash", "tree_hash_derive", ] [[package]] name = "alloy-rpc-types-debug" -version = "2.4.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32f6d7c9462a3cf3bb046d0b870b86f1ce8c6892157491abebba62913e6f53cb" +checksum = "ce17ebd75d90c490897ca320e34bd5c95e0d8620d35ba5842aee9e7b5a90ea21" dependencies = [ "alloy-primitives", "alloy-rlp", @@ -594,9 +590,9 @@ dependencies = [ [[package]] name = "alloy-rpc-types-engine" -version = "2.4.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6e23b5864b3ed3479285ae9af1924266d60cac839dc559d50da868a0734c1d3" +checksum = "77b967576e97165fed3fae1cf6adad964e192293e4ee61d9187afe3ecaa12323" dependencies = [ "alloy-consensus", "alloy-eips", @@ -614,9 +610,9 @@ dependencies = [ [[package]] name = "alloy-rpc-types-eth" -version = "2.4.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1eb4c87dfdde83cd97e03a8c0c5e986b52e14075e02266e322ac6c7eb02e7399" +checksum = "32c475e21fe8a8caa02166b326ed22207a1a0597fc9b0dcdfb46e2fe6f80dadf" dependencies = [ "alloy-consensus", "alloy-consensus-any", @@ -626,19 +622,20 @@ dependencies = [ "alloy-rlp", "alloy-serde", "alloy-sol-types", + "alloy-trie", "arbitrary", "itertools 0.14.0", "serde", "serde_json", "serde_with", - "thiserror 2.0.18", + "thiserror 2.0.21", ] [[package]] name = "alloy-rpc-types-mev" -version = "2.4.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e97bfdac1ec57f53ab2a0dacfedf382aeba1245ecb4ad7ecd8aeb4438a6c3b9b" +checksum = "8c230cc2e3f19a76889664522ffc10d746292f43fa1f57a3a9e20fe011346203" dependencies = [ "alloy-consensus", "alloy-eips", @@ -651,23 +648,23 @@ dependencies = [ [[package]] name = "alloy-rpc-types-trace" -version = "2.4.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d45ae3eadb97bf7933086205b4be0fef82c208bfc3007759e9afdcb6efa74c5" +checksum = "e3d8edefcef7d45a3da4bb869bbee1ee4c71b7437b22b87794f0912c89b5702c" dependencies = [ "alloy-primitives", "alloy-rpc-types-eth", "alloy-serde", "serde", "serde_json", - "thiserror 2.0.18", + "thiserror 2.0.21", ] [[package]] name = "alloy-rpc-types-txpool" -version = "2.4.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce0d7a9ab748d011daac12902ab9aedf8232d9b070bec6344cadd8509d8a6798" +checksum = "2fcacd9928d9788790afcd1d3fd8d0206329d2ef2391070867bafcc20ecf278f" dependencies = [ "alloy-primitives", "alloy-rpc-types-eth", @@ -677,9 +674,9 @@ dependencies = [ [[package]] name = "alloy-serde" -version = "2.4.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ff89f75b8a9d00f659750e9220c31b42d67c69ffc43b2ac8911dfd0506eb4a6" +checksum = "4f44f297d3b9e3ca2c3039e3c0ed69acde9b35edda15381cf78f725b7263fbe2" dependencies = [ "alloy-primitives", "arbitrary", @@ -689,24 +686,24 @@ dependencies = [ [[package]] name = "alloy-signer" -version = "2.4.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69e1f6fae3ade809daa4c32bee35a30a439bb307209d7b42f3995988b5cc74b8" +checksum = "e7de6fd34b5ba1789d482fa800dd97219b34765d6b07633a989a24d2dace770e" dependencies = [ "alloy-primitives", "async-trait", "auto_impl", "either", - "elliptic-curve", - "k256", - "thiserror 2.0.18", + "elliptic-curve 0.13.8", + "k256 0.13.4", + "thiserror 2.0.21", ] [[package]] name = "alloy-signer-local" -version = "2.4.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "621cc39c34b85875858ef149598f3d5f9797dff9a3247f3606fcc06f9b20acc8" +checksum = "d6909c09d586c7b55eced688754d57dde8a6bcbae2b83e69a9b9250e74cfd79e" dependencies = [ "alloy-consensus", "alloy-network", @@ -715,9 +712,9 @@ dependencies = [ "async-trait", "coins-bip32", "coins-bip39", - "k256", + "k256 0.13.4", "rand 0.8.6", - "thiserror 2.0.18", + "thiserror 2.0.21", "zeroize", ] @@ -793,9 +790,9 @@ dependencies = [ [[package]] name = "alloy-transport" -version = "2.4.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06f4ca8484d6295d5165f67de8fdb00ae630ba585efb606f003171286b56441c" +checksum = "e10be13ab13ddadcfaec3320cc6cee83548a1ae32ada214ff864604cbf5c6f77" dependencies = [ "alloy-json-rpc", "auto_impl", @@ -806,7 +803,7 @@ dependencies = [ "parking_lot", "serde", "serde_json", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "tower", "tracing", @@ -816,9 +813,9 @@ dependencies = [ [[package]] name = "alloy-transport-http" -version = "2.4.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8342aa5a7f8dee6d606307eebbc847d9799a823c7e4f37b9c1e32b08715f73c8" +checksum = "df948f2f9530ed0325d789ad98aa08403aaeaf55ddd6eeaf0cda143e02afab39" dependencies = [ "alloy-json-rpc", "alloy-transport", @@ -832,9 +829,9 @@ dependencies = [ [[package]] name = "alloy-transport-ipc" -version = "2.4.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "184e03e1845edd5534f309d3169d93969a819ad1609108d9378fd33059de7547" +checksum = "a757d266eb7927d59a04878c99b450df0da49125e61d641f48fa7c6a82dd4418" dependencies = [ "alloy-json-rpc", "alloy-pubsub", @@ -842,6 +839,7 @@ dependencies = [ "bytes", "futures", "interprocess", + "memchr", "pin-project", "serde", "serde_json", @@ -852,9 +850,9 @@ dependencies = [ [[package]] name = "alloy-transport-ws" -version = "2.4.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee146fb5859e612e95570642a29def87c060c7ce47d14a0caa5ab7ee8570ec2c" +checksum = "8c799e5804cadb4a09e0ff21be230cc1025e5a21e02a41aa9c0022fdb41f830f" dependencies = [ "alloy-pubsub", "alloy-transport", @@ -871,9 +869,9 @@ dependencies = [ [[package]] name = "alloy-trie" -version = "0.9.5" +version = "0.9.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f14b5d9b2c2173980202c6ff470d96e7c5e202c65a9f67884ad565226df7fbb" +checksum = "b94e3e0a88f8db47250ac8a95fb825d020719f833eb1dc661bd3609c3bbece7d" dependencies = [ "alloy-primitives", "alloy-rlp", @@ -885,15 +883,15 @@ dependencies = [ "proptest-derive 0.7.0", "serde", "smallvec", - "thiserror 2.0.18", + "thiserror 2.0.21", "tracing", ] [[package]] name = "alloy-tx-macros" -version = "2.4.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d0626c4f3b2028f7e8db32f53c22d9ecd5939f772317b7c4b6fe5219cb0589a" +checksum = "60fa90c57738ace5b38106c9f743f3d6d47de09a82e82ecfc42702c1acf116ee" dependencies = [ "darling", "proc-macro2", @@ -1034,7 +1032,7 @@ dependencies = [ "fnv", "hashbrown 0.17.0", "itertools 0.14.0", - "num-bigint", + "num-bigint 0.4.6", "num-integer", "num-traits", "zeroize", @@ -1051,7 +1049,7 @@ dependencies = [ "ark-serialize 0.3.0", "ark-std 0.3.0", "derivative", - "num-bigint", + "num-bigint 0.4.6", "num-traits", "paste", "rustc_version 0.3.3", @@ -1071,7 +1069,7 @@ dependencies = [ "derivative", "digest 0.10.7", "itertools 0.10.5", - "num-bigint", + "num-bigint 0.4.6", "num-traits", "paste", "rustc_version 0.4.1", @@ -1092,7 +1090,7 @@ dependencies = [ "digest 0.10.7", "educe", "itertools 0.13.0", - "num-bigint", + "num-bigint 0.4.6", "num-traits", "paste", "zeroize", @@ -1110,7 +1108,7 @@ dependencies = [ "ark-std 0.6.0", "digest 0.10.7", "educe", - "num-bigint", + "num-bigint 0.4.6", "num-traits", "zeroize", ] @@ -1161,7 +1159,7 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "db2fd794a08ccb318058009eefdf15bcaaaaf6f8161eb3345f907222bac38b20" dependencies = [ - "num-bigint", + "num-bigint 0.4.6", "num-traits", "quote", "syn 1.0.109", @@ -1173,7 +1171,7 @@ version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7abe79b0e4288889c4574159ab790824d0033b9fdcb2a112a3182fac2e514565" dependencies = [ - "num-bigint", + "num-bigint 0.4.6", "num-traits", "proc-macro2", "quote", @@ -1186,7 +1184,7 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09be120733ee33f7693ceaa202ca41accd5653b779563608f1234f78ae07c4b3" dependencies = [ - "num-bigint", + "num-bigint 0.4.6", "num-traits", "proc-macro2", "quote", @@ -1199,7 +1197,7 @@ version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a0691ed21ef00ef89c1e9bda832eba493dda3ec2f8d892fb25b705f73f06bb8" dependencies = [ - "num-bigint", + "num-bigint 0.4.6", "num-traits", "proc-macro2", "quote", @@ -1233,7 +1231,7 @@ dependencies = [ "ark-std 0.6.0", "educe", "itertools 0.14.0", - "num-bigint", + "num-bigint 0.4.6", "num-integer", "num-traits", "tracing", @@ -1273,7 +1271,7 @@ checksum = "adb7b85a02b83d2f22f89bd5cac66c9c89474240cb6207cb1efc16d098e822a5" dependencies = [ "ark-std 0.4.0", "digest 0.10.7", - "num-bigint", + "num-bigint 0.4.6", ] [[package]] @@ -1285,7 +1283,7 @@ dependencies = [ "ark-std 0.5.0", "arrayvec", "digest 0.10.7", - "num-bigint", + "num-bigint 0.4.6", ] [[package]] @@ -1297,7 +1295,9 @@ dependencies = [ "ark-serialize-derive", "ark-std 0.6.0", "digest 0.10.7", - "num-bigint", + "num-bigint 0.4.6", + "serde", + "serde-encoded-bytes", "serde_with", ] @@ -1508,6 +1508,12 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" +[[package]] +name = "base16ct" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd307490d624467aa6f74b0eabb77633d1f758a7b25f12bceb0b22e08d9726f6" + [[package]] name = "base256emoji" version = "1.0.2" @@ -1583,7 +1589,7 @@ version = "0.72.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "993776b509cfb49c750f11b8f07a46fa23e0a1386ffc01fb1e7d343efc387895" dependencies = [ - "bitflags 2.11.1", + "bitflags 2.13.2", "cexpr", "clang-sys", "itertools 0.13.0", @@ -1634,9 +1640,9 @@ checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" [[package]] name = "bitflags" -version = "2.11.1" +version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4512299f36f043ab09a583e57bceb5a5aab7a73db1805848e8fef3c9e8c78b3" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" dependencies = [ "serde_core", ] @@ -1649,7 +1655,6 @@ checksum = "1bc2832c24239b0141d5674bb9174f9d68a8b5b3f2753311927c172ca46f7e9c" dependencies = [ "funty", "radium", - "serde", "tap", "wyz", ] @@ -1666,6 +1671,7 @@ dependencies = [ "cfg-if", "constant_time_eq", "cpufeatures 0.3.0", + "rayon-core", ] [[package]] @@ -1694,6 +1700,7 @@ checksum = "dcdb4c7013139a150f9fc55d123186dbfaba0d912817466282c73ac49e71fb45" dependencies = [ "cc", "glob", + "serde", "threadpool", "zeroize", ] @@ -1989,6 +1996,12 @@ dependencies = [ "cc", ] +[[package]] +name = "cmov" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" + [[package]] name = "coins-bip32" version = "0.12.0" @@ -1998,8 +2011,8 @@ dependencies = [ "bs58", "coins-core", "digest 0.10.7", - "hmac", - "k256", + "hmac 0.12.1", + "k256 0.13.4", "serde", "sha2 0.10.9", "thiserror 1.0.69", @@ -2013,7 +2026,7 @@ checksum = "74b169b26623ff17e9db37a539fe4f15342080df39f129ef7631df7683d6d9d4" dependencies = [ "bitvec", "coins-bip32", - "hmac", + "hmac 0.12.1", "once_cell", "pbkdf2", "rand 0.8.6", @@ -2091,8 +2104,8 @@ dependencies = [ "compression-core", "flate2", "memchr", - "zstd", - "zstd-safe", + "zstd 0.13.4", + "zstd-safe 7.4.0", ] [[package]] @@ -2128,6 +2141,12 @@ version = "0.9.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" +[[package]] +name = "const-oid" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" + [[package]] name = "const-str" version = "0.4.3" @@ -2196,6 +2215,12 @@ version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" +[[package]] +name = "cpubits" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae" + [[package]] name = "cpufeatures" version = "0.2.17" @@ -2293,7 +2318,7 @@ version = "0.29.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d8b9f2e4c67f833b660cdb0a3523065869fb35570177239812ed4c905aeff87b" dependencies = [ - "bitflags 2.11.1", + "bitflags 2.13.2", "crossterm_winapi", "derive_more", "document-features", @@ -2332,6 +2357,22 @@ dependencies = [ "zeroize", ] +[[package]] +name = "crypto-bigint" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c035cb64cba03dad2fb921f3e218785e8cf9a41790da5eb3a1400f62fa2be11" +dependencies = [ + "cpubits", + "ctutils", + "getrandom 0.4.2", + "hybrid-array", + "num-traits", + "rand_core 0.10.1", + "subtle", + "zeroize", +] + [[package]] name = "crypto-common" version = "0.1.7" @@ -2349,7 +2390,9 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" dependencies = [ + "getrandom 0.4.2", "hybrid-array", + "rand_core 0.10.1", ] [[package]] @@ -2361,6 +2404,16 @@ dependencies = [ "cipher", ] +[[package]] +name = "ctutils" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f" +dependencies = [ + "cmov", + "subtle", +] + [[package]] name = "curve25519-dalek" version = "4.1.3" @@ -2462,7 +2515,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ccc2776f0c61eca1ca32528f85548abd1a4be8fb53d1b21c013e4f18da1e7090" dependencies = [ "data-encoding", - "syn 1.0.109", + "syn 2.0.117", ] [[package]] @@ -2499,7 +2552,7 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "10d60334b3b2e7c9d91ef8150abfb6fa4c1c39ebbcf4a81c2e346aad939fee3e" dependencies = [ - "thiserror 2.0.18", + "thiserror 2.0.21", ] [[package]] @@ -2519,7 +2572,17 @@ version = "0.7.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" dependencies = [ - "const-oid", + "const-oid 0.9.6", + "zeroize", +] + +[[package]] +name = "der" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a996a108feb8b427a6e12fcf6af4aa83409b79d72c15337d7741368131ee004" +dependencies = [ + "const-oid 0.10.2", "zeroize", ] @@ -2610,7 +2673,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer 0.10.4", - "const-oid", + "const-oid 0.9.6", "crypto-common 0.1.7", "subtle", ] @@ -2622,7 +2685,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" dependencies = [ "block-buffer 0.12.1", + "const-oid 0.10.2", "crypto-common 0.2.2", + "ctutils", ] [[package]] @@ -2727,13 +2792,29 @@ version = "0.16.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca" dependencies = [ - "der", + "der 0.7.10", "digest 0.10.7", - "elliptic-curve", - "rfc6979", - "serdect", - "signature", - "spki", + "elliptic-curve 0.13.8", + "rfc6979 0.4.0", + "serdect 0.2.0", + "signature 2.2.0", + "spki 0.7.3", +] + +[[package]] +name = "ecdsa" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0681a4fc24c767085329728d8dfba959af91228aa4610cca4f8ce317ba46ae0" +dependencies = [ + "der 0.8.3", + "digest 0.11.3", + "elliptic-curve 0.14.3", + "rfc6979 0.6.0", + "serdect 0.4.3", + "signature 3.0.0", + "spki 0.8.1", + "zeroize", ] [[package]] @@ -2742,8 +2823,8 @@ version = "2.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53" dependencies = [ - "pkcs8", - "signature", + "pkcs8 0.10.2", + "signature 2.2.0", ] [[package]] @@ -2788,16 +2869,37 @@ version = "0.13.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47" dependencies = [ - "base16ct", - "crypto-bigint", + "base16ct 0.2.0", + "crypto-bigint 0.5.5", "digest 0.10.7", - "ff", + "ff 0.13.1", "generic-array", - "group", - "pkcs8", + "group 0.13.0", + "pkcs8 0.10.2", "rand_core 0.6.4", - "sec1", - "serdect", + "sec1 0.7.3", + "serdect 0.2.0", + "subtle", + "zeroize", +] + +[[package]] +name = "elliptic-curve" +version = "0.14.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "900f37e7e18d74a2347389af6cd69e3a30d5cc9e697f40004865679aa75e9c7c" +dependencies = [ + "base16ct 1.0.0", + "crypto-bigint 0.7.10", + "crypto-common 0.2.2", + "digest 0.11.3", + "ff 0.14.0", + "group 0.14.0", + "hybrid-array", + "pkcs8 0.11.0", + "rand_core 0.10.1", + "sec1 0.8.1", + "serdect 0.4.3", "subtle", "zeroize", ] @@ -2813,7 +2915,7 @@ dependencies = [ "bytes", "ed25519-dalek", "hex", - "k256", + "k256 0.13.4", "log", "rand 0.8.6", "secp256k1 0.30.0", @@ -2909,6 +3011,75 @@ dependencies = [ "syn 2.0.117", ] +[[package]] +name = "evm2" +version = "0.1.0" +source = "git+https://www.github.com/alloy-rs/evm2?rev=01df8f6a396d0250da286cb763faa6ec292d65b5#01df8f6a396d0250da286cb763faa6ec292d65b5" +dependencies = [ + "alloy-consensus", + "alloy-eip7928", + "alloy-eips", + "alloy-primitives", + "ark-bls12-381", + "ark-bn254", + "ark-ec", + "ark-ff 0.6.0", + "ark-serialize 0.6.0", + "arrayref", + "aurora-engine-modexp", + "auto_impl", + "aws-lc-rs", + "bitflags 2.13.2", + "blst", + "c-kzg", + "derive-where", + "evm2-macros", + "k256 0.14.0", + "once_cell", + "p256", + "phf", + "ripemd 0.2.0", + "ruint", + "secp256k1 0.33.1", + "serde", + "sha2 0.11.0", + "thiserror 2.0.21", + "triomphe", + "typeid", + "wincode", +] + +[[package]] +name = "evm2-inspectors" +version = "0.1.0" +source = "git+https://www.github.com/alloy-rs/evm2?rev=01df8f6a396d0250da286cb763faa6ec292d65b5#01df8f6a396d0250da286cb763faa6ec292d65b5" +dependencies = [ + "alloy-consensus", + "alloy-eip2930", + "alloy-eips", + "alloy-primitives", + "alloy-rpc-types-eth", + "alloy-rpc-types-trace", + "alloy-sol-types", + "anstyle", + "colorchoice", + "evm2", + "num-bigint 0.5.1", + "serde", + "serde_json", + "thiserror 2.0.21", +] + +[[package]] +name = "evm2-macros" +version = "0.1.0" +source = "git+https://www.github.com/alloy-rs/evm2?rev=01df8f6a396d0250da286cb763faa6ec292d65b5#01df8f6a396d0250da286cb763faa6ec292d65b5" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + [[package]] name = "evmap" version = "11.0.0" @@ -2979,6 +3150,16 @@ dependencies = [ "subtle", ] +[[package]] +name = "ff" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1f686ab92a9fb0eaf188f6c6c87b89490baa6fdb0db4544ba4dc47f7942489f" +dependencies = [ + "rand_core 0.10.1", + "subtle", +] + [[package]] name = "fiat-crypto" version = "0.2.9" @@ -3300,7 +3481,7 @@ version = "0.21.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ddddbf932745a6be37109b6112d3ee09696106f848449069d3a57bba937ab82e" dependencies = [ - "bitflags 2.11.1", + "bitflags 2.13.2", "libc", "libgit2-sys", "log", @@ -3364,11 +3545,22 @@ version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" dependencies = [ - "ff", + "ff 0.13.1", "rand_core 0.6.4", "subtle", ] +[[package]] +name = "group" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fd1a1c7a5206c5b7a3f5a0d7ccd3ff85d0c8f5133d62a02680255b0004af5f4" +dependencies = [ + "ff 0.14.0", + "rand_core 0.10.1", + "subtle", +] + [[package]] name = "h2" version = "0.4.18" @@ -3460,16 +3652,6 @@ dependencies = [ "hashbrown 0.16.1", ] -[[package]] -name = "hdrhistogram" -version = "7.5.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "765c9198f173dd59ce26ff9f95ef0aafd0a0fe01fb9d72841bc5066a4c06511d" -dependencies = [ - "byteorder", - "num-traits", -] - [[package]] name = "heck" version = "0.5.0" @@ -3514,7 +3696,7 @@ dependencies = [ "ipnet", "jni 0.22.4", "rand 0.10.2", - "thiserror 2.0.18", + "thiserror 2.0.21", "tinyvec", "tokio", "tracing", @@ -3536,7 +3718,7 @@ dependencies = [ "rand 0.10.2", "ring", "serde", - "thiserror 2.0.18", + "thiserror 2.0.21", "tinyvec", "tracing", "url", @@ -3564,7 +3746,7 @@ dependencies = [ "serde", "smallvec", "system-configuration", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "tracing", ] @@ -3575,7 +3757,7 @@ version = "0.12.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7" dependencies = [ - "hmac", + "hmac 0.12.1", ] [[package]] @@ -3587,6 +3769,15 @@ dependencies = [ "digest 0.10.7", ] +[[package]] +name = "hmac" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" +dependencies = [ + "digest 0.11.3", +] + [[package]] name = "http" version = "1.4.0" @@ -3620,12 +3811,6 @@ dependencies = [ "pin-project-lite", ] -[[package]] -name = "http-range-header" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9171a2ea8a68358193d15dd5d70c1c10a2afc3e7e4c5bc92bc9f025cebd7359c" - [[package]] name = "httparse" version = "1.10.1" @@ -3666,7 +3851,9 @@ version = "0.4.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "818356c5132c1fede50f837ca96afbe78ff42413047f4abb886217845e1b6c8c" dependencies = [ + "subtle", "typenum", + "zeroize", ] [[package]] @@ -3707,19 +3894,6 @@ dependencies = [ "tower-service", ] -[[package]] -name = "hyper-timeout" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b90d566bffbce6a75bd8b09a05aa8c2cb1fabb6cb348f8840c9e4c90a0d83b0" -dependencies = [ - "hyper", - "hyper-util", - "pin-project-lite", - "tokio", - "tower-service", -] - [[package]] name = "hyper-util" version = "0.1.20" @@ -3998,7 +4172,7 @@ version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bd5b3eaf1a28b758ac0faa5a4254e8ab2705605496f1b1f3fbbc3988ad73d199" dependencies = [ - "bitflags 2.11.1", + "bitflags 2.13.2", "inotify-sys", "libc", ] @@ -4208,7 +4382,7 @@ dependencies = [ "jni-sys 0.4.1", "log", "simd_cesu8", - "thiserror 2.0.18", + "thiserror 2.0.21", "walkdir", "windows-link 0.2.1", ] @@ -4311,7 +4485,7 @@ dependencies = [ "rustls-pki-types", "rustls-platform-verifier 0.5.3", "soketto", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "tokio-rustls", "tokio-util", @@ -4339,7 +4513,7 @@ dependencies = [ "rustc-hash", "serde", "serde_json", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "tokio-stream", "tower", @@ -4364,7 +4538,7 @@ dependencies = [ "rustls-platform-verifier 0.5.3", "serde", "serde_json", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "tower", "url", @@ -4402,7 +4576,7 @@ dependencies = [ "serde", "serde_json", "soketto", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "tokio-stream", "tokio-util", @@ -4419,7 +4593,7 @@ dependencies = [ "http", "serde", "serde_json", - "thiserror 2.0.18", + "thiserror 2.0.21", ] [[package]] @@ -4461,7 +4635,7 @@ dependencies = [ "pem", "serde", "serde_json", - "signature", + "signature 2.2.0", "simple_asn1", ] @@ -4472,12 +4646,27 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f6e3919bbaa2945715f0bb6d3934a173d1e9a59ac23767fbaaef277265a7411b" dependencies = [ "cfg-if", - "ecdsa", - "elliptic-curve", + "ecdsa 0.16.9", + "elliptic-curve 0.13.8", "once_cell", - "serdect", + "serdect 0.2.0", "sha2 0.10.9", - "signature", + "signature 2.2.0", +] + +[[package]] +name = "k256" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93f50113171a713f4a4231ef82eb26703607139b35dcb56241f0ceab2ae1f7d8" +dependencies = [ + "cpubits", + "ecdsa 0.17.0", + "elliptic-curve 0.14.3", + "primeorder", + "serdect 0.4.3", + "sha2 0.11.0", + "wnaf", ] [[package]] @@ -4488,7 +4677,7 @@ checksum = "bde5057d6143cc94e861d90f591b9303d6716c6b9602309150bd068853c10899" dependencies = [ "hashbrown 0.16.1", "portable-atomic", - "thiserror 2.0.18", + "thiserror 2.0.21", ] [[package]] @@ -4551,7 +4740,7 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a7b65860415f949f23fa882e669f2dbd4a0f0eeb1acdd56790b30494afd7da2f" dependencies = [ - "bitflags 2.11.1", + "bitflags 2.13.2", "libc", ] @@ -4622,11 +4811,11 @@ dependencies = [ "bs58", "ed25519-dalek", "hkdf", - "k256", + "k256 0.13.4", "multihash", "quick-protobuf", "sha2 0.10.9", - "thiserror 2.0.18", + "thiserror 2.0.21", "tracing", "zeroize", ] @@ -4648,7 +4837,7 @@ version = "0.1.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e02f3bb43d335493c96bf3fd3a321600bf6bd07ed34bc64118e9293bdffea46c" dependencies = [ - "bitflags 2.11.1", + "bitflags 2.13.2", "libc", "plain", "redox_syscall 0.7.5", @@ -4687,7 +4876,7 @@ version = "0.3.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f50e8f47623268b5407192d26876c4d7f89d686ca130fdc53bced4814cd29f8" dependencies = [ - "bitflags 2.11.1", + "bitflags 2.13.2", ] [[package]] @@ -4908,8 +5097,8 @@ dependencies = [ "indexmap 2.14.0", "metrics", "metrics-util", - "quanta", - "thiserror 2.0.18", + "quanta 0.12.6", + "thiserror 2.0.21", ] [[package]] @@ -4938,7 +5127,7 @@ dependencies = [ "crossbeam-utils", "hashbrown 0.16.1", "metrics", - "quanta", + "quanta 0.12.6", "rand 0.9.4", "rand_xoshiro", "rapidhash", @@ -4951,16 +5140,6 @@ version = "0.3.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" -[[package]] -name = "mime_guess" -version = "2.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e" -dependencies = [ - "mime", - "unicase", -] - [[package]] name = "minimal-lexical" version = "0.2.1" @@ -5066,12 +5245,12 @@ dependencies = [ "alloy-chains", "alloy-consensus", "alloy-eips", - "alloy-evm", "alloy-genesis", "alloy-hardforks", "alloy-primitives", "alloy-serde", "auto_impl", + "evm2", "eyre", "morph-primitives", "reth-chainspec", @@ -5088,7 +5267,6 @@ version = "1.4.1" dependencies = [ "alloy-consensus", "alloy-eips", - "alloy-evm", "alloy-genesis", "alloy-primitives", "alloy-rlp", @@ -5096,9 +5274,10 @@ dependencies = [ "morph-primitives", "reth-consensus", "reth-consensus-common", + "reth-execution-types", "reth-primitives-traits", "serde_json", - "thiserror 2.0.18", + "thiserror 2.0.21", ] [[package]] @@ -5125,7 +5304,7 @@ dependencies = [ "reth-provider", "reth-rpc-api", "serde_json", - "thiserror 2.0.18", + "thiserror 2.0.21", "tracing", ] @@ -5134,11 +5313,13 @@ name = "morph-evm" version = "1.4.1" dependencies = [ "alloy-consensus", - "alloy-evm", + "alloy-eip7928", + "alloy-eips", "alloy-genesis", "alloy-primitives", "alloy-rpc-types-eth", "derive_more", + "evm2", "morph-chainspec", "morph-payload-types", "morph-primitives", @@ -5147,12 +5328,12 @@ dependencies = [ "reth-chainspec", "reth-ethereum-primitives", "reth-evm", + "reth-evm-ethereum", + "reth-execution-types", "reth-primitives-traits", - "reth-revm", "reth-rpc-eth-api", - "revm", "serde_json", - "thiserror 2.0.18", + "thiserror 2.0.21", "tracing", ] @@ -5233,6 +5414,7 @@ dependencies = [ "alloy-eips", "alloy-primitives", "alloy-rlp", + "evm2", "metrics", "morph-chainspec", "morph-evm", @@ -5248,12 +5430,11 @@ dependencies = [ "reth-payload-primitives", "reth-payload-util", "reth-primitives-traits", - "reth-revm", "reth-storage-api", + "reth-tasks", "reth-transaction-pool", "reth-trie-parallel", - "revm", - "thiserror 2.0.18", + "thiserror 2.0.21", "tracing", ] @@ -5318,14 +5499,13 @@ dependencies = [ "reth-metrics", "reth-primitives-traits", "reth-provider", - "reth-revm", "reth-storage-errors", "reth-tasks", "reth-trie", "reth-trie-common", "serde", "tempfile", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "tracing", ] @@ -5376,7 +5556,7 @@ dependencies = [ "reth-tasks", "serde", "tempfile", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "tracing", ] @@ -5414,11 +5594,11 @@ version = "1.4.1" dependencies = [ "alloy-consensus", "alloy-eips", - "alloy-evm", "alloy-primitives", "alloy-sol-types", "auto_impl", "derive_more", + "evm2", "eyre", "morph-chainspec", "morph-primitives", @@ -5426,8 +5606,7 @@ dependencies = [ "reth-evm", "reth-rpc-eth-types", "reth-storage-api", - "revm", - "thiserror 2.0.18", + "thiserror 2.0.21", "tracing", ] @@ -5437,7 +5616,6 @@ version = "1.4.1" dependencies = [ "alloy-consensus", "alloy-eips", - "alloy-evm", "alloy-network", "alloy-primitives", "alloy-rpc-types-debug", @@ -5445,6 +5623,7 @@ dependencies = [ "alloy-serde", "async-trait", "derive_more", + "evm2", "eyre", "jsonrpsee", "metrics", @@ -5462,7 +5641,6 @@ dependencies = [ "reth-node-builder", "reth-primitives-traits", "reth-provider", - "reth-revm", "reth-rpc", "reth-rpc-api", "reth-rpc-convert", @@ -5473,11 +5651,10 @@ dependencies = [ "reth-tasks", "reth-transaction-pool", "reth-trie-common", - "revm", "serde", "serde_json", "tempfile", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "tracing", ] @@ -5486,21 +5663,19 @@ dependencies = [ name = "morph-statetest" version = "1.4.1" dependencies = [ - "alloy-evm", "alloy-primitives", "alloy-rlp", "alloy-trie", "clap", + "evm2", "eyre", "morph-chainspec", "morph-evm", "morph-primitives", "morph-revm", - "revm", - "revm-statetest-types", "serde", "serde_json", - "thiserror 2.0.18", + "thiserror 2.0.21", ] [[package]] @@ -5509,10 +5684,10 @@ version = "1.4.1" dependencies = [ "alloy-consensus", "alloy-eips", - "alloy-evm", "alloy-primitives", "c-kzg", "derive_more", + "evm2", "futures", "morph-chainspec", "morph-evm", @@ -5524,7 +5699,6 @@ dependencies = [ "reth-evm-ethereum", "reth-primitives-traits", "reth-provider", - "reth-revm", "reth-storage-api", "reth-transaction-pool", "tracing", @@ -5586,22 +5760,13 @@ dependencies = [ "minimal-lexical", ] -[[package]] -name = "nonmax" -version = "0.5.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "610a5acd306ec67f907abe5567859a3c693fb9886eb1f012ab8f2a47bef3db51" -dependencies = [ - "serde", -] - [[package]] name = "notify" version = "8.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4d3d07927151ff8575b7087f245456e549fea62edf0ec4e565a5ee50c8402bc3" dependencies = [ - "bitflags 2.11.1", + "bitflags 2.13.2", "fsevent-sys", "inotify", "kqueue", @@ -5619,7 +5784,7 @@ version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "42b8cfee0e339a0337359f3c88165702ac6e600dc01c0cc9579a92d62b08477a" dependencies = [ - "bitflags 2.11.1", + "bitflags 2.13.2", ] [[package]] @@ -5646,7 +5811,7 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23" dependencies = [ - "num-bigint", + "num-bigint 0.4.6", "num-complex", "num-integer", "num-iter", @@ -5664,6 +5829,17 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-bigint" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93e7820bc0a80a0238e650327316f929ba18d5be054b647490a3a6a339f3e7c0" +dependencies = [ + "num-integer", + "num-traits", + "serde", +] + [[package]] name = "num-complex" version = "0.4.6" @@ -5705,7 +5881,7 @@ version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824" dependencies = [ - "num-bigint", + "num-bigint 0.4.6", "num-integer", "num-traits", ] @@ -5781,7 +5957,7 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" dependencies = [ - "bitflags 2.11.1", + "bitflags 2.13.2", ] [[package]] @@ -5822,97 +5998,18 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" -[[package]] -name = "opentelemetry" -version = "0.32.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0142c63252a9e054e68a4c61a5778f7b14f576274d593f8ce883d191a099682" -dependencies = [ - "futures-core", - "futures-sink", - "js-sys", - "pin-project-lite", - "thiserror 2.0.18", - "tracing", -] - -[[package]] -name = "opentelemetry-http" -version = "0.32.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5683015d09e2df236ef005b17f6f196f0d5f6313c4fa43a7b6a53b52776e4331" -dependencies = [ - "async-trait", - "bytes", - "http", - "opentelemetry", - "reqwest", -] - -[[package]] -name = "opentelemetry-otlp" -version = "0.32.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9966929966d17620d7c316c643ba62631826e10021409357772d5eea84f62c35" -dependencies = [ - "http", - "opentelemetry", - "opentelemetry-http", - "opentelemetry-proto", - "opentelemetry_sdk", - "prost", - "reqwest", - "thiserror 2.0.18", - "tokio", - "tonic", - "tonic-types", -] - -[[package]] -name = "opentelemetry-proto" -version = "0.32.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56d658ba1faf63f7b9c492cfbe6e0ec365440a16132d3270c1065f7b33f1b638" -dependencies = [ - "opentelemetry", - "opentelemetry_sdk", - "prost", - "tonic", - "tonic-prost", -] - -[[package]] -name = "opentelemetry-semantic-conventions" -version = "0.32.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c913ac17a6c451661ee255f4625d143e51647ae78ebd969b75e41c4442f4fe47" - -[[package]] -name = "opentelemetry_sdk" -version = "0.32.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b59f80e1ac4d5ff7a2db8fb6c80badb7f0f3f858211fba08dd9aaec750894f9" -dependencies = [ - "futures-channel", - "futures-executor", - "futures-util", - "opentelemetry", - "percent-encoding", - "portable-atomic", - "rand 0.9.4", - "thiserror 2.0.18", -] - [[package]] name = "p256" -version = "0.13.2" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b" +checksum = "d2c9239b2dbc807adbbe147e8cf72ea7450c3a0aabe62cb8e75ff4ec22e1f72a" dependencies = [ - "ecdsa", - "elliptic-curve", + "ecdsa 0.17.0", + "elliptic-curve 0.14.3", + "primefield", "primeorder", - "sha2 0.10.9", + "serdect 0.4.3", + "sha2 0.11.0", ] [[package]] @@ -5983,6 +6080,12 @@ version = "1.0.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" +[[package]] +name = "pastey" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4" + [[package]] name = "pbkdf2" version = "0.12.2" @@ -5990,7 +6093,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8ed6a7761f76e3b9f92dfb0a60a6a6477c61024b775147ff0973a02653abaf2" dependencies = [ "digest 0.10.7", - "hmac", + "hmac 0.12.1", ] [[package]] @@ -6110,8 +6213,18 @@ version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" dependencies = [ - "der", - "spki", + "der 0.7.10", + "spki 0.7.3", +] + +[[package]] +name = "pkcs8" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "451913da69c775a56034ea8d9003d27ee8948e12443eae7c038ba100a4f21cb7" +dependencies = [ + "der 0.8.3", + "spki 0.8.1", ] [[package]] @@ -6256,13 +6369,31 @@ dependencies = [ "syn 2.0.117", ] +[[package]] +name = "primefield" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c555a6e4eb7d4e158fcb028c835c3b8642206ddc279b5c6b202ef9a8bdb592f4" +dependencies = [ + "crypto-bigint 0.7.10", + "crypto-common 0.2.2", + "ff 0.14.0", + "rand_core 0.10.1", + "subtle", + "zeroize", +] + [[package]] name = "primeorder" -version = "0.13.6" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "353e1ca18966c16d9deb1c69278edbc5f194139612772bd9537af60ac231e1e6" +checksum = "5c9f42978c78a00e3d68f69fc03e57a234debae69da4020a4fb588fcdcd07b06" dependencies = [ - "elliptic-curve", + "elliptic-curve 0.14.3", + "once_cell", + "primefield", + "serdect 0.4.3", + "wnaf", ] [[package]] @@ -6343,7 +6474,7 @@ version = "0.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "25485360a54d6861439d60facef26de713b1e126bf015ec8f98239467a2b82f7" dependencies = [ - "bitflags 2.11.1", + "bitflags 2.13.2", "chrono", "flate2", "procfs-core", @@ -6356,7 +6487,7 @@ version = "0.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6401bf7b6af22f78b563665d15a22e9aef27775b79b149a66ca022468a4e405" dependencies = [ - "bitflags 2.11.1", + "bitflags 2.13.2", "chrono", "hex", ] @@ -6369,7 +6500,7 @@ checksum = "4b45fcc2344c680f5025fe57779faef368840d0bd1f42f216291f0dc4ace4744" dependencies = [ "bit-set", "bit-vec", - "bitflags 2.11.1", + "bitflags 2.13.2", "num-traits", "rand 0.9.4", "rand_chacha 0.9.0", @@ -6435,15 +6566,6 @@ dependencies = [ "syn 2.0.117", ] -[[package]] -name = "prost-types" -version = "0.14.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8991c4cbdb8bc5b11f0b074ffe286c30e523de90fee5ba8132f1399f23cb3dd7" -dependencies = [ - "prost", -] - [[package]] name = "quanta" version = "0.12.6" @@ -6459,6 +6581,21 @@ dependencies = [ "winapi", ] +[[package]] +name = "quanta" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73be39b77b45d82a4d1a5793fe9a89a5c143ceaa6ad0d8417982566bb0f34e11" +dependencies = [ + "libc", + "portable-atomic", + "raw-cpuid", + "wasip1", + "wasip2", + "web-sys", + "windows-sys 0.61.2", +] + [[package]] name = "quick-error" version = "1.2.3" @@ -6488,7 +6625,7 @@ dependencies = [ "rustc-hash", "rustls", "socket2", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "tracing", "web-time", @@ -6511,7 +6648,7 @@ dependencies = [ "rustls", "rustls-pki-types", "slab", - "thiserror 2.0.18", + "thiserror 2.0.21", "tinyvec", "tracing", "web-time", @@ -6692,7 +6829,7 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5ef8dea09a92caaf73bff7adb70b76162e5937524058a7e5bff37869cbbec293" dependencies = [ - "bitflags 2.11.1", + "bitflags 2.13.2", "compact_str", "hashbrown 0.16.1", "indoc", @@ -6700,7 +6837,7 @@ dependencies = [ "kasuari", "lru 0.16.4", "strum", - "thiserror 2.0.18", + "thiserror 2.0.21", "unicode-segmentation", "unicode-truncate", "unicode-width", @@ -6724,7 +6861,7 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d7dbfa023cd4e604c2553483820c5fe8aa9d71a42eea5aa77c6e7f35756612db" dependencies = [ - "bitflags 2.11.1", + "bitflags 2.13.2", "hashbrown 0.16.1", "indoc", "instability", @@ -6743,7 +6880,7 @@ version = "11.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "498cd0dc59d73224351ee52a95fee0f1a617a2eae0e7d9d720cc622c73a54186" dependencies = [ - "bitflags 2.11.1", + "bitflags 2.13.2", ] [[package]] @@ -6778,7 +6915,7 @@ version = "0.5.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" dependencies = [ - "bitflags 2.11.1", + "bitflags 2.13.2", ] [[package]] @@ -6787,7 +6924,7 @@ version = "0.7.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4666a1a60d8412eab19d94f6d13dcc9cea0a5ef4fdf6a5db306537413c661b1b" dependencies = [ - "bitflags 2.11.1", + "bitflags 2.13.2", ] [[package]] @@ -6900,8 +7037,8 @@ checksum = "1e061d1b48cb8d38042de4ae0a7a6401009d6143dc80d2e2d6f31f0bdd6470c7" [[package]] name = "reth-basic-payload-builder" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-consensus", "alloy-eips", @@ -6910,13 +7047,13 @@ dependencies = [ "futures-util", "metrics", "reth-chain-state", + "reth-evm", "reth-execution-cache", "reth-metrics", "reth-payload-builder", "reth-payload-builder-primitives", "reth-payload-primitives", "reth-primitives-traits", - "reth-revm", "reth-storage-api", "reth-tasks", "reth-trie-parallel", @@ -6927,8 +7064,8 @@ dependencies = [ [[package]] name = "reth-chain-state" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-consensus", "alloy-eips", @@ -6936,20 +7073,18 @@ dependencies = [ "alloy-signer", "alloy-signer-local", "derive_more", + "evm2", "metrics", "parking_lot", "pin-project", "rand 0.9.4", "reth-chainspec", - "reth-errors", "reth-ethereum-primitives", "reth-execution-types", "reth-metrics", "reth-primitives-traits", - "reth-storage-api", "reth-trie", "reth-trie-sparse", - "revm", "serde", "tokio", "tokio-stream", @@ -6958,13 +7093,12 @@ dependencies = [ [[package]] name = "reth-chainspec" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-chains", "alloy-consensus", "alloy-eips", - "alloy-evm", "alloy-genesis", "alloy-primitives", "alloy-trie", @@ -6978,8 +7112,8 @@ dependencies = [ [[package]] name = "reth-cli" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-genesis", "clap", @@ -6991,11 +7125,12 @@ dependencies = [ [[package]] name = "reth-cli-commands" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-chains", "alloy-consensus", + "alloy-eip7928", "alloy-eips", "alloy-primitives", "alloy-rlp", @@ -7051,7 +7186,6 @@ dependencies = [ "reth-provider", "reth-prune", "reth-prune-types", - "reth-revm", "reth-stages", "reth-stages-types", "reth-static-file", @@ -7070,13 +7204,13 @@ dependencies = [ "toml", "tracing", "url", - "zstd", + "zstd 0.14.3", ] [[package]] name = "reth-cli-runner" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "reth-tasks", "tokio", @@ -7085,28 +7219,26 @@ dependencies = [ [[package]] name = "reth-cli-util" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-eips", "alloy-primitives", - "cfg-if", "eyre", "libc", "rand 0.8.6", "reth-fs-util", "secp256k1 0.30.0", "serde", - "thiserror 2.0.18", + "thiserror 2.0.21", "tikv-jemalloc-sys", "tikv-jemallocator", ] [[package]] name = "reth-codecs" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f0dd7f542fbcae0e490ebe13f3eababcc05547375246ff7f62700b533cf3f01" +version = "0.8.2" +source = "git+https://github.com/paradigmxyz/reth-core?rev=275ce4cf5befeb9f1e8acd935ff2882d2d25fc61#275ce4cf5befeb9f1e8acd935ff2882d2d25fc61" dependencies = [ "alloy-consensus", "alloy-eips", @@ -7125,9 +7257,8 @@ dependencies = [ [[package]] name = "reth-codecs-derive" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7e508fcbb8cb775639dbbb56b81b62756d4322f28e76c60a52aa32575f993fe" +version = "0.8.2" +source = "git+https://github.com/paradigmxyz/reth-core?rev=275ce4cf5befeb9f1e8acd935ff2882d2d25fc61#275ce4cf5befeb9f1e8acd935ff2882d2d25fc61" dependencies = [ "proc-macro2", "quote", @@ -7136,8 +7267,8 @@ dependencies = [ [[package]] name = "reth-config" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "eyre", "humantime-serde", @@ -7153,8 +7284,8 @@ dependencies = [ [[package]] name = "reth-consensus" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-consensus", "alloy-eip7928", @@ -7162,13 +7293,13 @@ dependencies = [ "auto_impl", "reth-execution-types", "reth-primitives-traits", - "thiserror 2.0.18", + "thiserror 2.0.21", ] [[package]] name = "reth-consensus-common" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-consensus", "alloy-eips", @@ -7180,8 +7311,8 @@ dependencies = [ [[package]] name = "reth-consensus-debug-client" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-consensus", "alloy-eips", @@ -7196,17 +7327,17 @@ dependencies = [ "futures", "reqwest", "reth-node-api", - "reth-tracing", "ringbuffer", "serde", "serde_json", "tokio", + "tracing", ] [[package]] name = "reth-db" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-primitives", "derive_more", @@ -7215,29 +7346,29 @@ dependencies = [ "metrics", "page_size", "parking_lot", - "quanta", "reth-db-api", "reth-fs-util", "reth-libmdbx", "reth-metrics", "reth-nippy-jar", + "reth-primitives-traits", "reth-static-file-types", "reth-storage-errors", - "reth-tracing", "rustc-hash", "strum", "sysinfo", "tempfile", - "thiserror 2.0.18", + "thiserror 2.0.21", "tracing", ] [[package]] name = "reth-db-api" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-consensus", + "alloy-eips", "alloy-primitives", "arbitrary", "arrayvec", @@ -7260,8 +7391,8 @@ dependencies = [ [[package]] name = "reth-db-common" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-consensus", "alloy-genesis", @@ -7284,14 +7415,14 @@ dependencies = [ "reth-trie-db", "serde", "serde_json", - "thiserror 2.0.18", + "thiserror 2.0.21", "tracing", ] [[package]] name = "reth-db-models" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-eips", "alloy-primitives", @@ -7305,8 +7436,8 @@ dependencies = [ [[package]] name = "reth-discv4" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-primitives", "alloy-rlp", @@ -7322,7 +7453,7 @@ dependencies = [ "schnellru", "secp256k1 0.30.0", "serde", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "tokio-stream", "tracing", @@ -7330,8 +7461,8 @@ dependencies = [ [[package]] name = "reth-discv5" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-primitives", "alloy-rlp", @@ -7347,15 +7478,15 @@ dependencies = [ "reth-metrics", "reth-network-peers", "secp256k1 0.30.0", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "tracing", ] [[package]] name = "reth-dns-discovery" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-primitives", "dashmap", @@ -7370,7 +7501,7 @@ dependencies = [ "secp256k1 0.30.0", "serde", "serde_with", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "tokio-stream", "tracing", @@ -7378,8 +7509,8 @@ dependencies = [ [[package]] name = "reth-downloaders" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-consensus", "alloy-eips", @@ -7394,17 +7525,18 @@ dependencies = [ "rayon", "reth-config", "reth-consensus", + "reth-eth-wire-types", "reth-ethereum-primitives", "reth-metrics", "reth-network-p2p", "reth-network-peers", "reth-primitives-traits", - "reth-provider", "reth-storage-api", "reth-tasks", "reth-testing-utils", + "reth-trie-common", "tempfile", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "tokio-stream", "tokio-util", @@ -7413,11 +7545,12 @@ dependencies = [ [[package]] name = "reth-e2e-test-utils" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-consensus", "alloy-eips", + "alloy-genesis", "alloy-network", "alloy-primitives", "alloy-provider", @@ -7430,15 +7563,17 @@ dependencies = [ "eyre", "futures-util", "jsonrpsee", + "parking_lot", "reth-chainspec", "reth-cli-commands", "reth-config", "reth-consensus", "reth-db", "reth-db-common", - "reth-engine-local", "reth-engine-primitives", + "reth-eth-wire-types", "reth-ethereum-primitives", + "reth-fs-util", "reth-network-api", "reth-network-p2p", "reth-network-peers", @@ -7451,6 +7586,7 @@ dependencies = [ "reth-payload-primitives", "reth-primitives-traits", "reth-provider", + "reth-prune-types", "reth-rpc-api", "reth-rpc-builder", "reth-rpc-eth-api", @@ -7459,7 +7595,9 @@ dependencies = [ "reth-tasks", "reth-tokio-util", "reth-tracing", - "revm", + "reth-transaction-pool", + "reth-trie", + "reth-trie-db", "serde_json", "tempfile", "tokio", @@ -7470,8 +7608,8 @@ dependencies = [ [[package]] name = "reth-ecies" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "aes", "alloy-primitives", @@ -7482,13 +7620,13 @@ dependencies = [ "ctr", "digest 0.10.7", "futures", - "hmac", + "hmac 0.12.1", "pin-project", "rand 0.8.6", "reth-network-peers", "secp256k1 0.30.0", "sha2 0.10.9", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "tokio-stream", "tokio-util", @@ -7497,8 +7635,8 @@ dependencies = [ [[package]] name = "reth-engine-local" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-consensus", "alloy-primitives", @@ -7520,8 +7658,8 @@ dependencies = [ [[package]] name = "reth-engine-primitives" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-consensus", "alloy-eips", @@ -7541,28 +7679,30 @@ dependencies = [ "reth-storage-api", "reth-trie-common", "serde", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", + "tracing", ] [[package]] name = "reth-engine-tree" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-consensus", "alloy-eip7928", "alloy-eips", - "alloy-evm", "alloy-primitives", "alloy-rlp", "alloy-rpc-types-engine", "crossbeam-channel", + "dashmap", + "derive-where", "derive_more", + "evm2", "futures", "indexmap 2.14.0", "metrics", - "moka", "parking_lot", "rayon", "reth-chain-state", @@ -7583,7 +7723,6 @@ dependencies = [ "reth-provider", "reth-prune", "reth-prune-types", - "reth-revm", "reth-stages", "reth-stages-api", "reth-static-file", @@ -7594,21 +7733,19 @@ dependencies = [ "reth-trie-common", "reth-trie-parallel", "reth-trie-sparse", - "revm", "schnellru", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "tracing", ] [[package]] name = "reth-engine-util" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-consensus", "alloy-primitives", - "alloy-rlp", "alloy-rpc-types-engine", "eyre", "futures", @@ -7622,7 +7759,6 @@ dependencies = [ "reth-fs-util", "reth-payload-primitives", "reth-primitives-traits", - "reth-revm", "reth-storage-api", "serde", "serde_json", @@ -7633,8 +7769,8 @@ dependencies = [ [[package]] name = "reth-era" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-consensus", "alloy-eips", @@ -7646,13 +7782,13 @@ dependencies = [ "ethereum_ssz_derive", "sha2 0.10.9", "snap", - "thiserror 2.0.18", + "thiserror 2.0.21", ] [[package]] name = "reth-era-downloader" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-primitives", "bytes", @@ -7667,8 +7803,8 @@ dependencies = [ [[package]] name = "reth-era-utils" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-consensus", "alloy-primitives", @@ -7691,19 +7827,19 @@ dependencies = [ [[package]] name = "reth-errors" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "reth-consensus", "reth-execution-errors", "reth-storage-errors", - "thiserror 2.0.18", + "thiserror 2.0.21", ] [[package]] name = "reth-eth-wire" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-chains", "alloy-primitives", @@ -7721,7 +7857,7 @@ dependencies = [ "reth-primitives-traits", "serde", "snap", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "tokio-stream", "tokio-util", @@ -7730,8 +7866,8 @@ dependencies = [ [[package]] name = "reth-eth-wire-types" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-chains", "alloy-consensus", @@ -7748,13 +7884,13 @@ dependencies = [ "reth-ethereum-primitives", "reth-primitives-traits", "serde", - "thiserror 2.0.18", + "thiserror 2.0.21", ] [[package]] name = "reth-ethereum-cli" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "clap", "eyre", @@ -7776,8 +7912,8 @@ dependencies = [ [[package]] name = "reth-ethereum-consensus" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-consensus", "alloy-eips", @@ -7792,8 +7928,8 @@ dependencies = [ [[package]] name = "reth-ethereum-engine-primitives" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-eips", "alloy-primitives", @@ -7803,13 +7939,13 @@ dependencies = [ "reth-payload-primitives", "reth-primitives-traits", "serde", - "thiserror 2.0.18", + "thiserror 2.0.21", ] [[package]] name = "reth-ethereum-forks" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-eip2124", "alloy-hardforks", @@ -7821,8 +7957,8 @@ dependencies = [ [[package]] name = "reth-ethereum-payload-builder" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-consensus", "alloy-eips", @@ -7842,21 +7978,19 @@ dependencies = [ "reth-payload-primitives", "reth-payload-validator", "reth-primitives-traits", - "reth-revm", "reth-storage-api", "reth-transaction-pool", - "revm", + "reth-trie-common", "tracing", ] [[package]] name = "reth-ethereum-primitives" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-consensus", "alloy-eips", - "alloy-primitives", "alloy-rpc-types-eth", "reth-codecs", "reth-primitives-traits", @@ -7865,8 +7999,8 @@ dependencies = [ [[package]] name = "reth-etl" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "rayon", "reth-db-api", @@ -7875,19 +8009,21 @@ dependencies = [ [[package]] name = "reth-evm" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-consensus", "alloy-eip7928", "alloy-eips", - "alloy-evm", "alloy-primitives", + "alloy-rlp", + "alloy-rpc-types-debug", "auto_impl", - "derive_more", + "evm2", "fixed-cache", "futures-util", "metrics", + "moka", "rayon", "reth-execution-errors", "reth-execution-types", @@ -7896,19 +8032,21 @@ dependencies = [ "reth-storage-api", "reth-storage-errors", "reth-trie-common", - "revm", + "tracing", ] [[package]] name = "reth-evm-ethereum" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-consensus", + "alloy-eip7928", "alloy-eips", - "alloy-evm", "alloy-primitives", "alloy-rpc-types-engine", + "alloy-sol-types", + "evm2", "reth-chainspec", "reth-ethereum-forks", "reth-ethereum-primitives", @@ -7916,63 +8054,61 @@ dependencies = [ "reth-execution-types", "reth-primitives-traits", "reth-storage-errors", - "revm", ] [[package]] name = "reth-execution-cache" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-primitives", "fixed-cache", "metrics", "parking_lot", "reth-errors", + "reth-evm", "reth-metrics", "reth-primitives-traits", - "reth-provider", - "reth-revm", - "reth-trie", + "reth-storage-api", + "reth-trie-common", "tracing", ] [[package]] name = "reth-execution-errors" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ - "alloy-evm", "alloy-primitives", "alloy-rlp", "nybbles", "reth-storage-errors", - "thiserror 2.0.18", + "thiserror 2.0.21", ] [[package]] name = "reth-execution-types" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-consensus", + "alloy-eip7928", "alloy-eips", - "alloy-evm", "alloy-primitives", "alloy-rlp", "derive_more", + "evm2", "reth-ethereum-primitives", "reth-primitives-traits", "reth-trie-common", - "revm", "serde", "serde_with", ] [[package]] name = "reth-exex" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-consensus", "alloy-eips", @@ -7996,12 +8132,10 @@ dependencies = [ "reth-primitives-traits", "reth-provider", "reth-prune-types", - "reth-revm", "reth-stages-api", "reth-tasks", - "reth-tracing", "rmp-serde", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "tokio-util", "tracing", @@ -8009,8 +8143,8 @@ dependencies = [ [[package]] name = "reth-exex-test-utils" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-eips", "eyre", @@ -8035,14 +8169,14 @@ dependencies = [ "reth-tasks", "reth-transaction-pool", "tempfile", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", ] [[package]] name = "reth-exex-types" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-eips", "alloy-primitives", @@ -8055,44 +8189,44 @@ dependencies = [ [[package]] name = "reth-fs-util" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "serde", "serde_json", - "thiserror 2.0.18", + "thiserror 2.0.21", ] [[package]] name = "reth-invalid-block-hooks" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-consensus", "alloy-primitives", "alloy-rlp", "alloy-rpc-types-debug", + "evm2", "eyre", "futures", "jsonrpsee", "pretty_assertions", "reth-engine-primitives", "reth-evm", + "reth-execution-types", "reth-primitives-traits", "reth-provider", - "reth-revm", "reth-rpc-api", - "reth-tracing", "reth-trie", - "revm", "serde", "serde_json", + "tracing", ] [[package]] name = "reth-ipc" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "bytes", "futures", @@ -8101,7 +8235,7 @@ dependencies = [ "jsonrpsee", "pin-project", "serde_json", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "tokio-stream", "tokio-util", @@ -8111,10 +8245,10 @@ dependencies = [ [[package]] name = "reth-libmdbx" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ - "bitflags 2.11.1", + "bitflags 2.13.2", "byteorder", "crossbeam-queue", "dashmap", @@ -8122,14 +8256,14 @@ dependencies = [ "parking_lot", "reth-mdbx-sys", "smallvec", - "thiserror 2.0.18", + "thiserror 2.0.21", "tracing", ] [[package]] name = "reth-mdbx-sys" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "bindgen", "cc", @@ -8137,8 +8271,8 @@ dependencies = [ [[package]] name = "reth-metrics" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "futures", "libc", @@ -8151,8 +8285,8 @@ dependencies = [ [[package]] name = "reth-net-banlist" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-primitives", "ipnet", @@ -8160,22 +8294,22 @@ dependencies = [ [[package]] name = "reth-net-nat" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "futures-util", "if-addrs", "reqwest", "serde_with", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "tracing", ] [[package]] name = "reth-network" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-consensus", "alloy-eips", @@ -8209,6 +8343,7 @@ dependencies = [ "reth-fs-util", "reth-metrics", "reth-net-banlist", + "reth-net-nat", "reth-network-api", "reth-network-p2p", "reth-network-peers", @@ -8224,7 +8359,7 @@ dependencies = [ "serde", "smallvec", "socket2", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "tokio-stream", "tokio-util", @@ -8233,8 +8368,8 @@ dependencies = [ [[package]] name = "reth-network-api" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-consensus", "alloy-primitives", @@ -8251,15 +8386,15 @@ dependencies = [ "reth-network-types", "reth-tokio-util", "serde", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "tokio-stream", ] [[package]] name = "reth-network-p2p" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-consensus", "alloy-eip7928", @@ -8282,23 +8417,23 @@ dependencies = [ [[package]] name = "reth-network-peers" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-primitives", "alloy-rlp", "enr", "secp256k1 0.30.0", "serde_with", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "url", ] [[package]] name = "reth-network-types" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-eip2124", "humantime-serde", @@ -8311,8 +8446,8 @@ dependencies = [ [[package]] name = "reth-nippy-jar" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "anyhow", "bincode 1.3.3", @@ -8321,15 +8456,16 @@ dependencies = [ "memmap2", "reth-fs-util", "serde", - "thiserror 2.0.18", + "smallvec", + "thiserror 2.0.21", "tracing", - "zstd", + "zstd 0.14.3", ] [[package]] name = "reth-node-api" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-rpc-types-engine", "eyre", @@ -8352,13 +8488,13 @@ dependencies = [ [[package]] name = "reth-node-builder" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-consensus", "alloy-eips", + "alloy-network", "alloy-primitives", - "alloy-provider", "alloy-rpc-types", "alloy-rpc-types-engine", "aquamarine", @@ -8401,7 +8537,9 @@ dependencies = [ "reth-rpc", "reth-rpc-api", "reth-rpc-builder", + "reth-rpc-convert", "reth-rpc-engine-api", + "reth-rpc-eth-api", "reth-rpc-eth-types", "reth-rpc-layer", "reth-stages", @@ -8420,8 +8558,8 @@ dependencies = [ [[package]] name = "reth-node-core" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-consensus", "alloy-eips", @@ -8464,34 +8602,38 @@ dependencies = [ "reth-transaction-pool", "secp256k1 0.30.0", "serde", + "smolgen", "strum", - "thiserror 2.0.18", + "thiserror 2.0.21", "toml", "tracing", "url", - "vergen", - "vergen-git2", ] [[package]] name = "reth-node-ethereum" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-consensus", "alloy-eips", "alloy-network", "alloy-primitives", + "alloy-rlp", "alloy-rpc-types-engine", "alloy-rpc-types-eth", "ethereum_ssz", "ethereum_ssz_derive", + "evm2", "eyre", + "futures", "http-body-util", "jsonrpsee", "reth-chainspec", "reth-engine-local", "reth-engine-primitives", + "reth-engine-tree", + "reth-errors", "reth-ethereum-consensus", "reth-ethereum-engine-primitives", "reth-ethereum-payload-builder", @@ -8499,13 +8641,13 @@ dependencies = [ "reth-evm", "reth-evm-ethereum", "reth-network", + "reth-network-p2p", "reth-node-api", "reth-node-builder", "reth-node-core", "reth-payload-primitives", "reth-primitives-traits", "reth-provider", - "reth-revm", "reth-rpc", "reth-rpc-api", "reth-rpc-builder", @@ -8513,19 +8655,23 @@ dependencies = [ "reth-rpc-eth-api", "reth-rpc-eth-types", "reth-rpc-server-types", - "reth-tracing", + "reth-snap-sync", + "reth-stages", + "reth-tasks", "reth-transaction-pool", - "revm", + "reth-trie-common", "serde", "serde_json", "tokio", + "tokio-util", "tower", + "tracing", ] [[package]] name = "reth-node-ethstats" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-consensus", "alloy-primitives", @@ -8538,7 +8684,7 @@ dependencies = [ "reth-transaction-pool", "serde", "serde_json", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "tokio-stream", "tokio-tungstenite", @@ -8548,8 +8694,8 @@ dependencies = [ [[package]] name = "reth-node-events" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-consensus", "alloy-eips", @@ -8572,8 +8718,8 @@ dependencies = [ [[package]] name = "reth-node-metrics" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "bytes", "eyre", @@ -8586,6 +8732,7 @@ dependencies = [ "metrics-exporter-prometheus", "metrics-process", "metrics-util", + "parking_lot", "pprof_util", "procfs", "reqwest", @@ -8596,13 +8743,14 @@ dependencies = [ "tikv-jemalloc-ctl", "tokio", "tower", + "tower-http", "tracing", ] [[package]] name = "reth-node-types" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "reth-chainspec", "reth-db-api", @@ -8613,8 +8761,8 @@ dependencies = [ [[package]] name = "reth-payload-builder" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-consensus", "alloy-primitives", @@ -8637,8 +8785,8 @@ dependencies = [ [[package]] name = "reth-payload-builder-primitives" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "pin-project", "reth-payload-primitives", @@ -8649,8 +8797,8 @@ dependencies = [ [[package]] name = "reth-payload-primitives" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-consensus", "alloy-eips", @@ -8666,14 +8814,14 @@ dependencies = [ "reth-trie-common", "serde", "sha2 0.10.9", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", ] [[package]] name = "reth-payload-util" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-consensus", "alloy-primitives", @@ -8682,8 +8830,8 @@ dependencies = [ [[package]] name = "reth-payload-validator" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-consensus", "alloy-rpc-types-engine", @@ -8692,11 +8840,11 @@ dependencies = [ [[package]] name = "reth-primitives-traits" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4666a8d5b246650b23e6767a45e46334d352557f473e91c2ea7211cc29291cca" +version = "0.8.2" +source = "git+https://github.com/paradigmxyz/reth-core?rev=275ce4cf5befeb9f1e8acd935ff2882d2d25fc61#275ce4cf5befeb9f1e8acd935ff2882d2d25fc61" dependencies = [ "alloy-consensus", + "alloy-eip7928", "alloy-eips", "alloy-genesis", "alloy-primitives", @@ -8708,25 +8856,23 @@ dependencies = [ "bytes", "dashmap", "derive_more", + "evm2", "modular-bitfield", "once_cell", "proptest", "proptest-arbitrary-interop", - "quanta", + "quanta 0.13.0", "rayon", "reth-codecs", - "revm-bytecode", - "revm-primitives", - "revm-state", "secp256k1 0.30.0", "serde", - "thiserror 2.0.18", + "thiserror 2.0.21", ] [[package]] name = "reth-provider" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-consensus", "alloy-eip7928", @@ -8734,6 +8880,7 @@ dependencies = [ "alloy-genesis", "alloy-primitives", "alloy-rpc-types-engine", + "evm2", "eyre", "itertools 0.14.0", "libc", @@ -8762,10 +8909,8 @@ dependencies = [ "reth-storage-errors", "reth-storage-overlay", "reth-tasks", - "reth-tokio-util", "reth-trie", "reth-trie-db", - "revm", "rocksdb", "smallvec", "strum", @@ -8775,8 +8920,8 @@ dependencies = [ [[package]] name = "reth-prune" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-consensus", "alloy-primitives", @@ -8795,15 +8940,15 @@ dependencies = [ "reth-storage-api", "reth-tokio-util", "rustc-hash", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "tracing", ] [[package]] name = "reth-prune-types" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-primitives", "arbitrary", @@ -8812,35 +8957,19 @@ dependencies = [ "reth-codecs", "serde", "strum", - "thiserror 2.0.18", + "thiserror 2.0.21", "tracing", ] -[[package]] -name = "reth-revm" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" -dependencies = [ - "alloy-primitives", - "alloy-rlp", - "alloy-rpc-types-debug", - "reth-primitives-traits", - "reth-storage-api", - "reth-storage-errors", - "reth-trie", - "revm", -] - [[package]] name = "reth-rpc" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-consensus", "alloy-dyn-abi", "alloy-eip7928", "alloy-eips", - "alloy-evm", "alloy-genesis", "alloy-network", "alloy-primitives", @@ -8861,6 +8990,8 @@ dependencies = [ "async-trait", "derive_more", "dyn-clone", + "evm2", + "evm2-inspectors", "futures", "itertools 0.14.0", "jsonrpsee", @@ -8881,10 +9012,8 @@ dependencies = [ "reth-network-api", "reth-network-peers", "reth-network-types", - "reth-node-api", "reth-payload-primitives", "reth-primitives-traits", - "reth-revm", "reth-rpc-api", "reth-rpc-convert", "reth-rpc-engine-api", @@ -8895,12 +9024,10 @@ dependencies = [ "reth-tasks", "reth-transaction-pool", "reth-trie-common", - "revm", - "revm-inspectors", "serde", "serde_json", "sha2 0.10.9", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "tokio-stream", "tracing", @@ -8909,8 +9036,8 @@ dependencies = [ [[package]] name = "reth-rpc-api" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-eips", "alloy-genesis", @@ -8939,8 +9066,8 @@ dependencies = [ [[package]] name = "reth-rpc-builder" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-network", "alloy-provider", @@ -8972,7 +9099,7 @@ dependencies = [ "reth-tokio-util", "reth-transaction-pool", "serde", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "tokio-util", "tower", @@ -8982,28 +9109,28 @@ dependencies = [ [[package]] name = "reth-rpc-convert" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-consensus", - "alloy-evm", "alloy-json-rpc", "alloy-network", "alloy-primitives", "alloy-rpc-types-eth", "auto_impl", "dyn-clone", + "evm2", "jsonrpsee-types", "reth-evm", "reth-primitives-traits", "reth-rpc-traits", - "thiserror 2.0.18", + "thiserror 2.0.21", ] [[package]] name = "reth-rpc-engine-api" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-eips", "alloy-primitives", @@ -9026,21 +9153,20 @@ dependencies = [ "reth-tasks", "reth-transaction-pool", "serde", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "tracing", ] [[package]] name = "reth-rpc-eth-api" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-consensus", "alloy-dyn-abi", "alloy-eip7928", "alloy-eips", - "alloy-evm", "alloy-json-rpc", "alloy-network", "alloy-primitives", @@ -9051,6 +9177,8 @@ dependencies = [ "async-trait", "auto_impl", "dyn-clone", + "evm2", + "evm2-inspectors", "futures", "jsonrpsee", "jsonrpsee-types", @@ -9059,11 +9187,10 @@ dependencies = [ "reth-chainspec", "reth-errors", "reth-evm", + "reth-execution-types", "reth-network-api", - "reth-node-api", "reth-primitives-traits", "reth-prune-types", - "reth-revm", "reth-rpc-convert", "reth-rpc-eth-types", "reth-rpc-server-types", @@ -9071,8 +9198,6 @@ dependencies = [ "reth-tasks", "reth-transaction-pool", "reth-trie-common", - "revm", - "revm-inspectors", "serde_json", "tokio", "tracing", @@ -9080,14 +9205,13 @@ dependencies = [ [[package]] name = "reth-rpc-eth-types" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-chains", "alloy-consensus", "alloy-eip7928", "alloy-eips", - "alloy-evm", "alloy-network", "alloy-primitives", "alloy-rpc-client", @@ -9096,6 +9220,8 @@ dependencies = [ "alloy-sol-types", "alloy-transport", "derive_more", + "evm2", + "evm2-inspectors", "futures", "itertools 0.14.0", "jsonrpsee-core", @@ -9111,18 +9237,15 @@ dependencies = [ "reth-execution-types", "reth-metrics", "reth-primitives-traits", - "reth-revm", "reth-rpc-convert", "reth-rpc-server-types", "reth-storage-api", "reth-tasks", "reth-transaction-pool", - "reth-trie", - "revm", - "revm-inspectors", + "reth-trie-common", "schnellru", "serde", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "tokio-stream", "tracing", @@ -9131,13 +9254,15 @@ dependencies = [ [[package]] name = "reth-rpc-layer" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-rpc-types-engine", "http", + "http-body-util", "jsonrpsee-http-client", "pin-project", + "tokio", "tower", "tower-http", "tracing", @@ -9145,10 +9270,9 @@ dependencies = [ [[package]] name = "reth-rpc-server-types" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ - "alloy-eips", "alloy-primitives", "alloy-rpc-types-engine", "jsonrpsee-core", @@ -9161,9 +9285,8 @@ dependencies = [ [[package]] name = "reth-rpc-traits" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b417a50d3fa9b58bb1a22e46fb47e0866006f24abffa1fbe75ae60116b5b2efa" +version = "0.8.2" +source = "git+https://github.com/paradigmxyz/reth-core?rev=275ce4cf5befeb9f1e8acd935ff2882d2d25fc61#275ce4cf5befeb9f1e8acd935ff2882d2d25fc61" dependencies = [ "alloy-consensus", "alloy-network", @@ -9171,23 +9294,55 @@ dependencies = [ "alloy-rpc-types-eth", "alloy-signer", "reth-primitives-traits", - "thiserror 2.0.18", + "thiserror 2.0.21", ] [[package]] -name = "reth-stages" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +name = "reth-snap-sync" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ - "alloy-consensus", + "alloy-eip7928", + "alloy-eips", "alloy-primitives", - "alloy-rlp", - "eyre", - "futures-util", - "itertools 0.14.0", - "num-traits", - "page_size", - "rayon", + "evm2", + "futures", + "metrics", + "reth-db-api", + "reth-downloaders", + "reth-eth-wire-types", + "reth-metrics", + "reth-network-p2p", + "reth-network-peers", + "reth-primitives-traits", + "reth-prune-types", + "reth-stages-types", + "reth-storage-api", + "reth-storage-errors", + "reth-tasks", + "reth-trie-common", + "serde", + "serde_json", + "thiserror 2.0.21", + "tokio-util", + "tracing", +] + +[[package]] +name = "reth-stages" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +dependencies = [ + "alloy-consensus", + "alloy-eip7928", + "alloy-primitives", + "alloy-rlp", + "eyre", + "futures-util", + "itertools 0.14.0", + "num-traits", + "page_size", + "rayon", "reqwest", "reth-chainspec", "reth-codecs", @@ -9210,7 +9365,6 @@ dependencies = [ "reth-provider", "reth-prune", "reth-prune-types", - "reth-revm", "reth-stages-api", "reth-static-file-types", "reth-storage-api", @@ -9220,15 +9374,15 @@ dependencies = [ "reth-trie", "reth-trie-db", "tempfile", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "tracing", ] [[package]] name = "reth-stages-api" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-eips", "alloy-primitives", @@ -9248,29 +9402,30 @@ dependencies = [ "reth-static-file", "reth-static-file-types", "reth-tokio-util", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "tracing", ] [[package]] name = "reth-stages-types" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-primitives", "arbitrary", "bytes", "modular-bitfield", "reth-codecs", + "reth-primitives-traits", "reth-trie-common", "serde", ] [[package]] name = "reth-static-file" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-primitives", "parking_lot", @@ -9289,8 +9444,8 @@ dependencies = [ [[package]] name = "reth-static-file-types" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-primitives", "clap", @@ -9304,8 +9459,8 @@ dependencies = [ [[package]] name = "reth-storage-api" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-consensus", "alloy-eip7928", @@ -9313,6 +9468,7 @@ dependencies = [ "alloy-primitives", "alloy-rpc-types-engine", "auto_impl", + "reth-chain-state", "reth-chainspec", "reth-db-api", "reth-db-models", @@ -9322,16 +9478,15 @@ dependencies = [ "reth-prune-types", "reth-stages-types", "reth-storage-errors", - "reth-tokio-util", "reth-trie-common", - "revm", "serde_json", + "tokio", ] [[package]] name = "reth-storage-errors" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-eips", "alloy-primitives", @@ -9341,17 +9496,17 @@ dependencies = [ "reth-primitives-traits", "reth-prune-types", "reth-static-file-types", - "revm", - "thiserror 2.0.18", + "thiserror 2.0.21", ] [[package]] name = "reth-storage-overlay" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-eips", "alloy-primitives", + "evm2", "metrics", "parking_lot", "rayon", @@ -9374,8 +9529,8 @@ dependencies = [ [[package]] name = "reth-tasks" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "crossbeam-utils", "dashmap", @@ -9386,7 +9541,7 @@ dependencies = [ "pin-project", "rayon", "reth-metrics", - "thiserror 2.0.18", + "thiserror 2.0.21", "thread-priority", "tokio", "tracing", @@ -9395,8 +9550,8 @@ dependencies = [ [[package]] name = "reth-testing-utils" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-consensus", "alloy-eips", @@ -9411,8 +9566,8 @@ dependencies = [ [[package]] name = "reth-tokio-util" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "tokio", "tokio-stream", @@ -9421,12 +9576,11 @@ dependencies = [ [[package]] name = "reth-tracing" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "clap", "eyre", - "reth-tracing-otlp", "rolling-file", "tracing", "tracing-appender", @@ -9439,26 +9593,18 @@ dependencies = [ [[package]] name = "reth-tracing-otlp" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ - "base64 0.22.1", "clap", "eyre", - "opentelemetry", - "opentelemetry-otlp", - "opentelemetry-semantic-conventions", - "opentelemetry_sdk", - "tracing", - "tracing-opentelemetry", - "tracing-subscriber", "url", ] [[package]] name = "reth-transaction-pool" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-consensus", "alloy-eips", @@ -9466,7 +9612,7 @@ dependencies = [ "alloy-rlp", "aquamarine", "auto_impl", - "bitflags 2.11.1", + "bitflags 2.13.2", "futures-util", "imbl", "metrics", @@ -9486,13 +9632,12 @@ dependencies = [ "reth-primitives-traits", "reth-storage-api", "reth-tasks", - "revm", "rustc-hash", "schnellru", "serde", "serde_json", "smallvec", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "tokio-stream", "tracing", @@ -9500,8 +9645,8 @@ dependencies = [ [[package]] name = "reth-trie" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-consensus", "alloy-eips", @@ -9509,6 +9654,7 @@ dependencies = [ "alloy-rlp", "alloy-trie", "auto_impl", + "crossbeam-channel", "itertools 0.14.0", "metrics", "parking_lot", @@ -9517,17 +9663,17 @@ dependencies = [ "reth-primitives-traits", "reth-stages-types", "reth-storage-errors", + "reth-tasks", "reth-trie-common", "reth-trie-sparse", - "revm", "tracing", "triehash", ] [[package]] name = "reth-trie-common" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-consensus", "alloy-primitives", @@ -9539,6 +9685,7 @@ dependencies = [ "arrayvec", "bytes", "derive_more", + "evm2", "hash-db", "itertools 0.14.0", "nybbles", @@ -9546,15 +9693,15 @@ dependencies = [ "rayon", "reth-codecs", "reth-primitives-traits", - "revm", "serde", "serde_with", + "thiserror 2.0.21", ] [[package]] name = "reth-trie-db" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-primitives", "reth-db-api", @@ -9569,32 +9716,28 @@ dependencies = [ [[package]] name = "reth-trie-parallel" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ - "alloy-evm", "alloy-primitives", - "alloy-rlp", "crossbeam-channel", "crossbeam-utils", "metrics", "reth-execution-errors", + "reth-execution-types", "reth-metrics", "reth-primitives-traits", "reth-provider", - "reth-storage-errors", "reth-tasks", "reth-trie", - "reth-trie-sparse", - "revm", - "thiserror 2.0.18", + "thiserror 2.0.21", "tracing", ] [[package]] name = "reth-trie-sparse" -version = "2.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.10.1" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" dependencies = [ "alloy-primitives", "alloy-trie", @@ -9605,9 +9748,6 @@ dependencies = [ "reth-metrics", "reth-primitives-traits", "reth-trie-common", - "serde", - "serde_json", - "slotmap", "smallvec", "strum", "tracing", @@ -9615,252 +9755,30 @@ dependencies = [ [[package]] name = "reth-zstd-compressors" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "80addacffc5df9398c55919f8993922d2b688f2aa5753708fdd658ca3cc63e39" -dependencies = [ - "zstd", -] - -[[package]] -name = "revm" -version = "42.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b7c7fcd426beab3b91300a6d0d5eb8d583c0fad0fba451126e19fd51443eca62" -dependencies = [ - "revm-bytecode", - "revm-context", - "revm-context-interface", - "revm-database", - "revm-database-interface", - "revm-handler", - "revm-inspector", - "revm-interpreter", - "revm-precompile", - "revm-primitives", - "revm-state", -] - -[[package]] -name = "revm-bytecode" -version = "42.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "537356bdec80dbc04e4e6bb688b3441ff7cf18eecdcf3cac23150633c46467f1" -dependencies = [ - "bitvec", - "phf", - "revm-primitives", - "serde", -] - -[[package]] -name = "revm-context" -version = "42.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc6512f05f83378e29b2b016fa5bd7f5a533e3625548be4113732e1a536c2564" -dependencies = [ - "bitvec", - "cfg-if", - "derive-where", - "revm-bytecode", - "revm-context-interface", - "revm-database-interface", - "revm-primitives", - "revm-state", - "serde", -] - -[[package]] -name = "revm-context-interface" -version = "42.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "103fff818b10311034c0c11ff8760294ee0e3c320daab3c5717990fe8ee2617b" -dependencies = [ - "alloy-eip2930", - "alloy-eip7702", - "auto_impl", - "either", - "revm-database-interface", - "revm-primitives", - "revm-state", - "serde", -] - -[[package]] -name = "revm-database" -version = "42.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df72760eab0852100e748c7cb03ce0221626d60ac14534118c84c5cc894fb4c9" -dependencies = [ - "alloy-eips", - "derive_more", - "either", - "revm-bytecode", - "revm-database-interface", - "revm-primitives", - "revm-state", - "serde", -] - -[[package]] -name = "revm-database-interface" -version = "42.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9286c059a11be1dee814cafdc3a3ade57521c8caa050785a52c19a9d894f400" -dependencies = [ - "auto_impl", - "either", - "revm-primitives", - "revm-state", - "serde", - "thiserror 2.0.18", -] - -[[package]] -name = "revm-handler" -version = "42.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09126175c3fa482e71e80cc28c6bb17e681911e472b94d4f7f73dd6780411798" -dependencies = [ - "auto_impl", - "derive-where", - "revm-bytecode", - "revm-context", - "revm-context-interface", - "revm-database-interface", - "revm-interpreter", - "revm-precompile", - "revm-primitives", - "revm-state", - "serde", -] - -[[package]] -name = "revm-inspector" -version = "42.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4aa55b208b52f0c083ea68147c78866eeecadd7c0071a614f477de316b60648e" -dependencies = [ - "auto_impl", - "either", - "revm-context", - "revm-database-interface", - "revm-handler", - "revm-interpreter", - "revm-primitives", - "revm-state", - "serde", - "serde_json", -] - -[[package]] -name = "revm-inspectors" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90c136a072540987ee442e9824631835520b13e5756f20780a637ba2e11f9c28" -dependencies = [ - "alloy-primitives", - "alloy-rpc-types-eth", - "alloy-rpc-types-trace", - "alloy-sol-types", - "anstyle", - "colorchoice", - "revm", - "serde", - "serde_json", - "thiserror 2.0.18", -] - -[[package]] -name = "revm-interpreter" -version = "42.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd310927437752ce4bac6997b385772823b84843f04c82e151993bec1265a5ed" -dependencies = [ - "revm-bytecode", - "revm-context-interface", - "revm-primitives", - "revm-state", - "serde", -] - -[[package]] -name = "revm-precompile" -version = "42.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2431091420999795df6a200b9f7933defe3d654710560a895e6bcabbd9954a5" -dependencies = [ - "ark-bls12-381", - "ark-bn254", - "ark-ec", - "ark-ff 0.6.0", - "ark-serialize 0.6.0", - "arrayref", - "aurora-engine-modexp", - "aws-lc-rs", - "blst", - "c-kzg", - "cfg-if", - "k256", - "p256", - "revm-context-interface", - "revm-primitives", - "ripemd 0.2.0", - "secp256k1 0.31.1", - "sha2 0.11.0", -] - -[[package]] -name = "revm-primitives" -version = "42.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ef5564c1bce219fd08beca43d4f39fdcbc19193fa4f604c0c6b58950a13194a" -dependencies = [ - "alloy-primitives", - "once_cell", - "serde", -] - -[[package]] -name = "revm-state" -version = "42.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2c4ae66db3abfcb565854dbfc95513bfa440b3dc390ddf8e50b0363d12a6fa79" +version = "0.8.2" +source = "git+https://github.com/paradigmxyz/reth-core?rev=275ce4cf5befeb9f1e8acd935ff2882d2d25fc61#275ce4cf5befeb9f1e8acd935ff2882d2d25fc61" dependencies = [ - "alloy-eip7928", - "bitflags 2.11.1", - "nonmax", - "revm-bytecode", - "revm-primitives", - "serde", + "zstd 0.14.3", ] [[package]] -name = "revm-statetest-types" -version = "42.0.0" +name = "rfc6979" +version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b61ce97f20c478a2b9be24e967d7c6481301d466a47b3c13dd3b030a7a93709d" +checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2" dependencies = [ - "alloy-eip7928", - "k256", - "revm-context", - "revm-context-interface", - "revm-database", - "revm-primitives", - "revm-state", - "serde", - "serde_json", - "thiserror 2.0.18", + "hmac 0.12.1", + "subtle", ] [[package]] name = "rfc6979" -version = "0.4.0" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2" +checksum = "b4a459cddafb3fe76b31fd8f1108007566c40301feb64dc7b54656eb7388172b" dependencies = [ - "hmac", - "subtle", + "crypto-bigint 0.7.10", + "hmac 0.13.0", ] [[package]] @@ -9976,9 +9894,9 @@ checksum = "afab94fb28594581f62d981211a9a4d53cc8130bbcbbb89a0440d9b8e81a7746" [[package]] name = "ruint" -version = "1.20.0" +version = "1.21.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f5e99bff0393163bb25029a6af25d3d8d202ba5b5438a74d1bd8789f5c822970" +checksum = "a0de3fa9b4dac39cc2bd65679bacf9f531899d933605e2963b40c2129cdb55f2" dependencies = [ "alloy-rlp", "arbitrary", @@ -9989,12 +9907,13 @@ dependencies = [ "bytes", "fastrlp 0.3.1", "fastrlp 0.4.0", - "num-bigint", + "num-bigint 0.4.6", "num-integer", "num-traits", "parity-scale-codec", "primitive-types", "proptest", + "rand 0.10.2", "rand 0.8.6", "rand 0.9.4", "rlp", @@ -10049,7 +9968,7 @@ version = "1.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" dependencies = [ - "bitflags 2.11.1", + "bitflags 2.13.2", "errno", "libc", "linux-raw-sys", @@ -10258,11 +10177,26 @@ version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc" dependencies = [ - "base16ct", - "der", + "base16ct 0.2.0", + "der 0.7.10", "generic-array", - "pkcs8", - "serdect", + "pkcs8 0.10.2", + "serdect 0.2.0", + "subtle", + "zeroize", +] + +[[package]] +name = "sec1" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56d437c2f19203ce5f7122e507831de96f3d2d4d3be5af44a0b0a09d8a80e4d" +dependencies = [ + "base16ct 1.0.0", + "ctutils", + "der 0.8.3", + "hybrid-array", + "serdect 0.4.3", "subtle", "zeroize", ] @@ -10290,6 +10224,17 @@ dependencies = [ "secp256k1-sys 0.11.0", ] +[[package]] +name = "secp256k1" +version = "0.33.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7f404a8dab7a7a5a631e741d8699aa9c8e1d689fc26ccf897c7187565490b69" +dependencies = [ + "rand 0.9.4", + "secp256k1-sys 0.14.1", + "serde", +] + [[package]] name = "secp256k1-sys" version = "0.10.1" @@ -10308,13 +10253,22 @@ dependencies = [ "cc", ] +[[package]] +name = "secp256k1-sys" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b2992d4a3cd244539a7d5d0966aadbe5ca7fb868a5d7e38c29499b9e709bbd" +dependencies = [ + "cc", +] + [[package]] name = "security-framework" version = "3.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" dependencies = [ - "bitflags 2.11.1", + "bitflags 2.13.2", "core-foundation 0.10.1", "core-foundation-sys", "libc", @@ -10377,6 +10331,17 @@ dependencies = [ "serde_derive", ] +[[package]] +name = "serde-encoded-bytes" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "988156b15813ab36ef7527430ed5d055d826f0d5fae2d17514a943360db27200" +dependencies = [ + "base64 0.22.1", + "hex", + "serde", +] + [[package]] name = "serde_core" version = "1.0.228" @@ -10403,7 +10368,6 @@ version = "1.0.149" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86" dependencies = [ - "indexmap 2.14.0", "itoa", "memchr", "serde", @@ -10471,7 +10435,17 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a84f14a19e9a014bb9f4512488d9829a68e04ecabffb0f9904cd1ace94598177" dependencies = [ - "base16ct", + "base16ct 0.2.0", + "serde", +] + +[[package]] +name = "serdect" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66cf8fedced2fcf12406bcb34223dffb92eaf34908ede12fed414c82b7f00b3e" +dependencies = [ + "base16ct 1.0.0", "serde", ] @@ -10594,6 +10568,16 @@ dependencies = [ "rand_core 0.6.4", ] +[[package]] +name = "signature" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28d567dcbaf0049cb8ac2608a76cd95ff9e4412e1899d389ee400918ca7537f5" +dependencies = [ + "digest 0.11.3", + "rand_core 0.10.1", +] + [[package]] name = "simd-adler32" version = "0.3.9" @@ -10622,9 +10606,9 @@ version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0d585997b0ac10be3c5ee635f1bab02d512760d14b7c468801ac8a01d9ae5f1d" dependencies = [ - "num-bigint", + "num-bigint 0.4.6", "num-traits", - "thiserror 2.0.18", + "thiserror 2.0.21", "time", ] @@ -10646,15 +10630,6 @@ version = "0.4.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" -[[package]] -name = "slotmap" -version = "1.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bdd58c3c93c3d278ca835519292445cb4b0d4dc59ccfdf7ceadaab3f8aeb4038" -dependencies = [ - "version_check", -] - [[package]] name = "smallvec" version = "1.15.1" @@ -10665,6 +10640,12 @@ dependencies = [ "serde", ] +[[package]] +name = "smolgen" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c9a98255db4f93af8770f11f42b5a7f345cd93b96dafe7b1ae72ef99a16386" + [[package]] name = "snap" version = "1.1.1" @@ -10704,7 +10685,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" dependencies = [ "base64ct", - "der", + "der 0.7.10", +] + +[[package]] +name = "spki" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ef958a98b9d5da290cfc78946e9f3e61e1e62a18db0d92cac0b83cc161491a9" +dependencies = [ + "base64ct", + "der 0.8.3", ] [[package]] @@ -10843,7 +10834,7 @@ version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a13f3d0daba03132c0aa9767f98351b3488edc2c100cda2d2ec2b04f3d8d3c8b" dependencies = [ - "bitflags 2.11.1", + "bitflags 2.13.2", "core-foundation 0.9.4", "system-configuration-sys", ] @@ -10911,11 +10902,11 @@ dependencies = [ [[package]] name = "thiserror" -version = "2.0.18" +version = "2.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" dependencies = [ - "thiserror-impl 2.0.18", + "thiserror-impl 2.0.21", ] [[package]] @@ -10931,13 +10922,13 @@ dependencies = [ [[package]] name = "thiserror-impl" -version = "2.0.18" +version = "2.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" dependencies = [ "proc-macro2", "quote", - "syn 2.0.117", + "syn 3.0.6", ] [[package]] @@ -10946,7 +10937,7 @@ version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2210811179577da3d54eb69ab0b50490ee40491a25d95b8c6011ba40771cb721" dependencies = [ - "bitflags 2.11.1", + "bitflags 2.13.2", "cfg-if", "libc", "log", @@ -11137,6 +11128,7 @@ dependencies = [ "futures-core", "futures-io", "futures-sink", + "futures-util", "pin-project-lite", "slab", "tokio", @@ -11202,54 +11194,6 @@ version = "1.1.1+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "756daf9b1013ebe47a8776667b466417e2d4c5679d441c26230efd9ef78692db" -[[package]] -name = "tonic" -version = "0.14.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac2a5518c70fa84342385732db33fb3f44bc4cc748936eb5833d2df34d6445ef" -dependencies = [ - "async-trait", - "base64 0.22.1", - "bytes", - "http", - "http-body", - "http-body-util", - "hyper", - "hyper-timeout", - "hyper-util", - "percent-encoding", - "pin-project", - "sync_wrapper", - "tokio", - "tokio-stream", - "tower", - "tower-layer", - "tower-service", - "tracing", -] - -[[package]] -name = "tonic-prost" -version = "0.14.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50849f68853be452acf590cde0b146665b8d507b3b8af17261df47e02c209ea0" -dependencies = [ - "bytes", - "prost", - "tonic", -] - -[[package]] -name = "tonic-types" -version = "0.14.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73ab1b02061f83d519bba3caa167f88f261ef05720ab8ebc954ade70de3348e8" -dependencies = [ - "prost", - "prost-types", - "tonic", -] - [[package]] name = "tower" version = "0.5.3" @@ -11258,16 +11202,11 @@ checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" dependencies = [ "futures-core", "futures-util", - "hdrhistogram", - "indexmap 2.14.0", "pin-project-lite", - "slab", "sync_wrapper", "tokio", - "tokio-util", "tower-layer", "tower-service", - "tracing", ] [[package]] @@ -11277,28 +11216,21 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "68d6fdd9f81c2819c9a8b0e0cd91660e7746a8e6ea2ba7c6b2b057985f6bcb51" dependencies = [ "async-compression", - "base64 0.22.1", - "bitflags 2.11.1", + "bitflags 2.13.2", "bytes", "futures-core", "futures-util", "http", "http-body", "http-body-util", - "http-range-header", - "httpdate", "mime", - "mime_guess", - "percent-encoding", "pin-project-lite", "tokio", "tokio-util", "tower", "tower-layer", "tower-service", - "tracing", "url", - "uuid", ] [[package]] @@ -11333,7 +11265,7 @@ checksum = "050686193eb999b4bb3bc2acfa891a13da00f79734704c4b8b4ef1a10b368a3c" dependencies = [ "crossbeam-channel", "symlink", - "thiserror 2.0.18", + "thiserror 2.0.21", "time", "tracing-subscriber", ] @@ -11414,22 +11346,6 @@ dependencies = [ "tracing-subscriber", ] -[[package]] -name = "tracing-opentelemetry" -version = "0.33.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "adbc64cba7137545b8044cb1fe9814f7aacf3c6b5f9b45be8bb5db538befdb26" -dependencies = [ - "js-sys", - "opentelemetry", - "smallvec", - "tracing", - "tracing-core", - "tracing-log", - "tracing-subscriber", - "web-time", -] - [[package]] name = "tracing-samply" version = "0.1.5" @@ -11512,6 +11428,15 @@ dependencies = [ "rlp", ] +[[package]] +name = "triomphe" +version = "0.1.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d15f4f5898bcfc5d8a8e45ed30b2f108d710c1a2e5489dbf80e078f707181bc" +dependencies = [ + "serde", +] + [[package]] name = "try-lock" version = "0.2.5" @@ -11533,7 +11458,7 @@ dependencies = [ "rustls", "rustls-pki-types", "sha1", - "thiserror 2.0.18", + "thiserror 2.0.21", ] [[package]] @@ -11584,12 +11509,6 @@ version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94" -[[package]] -name = "unicase" -version = "2.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dbc4bc3a9f746d862c45cb89d705aa10f187bb96c76001afab07a0d35ce60142" - [[package]] name = "unicode-ident" version = "1.0.24" @@ -11803,6 +11722,12 @@ version = "0.11.1+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" +[[package]] +name = "wasip1" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5e26842486624357dbeb8f0381cf1fb42f022291fd787d4a816768fec8cc760" + [[package]] name = "wasip2" version = "1.0.3+wasi-0.2.9" @@ -11917,7 +11842,7 @@ version = "0.244.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe" dependencies = [ - "bitflags 2.11.1", + "bitflags 2.13.2", "hashbrown 0.15.5", "indexmap 2.14.0", "semver 1.0.28", @@ -12040,6 +11965,31 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" +[[package]] +name = "wincode" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "063b5affe63fb4e584a33101d8808f01f2348b4f533db6223bf27263a0fdb9e9" +dependencies = [ + "pastey", + "proc-macro2", + "quote", + "thiserror 2.0.21", + "wincode-derive", +] + +[[package]] +name = "wincode-derive" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11d582d9fc9d813264407a9e16bfa16846ccf15ef032f9bbcd700741bdc00255" +dependencies = [ + "darling", + "proc-macro2", + "quote", + "syn 2.0.117", +] + [[package]] name = "windows" version = "0.61.3" @@ -12510,6 +12460,9 @@ name = "wit-bindgen" version = "0.57.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" +dependencies = [ + "bitflags 2.13.2", +] [[package]] name = "wit-bindgen-core" @@ -12560,7 +12513,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2" dependencies = [ "anyhow", - "bitflags 2.11.1", + "bitflags 2.13.2", "indexmap 2.14.0", "log", "serde", @@ -12590,6 +12543,18 @@ dependencies = [ "wasmparser", ] +[[package]] +name = "wnaf" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "795ca18b3fdb5e62bf982199278341ddcf7ebf7d32e25e212ad05d496e95f6fa" +dependencies = [ + "ff 0.14.0", + "group 0.14.0", + "hybrid-array", + "primefield", +] + [[package]] name = "writeable" version = "0.6.3" @@ -12609,7 +12574,7 @@ dependencies = [ "pharos", "rustc_version 0.4.1", "send_wrapper 0.6.0", - "thiserror 2.0.18", + "thiserror 2.0.21", "wasm-bindgen", "wasm-bindgen-futures", "web-sys", @@ -12769,7 +12734,16 @@ version = "0.13.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cdb02c3132d251ab1606e9fc913a7da6c6ed08cc263df15edf082e1dc497d157" dependencies = [ - "zstd-safe", + "zstd-safe 7.4.0", +] + +[[package]] +name = "zstd" +version = "0.14.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db3ae9bf90af6e40197bef767eeefc46ad6397420fe873830bd85e5fbbfb3c70" +dependencies = [ + "zstd-safe 8.2.0", ] [[package]] @@ -12781,6 +12755,15 @@ dependencies = [ "zstd-sys", ] +[[package]] +name = "zstd-safe" +version = "8.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ded520f16b29e1a9b771c722221b2b0a0398c2316d9bb3c42b458a5414d7434b" +dependencies = [ + "zstd-sys", +] + [[package]] name = "zstd-sys" version = "2.1.2+zstd.1.5.7" diff --git a/Cargo.toml b/Cargo.toml index f19a79e9..ca14f86d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,7 @@ [workspace.package] version = "1.4.1" edition = "2024" -rust-version = "1.95" +rust-version = "1.96" license = "MIT OR Apache-2.0" publish = false @@ -110,103 +110,98 @@ morph-rpc = { path = "crates/rpc" } morph-revm = { path = "crates/revm", default-features = false } morph-txpool = { path = "crates/txpool", default-features = false } -reth-basic-payload-builder = { git = "https://github.com/morph-l2/reth", tag = "v2.5.2-morph.1" } -reth-chain-state = { git = "https://github.com/morph-l2/reth", tag = "v2.5.2-morph.1" } -reth-chainspec = { git = "https://github.com/morph-l2/reth", tag = "v2.5.2-morph.1" } -reth-cli = { git = "https://github.com/morph-l2/reth", tag = "v2.5.2-morph.1" } -reth-cli-commands = { git = "https://github.com/morph-l2/reth", tag = "v2.5.2-morph.1" } -reth-cli-runner = { git = "https://github.com/morph-l2/reth", tag = "v2.5.2-morph.1" } -reth-cli-util = { git = "https://github.com/morph-l2/reth", tag = "v2.5.2-morph.1" } -reth-codecs = { version = "0.6.0", default-features = false } -reth-codecs-derive = "0.6.0" -reth-consensus = { git = "https://github.com/morph-l2/reth", tag = "v2.5.2-morph.1" } -reth-consensus-common = { git = "https://github.com/morph-l2/reth", tag = "v2.5.2-morph.1" } -reth-db = { git = "https://github.com/morph-l2/reth", tag = "v2.5.2-morph.1" } -reth-db-api = { git = "https://github.com/morph-l2/reth", tag = "v2.5.2-morph.1" } -reth-e2e-test-utils = { git = "https://github.com/morph-l2/reth", tag = "v2.5.2-morph.1" } -reth-engine-local = { git = "https://github.com/morph-l2/reth", tag = "v2.5.2-morph.1" } -reth-engine-primitives = { git = "https://github.com/morph-l2/reth", tag = "v2.5.2-morph.1" } -reth-engine-tree = { git = "https://github.com/morph-l2/reth", tag = "v2.5.2-morph.1" } -reth-errors = { git = "https://github.com/morph-l2/reth", tag = "v2.5.2-morph.1" } -reth-exex = { git = "https://github.com/morph-l2/reth", tag = "v2.5.2-morph.1" } -reth-exex-test-utils = { git = "https://github.com/morph-l2/reth", tag = "v2.5.2-morph.1" } -reth-execution-errors = { git = "https://github.com/morph-l2/reth", tag = "v2.5.2-morph.1" } -reth-eth-wire-types = { git = "https://github.com/morph-l2/reth", tag = "v2.5.2-morph.1" } -reth-ethereum = { git = "https://github.com/morph-l2/reth", tag = "v2.5.2-morph.1" } -reth-ethereum-cli = { git = "https://github.com/morph-l2/reth", tag = "v2.5.2-morph.1" } -reth-ethereum-consensus = { git = "https://github.com/morph-l2/reth", tag = "v2.5.2-morph.1" } -reth-ethereum-engine-primitives = { git = "https://github.com/morph-l2/reth", tag = "v2.5.2-morph.1" } -reth-ethereum-primitives = { git = "https://github.com/morph-l2/reth", tag = "v2.5.2-morph.1", default-features = false } -reth-evm = { git = "https://github.com/morph-l2/reth", tag = "v2.5.2-morph.1" } -reth-evm-ethereum = { git = "https://github.com/morph-l2/reth", tag = "v2.5.2-morph.1" } -reth-execution-types = { git = "https://github.com/morph-l2/reth", tag = "v2.5.2-morph.1" } -reth-metrics = { git = "https://github.com/morph-l2/reth", tag = "v2.5.2-morph.1" } -reth-network-peers = { git = "https://github.com/morph-l2/reth", tag = "v2.5.2-morph.1" } -reth-node-api = { git = "https://github.com/morph-l2/reth", tag = "v2.5.2-morph.1" } -reth-node-builder = { git = "https://github.com/morph-l2/reth", tag = "v2.5.2-morph.1" } -reth-node-core = { git = "https://github.com/morph-l2/reth", tag = "v2.5.2-morph.1" } -reth-node-ethereum = { git = "https://github.com/morph-l2/reth", tag = "v2.5.2-morph.1" } -reth-node-metrics = { git = "https://github.com/morph-l2/reth", tag = "v2.5.2-morph.1" } -reth-payload-builder = { git = "https://github.com/morph-l2/reth", tag = "v2.5.2-morph.1" } -reth-payload-primitives = { git = "https://github.com/morph-l2/reth", tag = "v2.5.2-morph.1" } -reth-payload-util = { git = "https://github.com/morph-l2/reth", tag = "v2.5.2-morph.1" } -reth-primitives-traits = { version = "0.6.0", default-features = false } -reth-prune-types = { git = "https://github.com/morph-l2/reth", tag = "v2.5.2-morph.1" } -reth-provider = { git = "https://github.com/morph-l2/reth", tag = "v2.5.2-morph.1" } -reth-rpc = { git = "https://github.com/morph-l2/reth", tag = "v2.5.2-morph.1" } -reth-rpc-api = { git = "https://github.com/morph-l2/reth", tag = "v2.5.2-morph.1" } -reth-rpc-builder = { git = "https://github.com/morph-l2/reth", tag = "v2.5.2-morph.1" } -reth-rpc-convert = { git = "https://github.com/morph-l2/reth", tag = "v2.5.2-morph.1" } -reth-rpc-eth-api = { git = "https://github.com/morph-l2/reth", tag = "v2.5.2-morph.1" } -reth-rpc-eth-types = { git = "https://github.com/morph-l2/reth", tag = "v2.5.2-morph.1" } -reth-rpc-server-types = { git = "https://github.com/morph-l2/reth", tag = "v2.5.2-morph.1" } -reth-storage-api = { git = "https://github.com/morph-l2/reth", tag = "v2.5.2-morph.1" } -reth-storage-errors = { git = "https://github.com/morph-l2/reth", tag = "v2.5.2-morph.1", default-features = false } -reth-storage-overlay = { git = "https://github.com/morph-l2/reth", tag = "v2.5.2-morph.1" } -reth-tasks = { git = "https://github.com/morph-l2/reth", tag = "v2.5.2-morph.1" } -reth-tracing = { git = "https://github.com/morph-l2/reth", tag = "v2.5.2-morph.1" } -reth-trie = { git = "https://github.com/morph-l2/reth", tag = "v2.5.2-morph.1" } -reth-trie-common = { git = "https://github.com/morph-l2/reth", tag = "v2.5.2-morph.1" } -reth-transaction-pool = { git = "https://github.com/morph-l2/reth", tag = "v2.5.2-morph.1" } -reth-zstd-compressors = { version = "0.6.0", default-features = false } -reth-execution-cache = { git = "https://github.com/morph-l2/reth", tag = "v2.5.2-morph.1" } -reth-trie-parallel = { git = "https://github.com/morph-l2/reth", tag = "v2.5.2-morph.1" } -reth-trie-sparse = { git = "https://github.com/morph-l2/reth", tag = "v2.5.2-morph.1", default-features = false } +reth-basic-payload-builder = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } +reth-chain-state = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } +reth-chainspec = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } +reth-cli = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } +reth-cli-commands = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } +reth-cli-runner = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } +reth-cli-util = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } +reth-codecs = { version = "0.8.2", default-features = false } +reth-codecs-derive = "0.8.2" +reth-consensus = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } +reth-consensus-common = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } +reth-db = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } +reth-db-api = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } +reth-e2e-test-utils = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } +reth-engine-local = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } +reth-engine-primitives = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } +reth-engine-tree = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } +reth-errors = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } +reth-exex = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } +reth-exex-test-utils = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } +reth-execution-errors = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } +reth-eth-wire-types = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } +reth-ethereum = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } +reth-ethereum-cli = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } +reth-ethereum-consensus = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } +reth-ethereum-engine-primitives = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } +reth-ethereum-primitives = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1", default-features = false } +reth-evm = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } +reth-evm-ethereum = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } +reth-execution-types = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } +reth-metrics = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } +reth-network-peers = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } +reth-node-api = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } +reth-node-builder = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } +reth-node-core = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } +reth-node-ethereum = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } +reth-node-metrics = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } +reth-payload-builder = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } +reth-payload-primitives = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } +reth-payload-util = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } +reth-primitives-traits = { version = "0.8.2", default-features = false } +reth-prune-types = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } +reth-provider = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } +reth-rpc = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } +reth-rpc-api = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } +reth-rpc-builder = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } +reth-rpc-convert = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } +reth-rpc-eth-api = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } +reth-rpc-eth-types = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } +reth-rpc-server-types = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } +reth-storage-api = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } +reth-storage-errors = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1", default-features = false } +reth-storage-overlay = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } +reth-tasks = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } +reth-tracing = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } +reth-trie = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } +reth-trie-common = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } +reth-transaction-pool = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } +reth-zstd-compressors = { version = "0.8.2", default-features = false } +reth-execution-cache = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } +reth-trie-parallel = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } +reth-trie-sparse = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1", default-features = false } -reth-revm = { git = "https://github.com/morph-l2/reth", tag = "v2.5.2-morph.1", features = [ - "std", - "optional-checks", -] } -revm = { version = "42.0.1", features = [ - "optional_fee_charge", - "optional_eip7623", -], default-features = false } +# evm2 has no release yet; this is the rev reth v2.10.1 declares, overridden by the +# `[patch]` below to the rev it actually builds against. +evm2 = { git = "https://github.com/alloy-rs/evm2", rev = "592bf18c4e22fff54ac9b4db606c4ee276e345cb", default-features = false } +evm2-inspectors = { git = "https://github.com/alloy-rs/evm2", rev = "592bf18c4e22fff54ac9b4db606c4ee276e345cb", default-features = false } -alloy = { version = "2.3.0", default-features = false } -alloy-consensus = { version = "2.3.0", default-features = false } -alloy-contract = { version = "2.3.0", default-features = false } -alloy-eip7928 = { version = "0.4.5", default-features = false } -alloy-eips = { version = "2.3.0", default-features = false } -alloy-evm = { version = "0.38.0", default-features = false } -alloy-genesis = "2.3.0" -alloy-hardforks = "0.4.7" -alloy-network = { version = "2.3.0", default-features = false } +alloy = { version = "2.5.0", default-features = false } +alloy-consensus = { version = "2.5.0", default-features = false } +alloy-contract = { version = "2.5.0", default-features = false } +alloy-eip7928 = { version = "0.4.10", default-features = false } +alloy-eips = { version = "2.5.0", default-features = false } +alloy-genesis = "2.5.0" +alloy-hardforks = "0.4.11" +alloy-network = { version = "2.5.0", default-features = false } alloy-primitives = { version = "1.6.1", default-features = false } -alloy-provider = { version = "2.3.0", default-features = false } +alloy-provider = { version = "2.5.0", default-features = false } alloy-rlp = "0.3.16" -alloy-trie = "0.9.4" -alloy-rpc-types-debug = "2.3.0" -alloy-rpc-types-engine = "2.3.0" -alloy-rpc-types-eth = { version = "2.3.0" } -alloy-serde = "2.3.0" -alloy-signer = "2.3.0" -alloy-signer-local = "2.3.0" +# reth v2.10.1's `reth-trie-common` builds `HashBuilder` with a struct literal, which 0.9.9 +# breaks by adding a field. +alloy-trie = "=0.9.8" +alloy-rpc-types-debug = "2.5.0" +alloy-rpc-types-engine = "2.5.0" +alloy-rpc-types-eth = { version = "2.5.0" } +alloy-serde = "2.5.0" +alloy-signer = "2.5.0" +alloy-signer-local = "2.5.0" alloy-sol-types = { version = "1.6.1", default-features = false } -alloy-transport = "2.3.0" +alloy-transport = "2.5.0" alloy-chains = { version = "0.2.33", default-features = false } crossbeam-channel = "0.5.13" -revm-primitives = { version = "42.0.0", default-features = false } -revm-statetest-types = { version = "42.0.0", default-features = false } arbitrary = { version = "1.3", features = ["derive"] } async-lock = "3.4.1" async-trait = "0.1.92" @@ -257,3 +252,19 @@ criterion = "0.7.0" test-case = "3" pyroscope = "0.5.8" pyroscope_pprofrs = "0.2.10" + +# Patches only take effect at the root workspace, so reth v2.10.1's own overrides are +# repeated here. Keep both sections identical to the `[patch]` sections of the pinned reth +# tag; a drifted rev compiles a second, incompatible copy of these crates. +# +# Cargo requires a distinct patch source URL; www.github.com redirects to the public repository. +[patch."https://github.com/alloy-rs/evm2"] +evm2 = { git = "https://www.github.com/alloy-rs/evm2", rev = "01df8f6a396d0250da286cb763faa6ec292d65b5" } +evm2-inspectors = { git = "https://www.github.com/alloy-rs/evm2", rev = "01df8f6a396d0250da286cb763faa6ec292d65b5" } + +[patch.crates-io] +reth-codecs = { git = "https://github.com/paradigmxyz/reth-core", rev = "275ce4cf5befeb9f1e8acd935ff2882d2d25fc61" } +reth-codecs-derive = { git = "https://github.com/paradigmxyz/reth-core", rev = "275ce4cf5befeb9f1e8acd935ff2882d2d25fc61" } +reth-primitives-traits = { git = "https://github.com/paradigmxyz/reth-core", rev = "275ce4cf5befeb9f1e8acd935ff2882d2d25fc61" } +reth-rpc-traits = { git = "https://github.com/paradigmxyz/reth-core", rev = "275ce4cf5befeb9f1e8acd935ff2882d2d25fc61" } +reth-zstd-compressors = { git = "https://github.com/paradigmxyz/reth-core", rev = "275ce4cf5befeb9f1e8acd935ff2882d2d25fc61" } diff --git a/bin/morph-statetest/Cargo.toml b/bin/morph-statetest/Cargo.toml index a4e687de..e458b491 100644 --- a/bin/morph-statetest/Cargo.toml +++ b/bin/morph-statetest/Cargo.toml @@ -7,7 +7,6 @@ license.workspace = true publish.workspace = true [dependencies] -alloy-evm.workspace = true alloy-primitives.workspace = true alloy-rlp.workspace = true alloy-trie.workspace = true @@ -17,8 +16,7 @@ morph-chainspec.workspace = true morph-evm.workspace = true morph-revm.workspace = true morph-primitives.workspace = true -revm = { workspace = true, features = ["tracer"] } -revm-statetest-types.workspace = true +evm2 = { workspace = true, features = ["std"] } serde.workspace = true serde_json.workspace = true thiserror.workspace = true diff --git a/crates/chainspec/Cargo.toml b/crates/chainspec/Cargo.toml index 1e2c858b..dd4dd34a 100644 --- a/crates/chainspec/Cargo.toml +++ b/crates/chainspec/Cargo.toml @@ -21,13 +21,14 @@ reth-primitives-traits.workspace = true alloy-chains.workspace = true alloy-consensus.workspace = true -alloy-evm.workspace = true alloy-genesis.workspace = true alloy-primitives.workspace = true alloy-eips.workspace = true alloy-hardforks.workspace = true alloy-serde.workspace = true +evm2.workspace = true + auto_impl.workspace = true eyre = { workspace = true, optional = true } serde.workspace = true diff --git a/crates/chainspec/src/hardfork.rs b/crates/chainspec/src/hardfork.rs index 5c3234e0..2b16f866 100644 --- a/crates/chainspec/src/hardfork.rs +++ b/crates/chainspec/src/hardfork.rs @@ -31,8 +31,8 @@ //! Bernoulli and Curie use block-based activation, while Morph203, Viridian, //! Emerald, Jade, and Celadon use timestamp-based activation. -use alloy_evm::revm::primitives::hardfork::SpecId; use alloy_hardforks::hardfork; +use evm2::SpecId; use reth_chainspec::{EthereumHardforks, ForkCondition}; hardfork!( @@ -206,9 +206,9 @@ impl From for MorphHardfork { /// Bernoulli/Curie/Morph203 all map to CANCUN), this returns the /// latest hardfork for the given spec level. fn from(spec: SpecId) -> Self { - if spec.is_enabled_in(SpecId::OSAKA) { + if spec.enables(SpecId::OSAKA) { Self::Celadon - } else if spec.is_enabled_in(SpecId::PRAGUE) { + } else if spec.enables(SpecId::PRAGUE) { Self::Viridian } else { // CANCUN or below → Morph203 (latest CANCUN-level hardfork) @@ -220,10 +220,10 @@ impl From for MorphHardfork { #[cfg(test)] mod tests { use super::*; - use alloy_evm::revm::{ - context::{Cfg, CfgEnv}, - context_interface::cfg::gas_params::GasParams, - primitives::eip7702, + use evm2::{ + EvmFeatures, Version, + interpreter::gas::{EIP7702_PER_AUTH_BASE_COST, EIP7702_PER_EMPTY_ACCOUNT_COST}, + version::GasId, }; #[test] @@ -252,53 +252,46 @@ mod tests { for fork in forks { let spec = SpecId::from(fork); assert!( - spec < SpecId::AMSTERDAM, + !spec.enables(SpecId::AMSTERDAM), "MorphHardfork {fork:?} maps to SpecId {spec:?}, which would enable Amsterdam-era gas semantics" ); - let params = GasParams::new_spec(spec); - assert_eq!( - params.tx_eip7702_state_gas_bytecode(), - 0, + // The Morph EVM version starts from the base version of the mapped spec, so + // neither Amsterdam gas model may be switched on there. + let version = Version::base(spec); + assert!( + !version.feature(EvmFeatures::EIP8037), "MorphHardfork {fork:?} must not enable EIP-8037 state gas" ); - - // `MorphEvmHandler::validate_initial_tx_gas` derives its EIP-2780 intrinsic-gas - // info from this flag. It must stay disabled for every Morph hardfork. - let cfg = CfgEnv::::default().with_spec_and_mainnet_gas_params(fork); assert!( - !cfg.is_amsterdam_eip2780_enabled(), + !version.feature(EvmFeatures::EIP2780), "MorphHardfork {fork:?} must not enable EIP-2780 intrinsic gas" ); } - // Positive control: the EIP-2780 flag really is derived from the spec, so the - // per-fork assertions above are not vacuously true. + // Positive control: both flags really are derived from the spec, so the per-fork + // assertions above are not vacuously true. + let amsterdam = Version::base(SpecId::AMSTERDAM); assert!( - CfgEnv::::default() - .with_spec_and_mainnet_gas_params(SpecId::AMSTERDAM) - .is_amsterdam_eip2780_enabled(), - "EIP-2780 flag is no longer spec-derived; the guard above would be vacuous" + amsterdam.feature(EvmFeatures::EIP8037) && amsterdam.feature(EvmFeatures::EIP2780), + "Amsterdam gas flags are no longer spec-derived; the guard above would be vacuous" ); } - /// The whole EIP-7702 per-authorization refund must be the *regular* refund, i.e. - /// `PER_EMPTY_ACCOUNT_COST - PER_AUTH_BASE_COST` with nothing diverted elsewhere. - /// - /// revm 42 removed `tx_eip7702_state_refund` / `tx_eip7702_auth_refund`, so the - /// invariant can no longer be written as "regular == total"; asserting the full - /// per-auth delta against revm's own constants is the equivalent that survives. + /// The whole EIP-7702 per-authorization refund must be the execution-gas refund, i.e. + /// `PER_EMPTY_ACCOUNT_COST - PER_AUTH_BASE_COST` with nothing diverted to state gas. #[test] fn test_eip7702_refund_stays_regular_for_morph_specs() { for spec in [SpecId::CANCUN, SpecId::PRAGUE, SpecId::OSAKA] { - let params = GasParams::new_spec(spec); - let expected_auth_refund = if spec.is_enabled_in(SpecId::PRAGUE) { - eip7702::PER_EMPTY_ACCOUNT_COST - eip7702::PER_AUTH_BASE_COST + let expected_auth_refund = if spec.enables(SpecId::PRAGUE) { + u64::from(EIP7702_PER_EMPTY_ACCOUNT_COST - EIP7702_PER_AUTH_BASE_COST) } else { 0 }; assert_eq!( - params.tx_eip7702_auth_refund_regular(), + Version::base(spec) + .gas_params + .get(GasId::TxEip7702AuthRefund), expected_auth_refund, "spec={spec:?}: the full EIP-7702 per-auth refund must stay in the regular refund" ); diff --git a/crates/chainspec/src/spec.rs b/crates/chainspec/src/spec.rs index f8c7289a..a2329e6b 100644 --- a/crates/chainspec/src/spec.rs +++ b/crates/chainspec/src/spec.rs @@ -8,7 +8,6 @@ use crate::{ use alloy_chains::Chain; use alloy_consensus::Sealable; use alloy_eips::eip7840::BlobParams; -use alloy_evm::eth::spec::EthExecutorSpec; use alloy_genesis::Genesis; use alloy_primitives::{Address, B256, U256}; use morph_primitives::MorphHeader; @@ -421,12 +420,6 @@ impl EthereumHardforks for MorphChainSpec { } } -impl EthExecutorSpec for MorphChainSpec { - fn deposit_contract_address(&self) -> Option
{ - self.inner.deposit_contract_address() - } -} - impl MorphHardforks for MorphChainSpec { fn morph_fork_activation(&self, fork: MorphHardfork) -> ForkCondition { self.fork(fork) diff --git a/crates/consensus/Cargo.toml b/crates/consensus/Cargo.toml index 265da655..dfb20a82 100644 --- a/crates/consensus/Cargo.toml +++ b/crates/consensus/Cargo.toml @@ -19,12 +19,12 @@ morph-primitives = { workspace = true, features = ["serde-bincode-compat", "reth # Reth reth-consensus.workspace = true reth-consensus-common.workspace = true +reth-execution-types.workspace = true reth-primitives-traits.workspace = true # Alloy alloy-consensus.workspace = true alloy-eips.workspace = true -alloy-evm.workspace = true alloy-primitives.workspace = true alloy-rlp.workspace = true diff --git a/crates/evm/Cargo.toml b/crates/evm/Cargo.toml index 282f0989..7e79b1ec 100644 --- a/crates/evm/Cargo.toml +++ b/crates/evm/Cargo.toml @@ -19,19 +19,22 @@ morph-payload-types.workspace = true reth-chainspec.workspace = true reth-evm.workspace = true +reth-evm-ethereum.workspace = true reth-ethereum-primitives = { workspace = true, features = ["serde"] } -reth-revm.workspace = true +reth-execution-types.workspace = true reth-primitives-traits.workspace = true reth-rpc-eth-api = { workspace = true, optional = true } -alloy-evm.workspace = true +evm2 = { workspace = true, features = ["std"] } + alloy-consensus.workspace = true +alloy-eips.workspace = true +alloy-eip7928.workspace = true alloy-primitives.workspace = true alloy-rpc-types-eth.workspace = true derive_more.workspace = true thiserror.workspace = true -revm.workspace = true tracing.workspace = true [dev-dependencies] diff --git a/crates/payload/builder/Cargo.toml b/crates/payload/builder/Cargo.toml index bef78a23..a2d7d901 100644 --- a/crates/payload/builder/Cargo.toml +++ b/crates/payload/builder/Cargo.toml @@ -28,20 +28,19 @@ reth-payload-builder.workspace = true reth-payload-primitives.workspace = true reth-payload-util.workspace = true reth-primitives-traits.workspace = true -reth-revm.workspace = true reth-storage-api.workspace = true +reth-tasks.workspace = true reth-trie-parallel.workspace = true reth-transaction-pool.workspace = true +evm2 = { workspace = true, features = ["std"] } + # Alloy alloy-consensus.workspace = true alloy-eips.workspace = true alloy-primitives.workspace = true alloy-rlp.workspace = true -# Revm -revm.workspace = true - # Metrics metrics.workspace = true reth-metrics.workspace = true diff --git a/crates/proofs/Cargo.toml b/crates/proofs/Cargo.toml index ac5196ce..957ae957 100644 --- a/crates/proofs/Cargo.toml +++ b/crates/proofs/Cargo.toml @@ -26,12 +26,11 @@ tracing.workspace = true reth-codecs.workspace = true reth-db = { workspace = true, features = ["mdbx"] } -reth-evm.workspace = true +reth-evm = { workspace = true, features = ["witness"] } reth-execution-errors.workspace = true reth-metrics.workspace = true reth-primitives-traits.workspace = true reth-provider.workspace = true -reth-revm = { workspace = true, features = ["witness"] } reth-tasks.workspace = true reth-trie = { workspace = true, features = ["serde"] } reth-trie-common = { workspace = true, features = ["serde"] } diff --git a/crates/revm/Cargo.toml b/crates/revm/Cargo.toml index 968390c8..572eee7d 100644 --- a/crates/revm/Cargo.toml +++ b/crates/revm/Cargo.toml @@ -19,9 +19,8 @@ reth-ethereum-primitives = { workspace = true, features = ["std", "serde"] } reth-storage-api = { workspace = true, optional = true } reth-rpc-eth-types = { workspace = true, optional = true } -revm.workspace = true +evm2 = { workspace = true, features = ["std"] } -alloy-evm.workspace = true alloy-primitives.workspace = true alloy-consensus.workspace = true alloy-sol-types.workspace = true diff --git a/crates/rpc/Cargo.toml b/crates/rpc/Cargo.toml index 69e14a81..b729f42c 100644 --- a/crates/rpc/Cargo.toml +++ b/crates/rpc/Cargo.toml @@ -31,9 +31,8 @@ reth-rpc-eth-types.workspace = true reth-rpc-server-types.workspace = true reth-metrics.workspace = true metrics.workspace = true -reth-evm.workspace = true +reth-evm = { workspace = true, features = ["witness"] } reth-provider.workspace = true -reth-revm = { workspace = true, features = ["witness"] } reth-storage-api.workspace = true reth-tasks.workspace = true reth-errors.workspace = true @@ -42,7 +41,6 @@ reth-transaction-pool.workspace = true # Alloy alloy-consensus.workspace = true -alloy-evm.workspace = true alloy-primitives.workspace = true alloy-rpc-types-debug.workspace = true alloy-rpc-types-eth.workspace = true @@ -58,7 +56,7 @@ async-trait.workspace = true serde.workspace = true derive_more.workspace = true tokio.workspace = true -revm.workspace = true +evm2 = { workspace = true, features = ["std"] } # Error handling thiserror.workspace = true diff --git a/crates/txpool/Cargo.toml b/crates/txpool/Cargo.toml index ce50efe4..e164d3b6 100644 --- a/crates/txpool/Cargo.toml +++ b/crates/txpool/Cargo.toml @@ -23,14 +23,14 @@ reth-chainspec.workspace = true reth-evm.workspace = true reth-primitives-traits.workspace = true reth-provider.workspace = true -reth-revm.workspace = true reth-storage-api.workspace = true reth-transaction-pool.workspace = true +evm2 = { workspace = true, features = ["std"] } + # Alloy alloy-consensus.workspace = true alloy-eips.workspace = true -alloy-evm.workspace = true alloy-primitives.workspace = true # Misc From fdf297dec7c74f8fde5aa2645c73c9b9c94690a1 Mon Sep 17 00:00:00 2001 From: panos-xyz Date: Mon, 9 Nov 2026 20:53:29 +0800 Subject: [PATCH 02/16] chore: upgrade reth to v2.10.1 and migrate to evm2 reth replaced revm with evm2 in v2.9.0, so the Morph fee handler cannot be carried forward. Rewrite the Morph EVM on the evm2 transaction registry and port the workspace to the v2.10.1 APIs. EVM and block execution: - Rewrite the alt-token and L1 fee handling on evm2, and hide fee calls from tracers with FeeFrameFilter. - Keep EIP-7623 off and cap transaction gas at the block gas limit. - Accumulate block state and drive the state hook from the executor. - Return an error when a receipt cannot read the token registry. RPC: - Follow upstream on the proof history paths: absent accounts report zero codeHash and storageHash, and window errors use code 4444. - Convert requests to the recovered transaction environment. Proofs and tooling: - Define tables locally, replace storage wipes with zeroed slots and implement multiproof_v2. - Refuse `proofs init` while the state trie lags the canonical tip. - Require Rust 1.96 and allow the new git sources in deny.toml. Claude-Session: https://claude.ai/code/session_01UaJCgZJEQM11Ymk1kqg62A --- CONTRIBUTING.md | 2 +- Cargo.lock | 14 +- Cargo.toml | 3 + Dockerfile | 2 +- README.md | 6 +- bin/morph-reth/Cargo.toml | 1 + bin/morph-reth/src/proofs.rs | 21 +- bin/morph-statetest/Cargo.toml | 5 +- bin/morph-statetest/src/lib.rs | 1 + bin/morph-statetest/src/runner.rs | 253 +- bin/morph-statetest/src/schema.rs | 290 +- bin/morph-statetest/src/trace.rs | 98 + crates/consensus/src/validation.rs | 4 +- crates/evm/Cargo.toml | 3 +- crates/evm/src/assemble.rs | 18 +- crates/evm/src/block/factory.rs | 79 - crates/evm/src/block/mod.rs | 704 +++- crates/evm/src/block/receipt.rs | 398 +- crates/evm/src/config.rs | 133 +- crates/evm/src/engine.rs | 30 +- crates/evm/src/evm.rs | 333 +- crates/evm/src/lib.rs | 69 +- crates/node/Cargo.toml | 1 + crates/node/src/test_utils.rs | 2 +- crates/node/src/validator.rs | 68 +- crates/node/tests/it/proof_history.rs | 20 +- crates/node/tests/it/rpc.rs | 8 +- crates/node/tests/it/txpool.rs | 69 + crates/payload/builder/src/builder.rs | 186 +- crates/payload/builder/src/error.rs | 2 +- crates/proofs-exex/src/lib.rs | 6 +- crates/proofs-exex/src/sync_target.rs | 4 +- crates/proofs/src/api.rs | 3 - crates/proofs/src/batch_provider.rs | 159 +- crates/proofs/src/db/models/mod.rs | 76 +- crates/proofs/src/db/store.rs | 418 +- crates/proofs/src/in_memory.rs | 31 - crates/proofs/src/live.rs | 10 +- crates/proofs/src/proof.rs | 71 +- crates/proofs/src/provider.rs | 167 +- crates/reference-index/src/tables.rs | 64 +- crates/revm/Cargo.toml | 12 +- crates/revm/src/block.rs | 66 +- crates/revm/src/common.rs | 67 - crates/revm/src/error.rs | 111 +- crates/revm/src/evm.rs | 568 +-- crates/revm/src/exec.rs | 193 - crates/revm/src/handler.rs | 4435 +++++++++++----------- crates/revm/src/l1block.rs | 31 +- crates/revm/src/lib.rs | 33 +- crates/revm/src/precompiles.rs | 407 +- crates/revm/src/token_fee.rs | 248 +- crates/revm/src/tx.rs | 767 ++-- crates/rpc/Cargo.toml | 2 +- crates/rpc/src/error.rs | 25 +- crates/rpc/src/eth/call.rs | 49 +- crates/rpc/src/eth/mod.rs | 33 +- crates/rpc/src/eth/proofs.rs | 4 +- crates/rpc/src/eth/transaction.rs | 157 +- crates/rpc/src/execution_witness.rs | 42 +- crates/rpc/src/state.rs | 21 +- crates/txpool/src/maintain.rs | 9 +- crates/txpool/src/morph_tx_validation.rs | 9 +- crates/txpool/src/validator.rs | 15 +- deny.toml | 5 +- 65 files changed, 5374 insertions(+), 5767 deletions(-) create mode 100644 bin/morph-statetest/src/trace.rs delete mode 100644 crates/evm/src/block/factory.rs delete mode 100644 crates/revm/src/common.rs delete mode 100644 crates/revm/src/exec.rs diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 7b225cb1..806cd9f1 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -23,7 +23,7 @@ Thanks for your interest in contributing to Morph Reth! This document provides g ### Prerequisites -- Rust 1.95 or later +- Rust 1.96 or later - Cargo ### Build diff --git a/Cargo.lock b/Cargo.lock index 40986564..d0fc5b87 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5314,7 +5314,6 @@ version = "1.4.1" dependencies = [ "alloy-consensus", "alloy-eip7928", - "alloy-eips", "alloy-genesis", "alloy-primitives", "alloy-rpc-types-eth", @@ -5342,6 +5341,7 @@ name = "morph-node" version = "1.4.1" dependencies = [ "alloy-consensus", + "alloy-eip7928", "alloy-eips", "alloy-genesis", "alloy-hardforks", @@ -5584,6 +5584,7 @@ dependencies = [ "reth-node-builder", "reth-provider", "reth-rpc-server-types", + "reth-stages-types", "reth-tasks", "tracing", ] @@ -5595,17 +5596,13 @@ dependencies = [ "alloy-consensus", "alloy-eips", "alloy-primitives", - "alloy-sol-types", - "auto_impl", - "derive_more", "evm2", + "evm2-macros", "eyre", "morph-chainspec", "morph-primitives", - "reth-ethereum-primitives", "reth-evm", - "reth-rpc-eth-types", - "reth-storage-api", + "reth-evm-ethereum", "thiserror 2.0.21", "tracing", ] @@ -5663,8 +5660,11 @@ dependencies = [ name = "morph-statetest" version = "1.4.1" dependencies = [ + "alloy-consensus", + "alloy-eips", "alloy-primitives", "alloy-rlp", + "alloy-signer-local", "alloy-trie", "clap", "evm2", diff --git a/Cargo.toml b/Cargo.toml index ca14f86d..9fa1df08 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -153,6 +153,7 @@ reth-payload-util = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10. reth-primitives-traits = { version = "0.8.2", default-features = false } reth-prune-types = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } reth-provider = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } +reth-stages-types = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } reth-rpc = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } reth-rpc-api = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } reth-rpc-builder = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } @@ -177,6 +178,7 @@ reth-trie-sparse = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1 # `[patch]` below to the rev it actually builds against. evm2 = { git = "https://github.com/alloy-rs/evm2", rev = "592bf18c4e22fff54ac9b4db606c4ee276e345cb", default-features = false } evm2-inspectors = { git = "https://github.com/alloy-rs/evm2", rev = "592bf18c4e22fff54ac9b4db606c4ee276e345cb", default-features = false } +evm2-macros = { git = "https://github.com/alloy-rs/evm2", rev = "592bf18c4e22fff54ac9b4db606c4ee276e345cb" } alloy = { version = "2.5.0", default-features = false } alloy-consensus = { version = "2.5.0", default-features = false } @@ -261,6 +263,7 @@ pyroscope_pprofrs = "0.2.10" [patch."https://github.com/alloy-rs/evm2"] evm2 = { git = "https://www.github.com/alloy-rs/evm2", rev = "01df8f6a396d0250da286cb763faa6ec292d65b5" } evm2-inspectors = { git = "https://www.github.com/alloy-rs/evm2", rev = "01df8f6a396d0250da286cb763faa6ec292d65b5" } +evm2-macros = { git = "https://www.github.com/alloy-rs/evm2", rev = "01df8f6a396d0250da286cb763faa6ec292d65b5" } [patch.crates-io] reth-codecs = { git = "https://github.com/paradigmxyz/reth-core", rev = "275ce4cf5befeb9f1e8acd935ff2882d2d25fc61" } diff --git a/Dockerfile b/Dockerfile index 6f09bb8f..d761d45d 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -FROM lukemathwalker/cargo-chef:latest-rust-1.95-trixie AS chef +FROM lukemathwalker/cargo-chef:latest-rust-1.96-trixie AS chef WORKDIR /app # reth-mdbx-sys requires libclang for bindgen diff --git a/README.md b/README.md index 4022e27d..5ae5ec81 100644 --- a/README.md +++ b/README.md @@ -46,7 +46,7 @@ morph-reth/ ├── proofs/ # Versioned MPT history and proof state provider ├── proofs-exex/ # Forward accumulation, reorg, unwind, and pruning ├── reference-index/ # Independent transaction reference index - ├── revm/ # L1 fee calculation, token fee logic + ├── revm/ # Morph EVM on evm2: L1 fee and token fee handler ├── rpc/ # RPC implementation and type conversions └── txpool/ # Transaction pool with L1 fee validation ``` @@ -67,7 +67,7 @@ morph-reth/ | `morph-proofs` | Bounded, versioned MPT history in MDBX | | `morph-proofs-exex` | Forward-only proof-history execution extension | | `morph-reference-index` | Independent Morph transaction reference index | -| `morph-revm` | L1 fee and token fee calculations | +| `morph-revm` | Morph EVM on evm2: L1 fee and token fee transaction handler | | `morph-rpc` | RPC implementation and type conversions | | `morph-txpool` | Transaction pool with L1 fee and MorphTx validation | @@ -75,7 +75,7 @@ morph-reth/ ### Prerequisites -- Rust 1.95 or later +- Rust 1.96 or later - Cargo ### Building from Source diff --git a/bin/morph-reth/Cargo.toml b/bin/morph-reth/Cargo.toml index 63b04307..f2e74e48 100644 --- a/bin/morph-reth/Cargo.toml +++ b/bin/morph-reth/Cargo.toml @@ -32,6 +32,7 @@ reth-cli-util.workspace = true reth-ethereum-cli.workspace = true reth-node-builder.workspace = true reth-provider.workspace = true +reth-stages-types.workspace = true reth-rpc-server-types.workspace = true reth-tasks.workspace = true diff --git a/bin/morph-reth/src/proofs.rs b/bin/morph-reth/src/proofs.rs index 34ffd1bd..aeb8b061 100644 --- a/bin/morph-reth/src/proofs.rs +++ b/bin/morph-reth/src/proofs.rs @@ -15,8 +15,10 @@ use reth_cli_commands::common::{AccessRights, Environment, EnvironmentArgs}; use reth_cli_runner::CliRunner; use reth_ethereum_cli::ExtendedCommand; use reth_provider::{ - BlockNumReader, BlockReader, DBProvider, DatabaseProviderFactory, TransactionVariant, + BlockNumReader, BlockReader, DBProvider, DatabaseProviderFactory, StageCheckpointReader, + TransactionVariant, }; +use reth_stages_types::StageId; use tracing::info; /// Morph-specific top-level CLI commands. @@ -95,6 +97,23 @@ impl InitCommand { let provider = provider_factory .database_provider_ro()? .disable_long_read_transaction_safety(); + + // The job reads the hashed state tables directly and records them as the state of the + // canonical tip. After a crash those tables can lag behind `Finish`, so proceeding would + // anchor the history on the wrong state. The node repairs this on its next start. + if let Some(finish) = provider.get_stage_checkpoint(StageId::Finish)? + && let Some(partial_state_trie) = finish + .finish_stage_checkpoint() + .and_then(|checkpoint| checkpoint.partial_state_trie()) + && partial_state_trie < finish.block_number + { + eyre::bail!( + "state trie is at block {partial_state_trie}, behind the canonical tip {}; \ + start the node once to repair the database before initializing proof history", + finish.block_number + ); + } + let chain_info = provider.chain_info()?; info!( target: "morph::proofs", diff --git a/bin/morph-statetest/Cargo.toml b/bin/morph-statetest/Cargo.toml index e458b491..0a3377dd 100644 --- a/bin/morph-statetest/Cargo.toml +++ b/bin/morph-statetest/Cargo.toml @@ -7,8 +7,11 @@ license.workspace = true publish.workspace = true [dependencies] -alloy-primitives.workspace = true +alloy-consensus.workspace = true +alloy-eips = { workspace = true, features = ["serde"] } +alloy-primitives = { workspace = true, features = ["serde"] } alloy-rlp.workspace = true +alloy-signer-local.workspace = true alloy-trie.workspace = true clap.workspace = true eyre.workspace = true diff --git a/bin/morph-statetest/src/lib.rs b/bin/morph-statetest/src/lib.rs index 70860d97..c05023db 100644 --- a/bin/morph-statetest/src/lib.rs +++ b/bin/morph-statetest/src/lib.rs @@ -1,5 +1,6 @@ pub mod runner; pub mod schema; +mod trace; #[cfg(test)] mod tests { diff --git a/bin/morph-statetest/src/runner.rs b/bin/morph-statetest/src/runner.rs index 1fed0dc6..2d55f481 100644 --- a/bin/morph-statetest/src/runner.rs +++ b/bin/morph-statetest/src/runner.rs @@ -1,23 +1,23 @@ -use crate::schema::{MorphTestSuite, MorphTestUnit, SchemaError, parse_fork}; -use alloy_evm::{Evm, EvmEnv}; -use alloy_primitives::{B256, Bytes}; +use crate::{ + schema::{MorphTestSuite, MorphTestUnit, SchemaError, Test, parse_fork}, + trace::Eip3155Tracer, +}; +use alloy_consensus::transaction::Recovered; +use alloy_primitives::{Address, B256, Bytes, Log, U256, address, keccak256}; use alloy_trie::{HashBuilder, Nibbles, TrieAccount, root::storage_root_unhashed}; +use evm2::TxResult; use morph_chainspec::hardfork::MorphHardfork; -use morph_evm::{MorphBlockEnv, evm::MorphEvm}; -use revm::{ - context::{CfgEnv, result::ExecutionResult}, - database::{EmptyDB, PlainAccount, State}, - inspector::inspectors::TracerEip3155, - primitives::{Address, Log, U256, address, keccak256}, -}; -use revm_statetest_types::Test; +use morph_revm::{FeeFrameFilter, MorphEvm, MorphEvmTypes, morph_evm, morph_evm_env}; use serde::Serialize; -use std::{fs, io::stderr, path::Path}; +use std::{collections::BTreeSet, fs, io::stderr, path::Path}; use thiserror::Error; const MORPH_STATE_TEST_FEE_VAULT_ADDRESS: Address = address!("48442aa154897eef141df231cc1517fc8c1d170f"); +/// A transaction's outcome, or why it was rejected. +type ExecResult = Result, String>; + #[derive(Clone, Copy, Debug, Default)] pub struct RunnerOptions { pub trace: bool, @@ -102,105 +102,84 @@ fn execute_case( test: &Test, options: RunnerOptions, ) -> Result { - let cache = unit.state(); - let mut state = State::builder() - .with_cached_prestate(cache) - .with_bundle_update() - .build(); - let mut cfg = CfgEnv::::default() - .with_chain_id( - unit.env - .current_chain_id - .unwrap_or(U256::ONE) - .try_into() - .unwrap_or(1), - ) - .with_spec_and_mainnet_gas_params(fork); - cfg.disable_eip7623 = true; + let chain_id = unit + .env + .current_chain_id + .unwrap_or(U256::ONE) + .try_into() + .unwrap_or(1); - let mut block = unit.block_env(&mut cfg); + let mut block = unit.block_env(); if fork.is_curie() { block.beneficiary = MORPH_STATE_TEST_FEE_VAULT_ADDRESS; } - cfg.tx_gas_limit_cap = Some(block.gas_limit); + let block_gas_limit = block.gas_limit.saturating_to::(); + + let mut evm = morph_evm( + unit.state(), + morph_evm_env(fork, chain_id, block_gas_limit, block), + ); let tx = match unit.morph_tx_env(test, fork) { Ok(tx) => tx, Err(error) if test.expect_exception.is_some() => { - let exec_result: Result, String> = - Err(error.to_string()); return Ok(build_outcome( name, fork_name, + unit, test, - &exec_result, - &state, - unit.out.as_ref(), - &[], + &Err(error.to_string()), + &mut evm, )); } Err(error) => return Err(error.into()), }; - let env = EvmEnv { - cfg_env: cfg, - block_env: MorphBlockEnv { inner: block }, - }; + let tx = Recovered::new_unchecked(tx.env, tx.caller); - if options.trace { - let mut evm = MorphEvm::new(&mut state, env) - .with_inspector(TracerEip3155::buffered(stderr()).without_summary()); - evm.enable_inspector(); - let exec_result = evm.transact_commit(tx); - let receipt_logs = collect_receipt_logs(&mut evm, &exec_result); - return Ok(build_outcome( - name, - fork_name, - test, - &exec_result, - &state, - unit.out.as_ref(), - &receipt_logs, - )); - } + let exec_result: ExecResult = if options.trace { + let mut tracer = FeeFrameFilter::new(Eip3155Tracer::new(stderr())); + evm.transact_with_inspector(&tx, &mut tracer) + .map(|executed| executed.commit()) + .map_err(|error| error.to_string()) + } else { + evm.transact(&tx) + .map(|executed| executed.commit()) + .map_err(|error| error.to_string()) + }; - let mut evm = MorphEvm::new(&mut state, env); - let exec_result = evm.transact_commit(tx); - let receipt_logs = collect_receipt_logs(&mut evm, &exec_result); Ok(build_outcome( name, fork_name, + unit, test, &exec_result, - &state, - unit.out.as_ref(), - &receipt_logs, + &mut evm, )) } -fn build_outcome( +fn build_outcome( name: &str, fork_name: &str, + unit: &MorphTestUnit, test: &Test, - exec_result: &Result, E>, - db: &State, - expected_output: Option<&Bytes>, - receipt_logs: &[Log], -) -> Outcome -where - E: std::fmt::Display, -{ - let logs_root = log_rlp_hash(receipt_logs); - let state_root = state_merkle_trie_root(db.cache.trie_account()); - let error_msg = validation_error(test, exec_result, expected_output, state_root, logs_root); + exec_result: &ExecResult, + evm: &mut MorphEvm<'_>, +) -> Outcome { + let no_logs = Vec::new(); + let logs = exec_result.as_ref().map_or(&no_logs, |result| &result.logs); + let logs_root = log_rlp_hash(logs); + let state_root = state_merkle_trie_root(unit, evm); + let error_msg = validation_error(test, exec_result, unit.out.as_ref(), state_root, logs_root); let output = exec_result .as_ref() .ok() - .and_then(|result| result.output().cloned()) + .and_then(result_output) + .cloned() .unwrap_or_default(); let gas_used = exec_result .as_ref() .ok() - .map(ExecutionResult::tx_gas_used) + .map(|result| result.tx_gas_used()) .unwrap_or_default(); Outcome { @@ -220,32 +199,18 @@ where } } -fn collect_receipt_logs( - evm: &mut MorphEvm, - exec_result: &Result, E>, -) -> Vec -where - DB: alloy_evm::Database, - I: revm::Inspector>, -{ - let mut logs = evm.take_pre_fee_logs(); - if let Ok(result) = exec_result { - logs.extend(result.logs().iter().cloned()); - } - logs.extend(evm.take_post_fee_logs()); - logs +/// The output of a transaction that ran to a result; a halt has none. +fn result_output(result: &TxResult) -> Option<&Bytes> { + (!result.is_halt()).then_some(&result.output) } -fn validation_error( +fn validation_error( test: &Test, - exec_result: &Result, E>, + exec_result: &ExecResult, expected_output: Option<&Bytes>, state_root: B256, logs_root: B256, -) -> Option -where - E: std::fmt::Display, -{ +) -> Option { // `expectException` is checked for presence, deliberately not for its text. // go-ethereum's own statetest harness does the same -- `tests/state_test.go` // returns early on `len(ExpectException) > 0` under a standing @@ -267,11 +232,11 @@ where } if let (Some(expected), Ok(result)) = (expected_output, exec_result) - && result.output() != Some(expected) + && result_output(result) != Some(expected) { return Some(format!( "unexpected output: got {:?}, expected {expected:?}", - result.output() + result_output(result) )); } if logs_root != test.logs { @@ -289,17 +254,12 @@ where None } -fn format_evm_result( - exec_result: &Result, E>, -) -> String -where - E: std::fmt::Display, -{ +fn format_evm_result(exec_result: &ExecResult) -> String { match exec_result { - Ok(ExecutionResult::Success { reason, .. }) => format!("Success: {reason:?}"), - Ok(ExecutionResult::Revert { .. }) => "Revert".to_string(), - Ok(ExecutionResult::Halt { reason, .. }) => format!("Halt: {reason:?}"), - Err(error) => error.to_string(), + Ok(result) if result.is_success() => format!("Success: {:?}", result.stop), + Ok(result) if result.is_revert() => "Revert".to_string(), + Ok(result) => format!("Halt: {:?}", result.stop), + Err(error) => error.clone(), } } @@ -309,30 +269,63 @@ fn log_rlp_hash(logs: &[Log]) -> B256 { keccak256(&out) } -fn state_merkle_trie_root<'a>( - accounts: impl IntoIterator, -) -> B256 { - let mut accounts: Vec<_> = accounts - .into_iter() - .map(|(address, account)| { - let storage_root = storage_root_unhashed( - account - .storage - .iter() - .filter(|&(_, &value)| !value.is_zero()) - .map(|(key, value)| (B256::from(*key), *value)), - ); - ( - keccak256(address), - TrieAccount { - nonce: account.info.nonce, - balance: account.info.balance, - storage_root, - code_hash: account.info.code_hash, - }, - ) - }) +/// Computes the state root over the prestate accounts and everything execution accepted. +fn state_merkle_trie_root(unit: &MorphTestUnit, evm: &mut MorphEvm<'_>) -> B256 { + let cache = &evm.overlay_db().cache; + let addresses: BTreeSet
= unit + .pre + .keys() + .chain(cache.accounts.keys()) + .copied() .collect(); + let written_slots: Vec<(Address, Vec)> = cache + .storage + .iter() + .map(|(address, storage)| (*address, storage.slots.keys().copied().collect())) + .collect(); + + let state = evm.state_mut(); + let mut accounts = Vec::with_capacity(addresses.len()); + for address in addresses { + let info = state + .account_info_untracked(&address) + .expect("the in-memory database cannot fail"); + let Some(info) = info else { + continue; + }; + + let mut slots: BTreeSet = unit + .pre + .get(&address) + .map(|account| account.storage.keys().copied().collect()) + .unwrap_or_default(); + slots.extend( + written_slots + .iter() + .filter(|(written, _)| *written == address) + .flat_map(|(_, keys)| keys.iter().copied()), + ); + let storage: Vec<(B256, U256)> = slots + .into_iter() + .map(|key| { + let value = state + .storage_slot_untracked(&address, &key) + .expect("the in-memory database cannot fail"); + (B256::from(key), value) + }) + .filter(|(_, value)| !value.is_zero()) + .collect(); + + accounts.push(( + keccak256(address), + TrieAccount { + nonce: info.nonce, + balance: info.balance, + storage_root: storage_root_unhashed(storage), + code_hash: info.code_hash, + }, + )); + } accounts.sort_unstable_by_key(|(key, _)| *key); let mut trie = HashBuilder::default(); diff --git a/bin/morph-statetest/src/schema.rs b/bin/morph-statetest/src/schema.rs index ee9661a5..4033b995 100644 --- a/bin/morph-statetest/src/schema.rs +++ b/bin/morph-statetest/src/schema.rs @@ -1,23 +1,24 @@ +use alloy_eips::{eip2930::AccessList, eip7702::SignedAuthorization}; +use alloy_primitives::{Address, B256, Bytes, TxKind, U256}; +use alloy_signer_local::PrivateKeySigner; +use evm2::{ + bytecode::Bytecode, + ethereum::LazyAuthorization, + evm::{AccountInfo, InMemoryDB}, +}; use morph_chainspec::hardfork::MorphHardfork; use morph_primitives::transaction::morph_transaction::MORPH_TX_VERSION_2; -use morph_revm::{MorphTxEnv, MorphTxExt}; -use revm::{ - context::{BlockEnv, CfgEnv, TransactionType, TxEnv}, - context_interface::{ - block::BlobExcessGasAndPrice, - transaction::{AccessList, SignedAuthorization}, - }, - database::CacheState, - primitives::{Address, AddressMap, B256, Bytes, TxKind, U256, keccak256}, - state::Bytecode, -}; -use revm_statetest_types::{ - AccountInfo, Env, Test, TestAuthorization, deserialize_maybe_empty, recover_address, -}; +use morph_revm::{MorphBlockEnv, MorphTxEnv, MorphTxExt}; use serde::{Deserialize, Deserializer, de}; use std::collections::BTreeMap; use thiserror::Error; +const LEGACY_TX_TYPE: u8 = 0; +const EIP2930_TX_TYPE: u8 = 1; +const EIP1559_TX_TYPE: u8 = 2; +const EIP4844_TX_TYPE: u8 = 3; +const EIP7702_TX_TYPE: u8 = 4; + #[derive(Debug, Deserialize)] pub struct MorphTestSuite(pub BTreeMap); @@ -26,13 +27,118 @@ pub struct MorphTestUnit { #[serde(default, rename = "_info")] pub info: Option, pub env: Env, - pub pre: AddressMap, + pub pre: BTreeMap, pub post: BTreeMap>, pub transaction: MorphTransactionParts, #[serde(default)] pub out: Option, } +/// The block a fixture runs in. +#[derive(Debug, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct Env { + #[serde(rename = "currentChainID")] + pub current_chain_id: Option, + pub current_coinbase: Address, + #[serde(default)] + pub current_difficulty: U256, + pub current_gas_limit: U256, + pub current_number: U256, + pub current_timestamp: U256, + pub current_base_fee: Option, + pub previous_hash: Option, + pub current_random: Option, + pub current_beacon_root: Option, + pub current_withdrawals_root: Option, + pub current_excess_blob_gas: Option, + pub slot_number: Option, +} + +/// A prestate account. +#[derive(Clone, Debug, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct TestAccount { + pub balance: U256, + pub code: Bytes, + #[serde(deserialize_with = "deserialize_str_as_u64")] + pub nonce: u64, + pub storage: BTreeMap, +} + +/// Selects one data/gas/value combination of a fixture transaction. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)] +pub struct TxPartIndices { + pub data: usize, + pub gas: usize, + pub value: usize, +} + +/// The expected result of one fixture case. +#[derive(Debug, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Test { + pub expect_exception: Option, + pub indexes: TxPartIndices, + pub hash: B256, + pub logs: B256, + pub txbytes: Option, +} + +/// An EIP-7702 authorization as written in fixtures, which may repeat `yParity` as `v`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct TestAuthorization(SignedAuthorization); + +impl<'de> Deserialize<'de> for TestAuthorization { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + let mut value = serde_json::Value::deserialize(deserializer)?; + if let Some(object) = value.as_object_mut() + && object.contains_key("v") + && object.contains_key("yParity") + { + object.remove("v"); + } + serde_json::from_value(value) + .map(Self) + .map_err(de::Error::custom) + } +} + +/// A fixture transaction environment and the account sending it. +#[derive(Debug)] +pub struct FixtureTx { + pub env: MorphTxEnv, + pub caller: Address, +} + +fn deserialize_str_as_u64<'de, D>(deserializer: D) -> Result +where + D: Deserializer<'de>, +{ + let string = String::deserialize(deserializer)?; + if let Some(stripped) = string.strip_prefix("0x") { + u64::from_str_radix(stripped, 16) + } else { + string.parse() + } + .map_err(de::Error::custom) +} + +fn deserialize_maybe_empty<'de, D>(deserializer: D) -> Result, D::Error> +where + D: Deserializer<'de>, +{ + let string = String::deserialize(deserializer)?; + if string.is_empty() { + Ok(None) + } else { + string.parse().map_err(de::Error::custom).map(Some) + } +} + #[derive(Debug, Error)] pub enum SchemaError { #[error("unknown Morph hardfork: {0}")] @@ -97,71 +203,58 @@ pub struct MorphTransactionParts { } impl MorphTestUnit { - pub fn state(&self) -> CacheState { - let mut cache_state = CacheState::new(); - for (address, info) in &self.pre { - let code_hash = keccak256(&info.code); - let bytecode = Bytecode::new_raw_checked(info.code.clone()) - .unwrap_or_else(|_| Bytecode::new_legacy(info.code.clone())); - let account_info = revm::state::AccountInfo { - balance: info.balance, - code_hash, - code: Some(bytecode), - nonce: info.nonce, - account_id: None, - }; - cache_state.insert_account_with_storage(*address, account_info, info.storage.clone()); + /// Builds the database holding the prestate. + pub fn state(&self) -> InMemoryDB { + let mut db = InMemoryDB::default(); + for (address, account) in &self.pre { + let bytecode = Bytecode::new_raw_checked(account.code.clone()) + .unwrap_or_else(|_| Bytecode::new_legacy(account.code.clone())); + db.insert_account_info( + address, + AccountInfo::default() + .with_balance(account.balance) + .with_nonce(account.nonce) + .with_code(bytecode), + ); + for (key, value) in &account.storage { + db.insert_account_storage(address, key, value); + } } - cache_state + db } - pub fn block_env(&self, cfg: &mut CfgEnv) -> BlockEnv { - let mut block = BlockEnv { + /// Builds the block the fixture runs in. + /// + /// The blob base fee keeps its placeholder: BLOBBASEFEE is disabled on Morph and blob + /// transactions do not exist there, so nothing can observe it. + pub fn block_env(&self) -> MorphBlockEnv { + MorphBlockEnv { number: self.env.current_number, beneficiary: self.env.current_coinbase, timestamp: self.env.current_timestamp, - gas_limit: self.env.current_gas_limit.try_into().unwrap_or(u64::MAX), - basefee: self - .env - .current_base_fee - .unwrap_or_default() - .try_into() - .unwrap_or(u64::MAX), + gas_limit: U256::from(self.env.current_gas_limit.saturating_to::()), + basefee: U256::from( + self.env + .current_base_fee + .unwrap_or_default() + .saturating_to::(), + ), difficulty: self.env.current_difficulty, - prevrandao: self.env.current_random, - slot_num: self + prevrandao: self .env - .slot_number - .unwrap_or_default() - .try_into() - .unwrap_or(u64::MAX), - ..BlockEnv::default() - }; - - if let Some(excess_blob_gas) = self.env.current_excess_blob_gas { - block.set_blob_excess_gas_and_price( - excess_blob_gas.to(), - cfg.blob_base_fee_update_fraction(), - ); - } else { - block.blob_excess_gas_and_price = Some(BlobExcessGasAndPrice { - excess_blob_gas: 0, - blob_gasprice: 1, - }); + .current_random + .map(|random| U256::from_be_bytes(random.0)) + .unwrap_or_default(), + slot_num: self.env.slot_number.unwrap_or_default(), + ..Default::default() } - - if block.prevrandao.is_none() { - block.prevrandao = Some(B256::ZERO); - } - - block } pub fn morph_tx_env( &self, test: &Test, _fork: MorphHardfork, - ) -> Result { + ) -> Result { self.transaction.morph_tx_env( test.indexes.data, test.indexes.gas, @@ -182,28 +275,16 @@ impl MorphTransactionParts { chain_id: Option, txbytes: Option, has_base_fee: bool, - ) -> Result { + ) -> Result { let caller = match self.sender { Some(address) => address, - None => recover_address(self.secret_key.as_slice()) - .ok_or(SchemaError::UnknownPrivateKey(self.secret_key))?, - }; - // Preserve the raw tx-type byte when the JSON explicitly specifies - // it. Routing it through `revm::context::TransactionType` first - // would lossily map any non-standard byte (Morph's 0x7f, L1Msg's - // 0x7e, future fork types) to `Custom = 0xFF`, since revm's enum - // only knows the 5 vanilla Ethereum tx types. The cast-to-u8 of - // `Custom` then yields 0xFF, so `MorphTxExt::is_morph_tx` and - // `is_l1_msg` both return false and the morph fee handler / - // L1Message short-circuit never activate. Only fall through to - // the enum-based inference for txs that didn't carry a `type` - // field at all. - let tx_type = match self.tx_type { - Some(t) => t, - None => self - .tx_type(data_index) - .ok_or(SchemaError::InvalidTransactionType)? as u8, + None => PrivateKeySigner::from_slice(self.secret_key.as_slice()) + .map_err(|_| SchemaError::UnknownPrivateKey(self.secret_key))? + .address(), }; + let tx_type = self + .tx_type(data_index) + .ok_or(SchemaError::InvalidTransactionType)?; let gas_limit = self .gas_limit .get(gas_index) @@ -239,9 +320,7 @@ impl MorphTransactionParts { .map(|auth_list| { auth_list .into_iter() - .map(|auth| { - revm::context::either::Either::::Left(auth.into()) - }) + .map(|auth| LazyAuthorization::Signed(auth.0)) .collect() }) .unwrap_or_default(); @@ -257,16 +336,10 @@ impl MorphTransactionParts { .map(|fee| fee.try_into().unwrap_or(u128::MAX)) .or_else(|| has_base_fee.then_some(gas_price)); - let inner = TxEnv { - caller, + let mut tx = MorphTxEnv { + tx_type, gas_price, gas_priority_fee, - blob_hashes: self.blob_versioned_hashes.clone(), - max_fee_per_blob_gas: self - .max_fee_per_blob_gas - .map(|fee| fee.try_into().unwrap_or(u128::MAX)) - .unwrap_or(u128::MAX), - tx_type, gas_limit, data, nonce: u64::try_from(self.nonce).unwrap_or(u64::MAX), @@ -278,9 +351,9 @@ impl MorphTransactionParts { Some(address) => TxKind::Call(address), None => TxKind::Create, }, + ..Default::default() }; - let mut tx = MorphTxEnv::new(inner); if let Some(version) = self.version { tx = tx.with_version(version); } else if tx.is_morph_tx() && self.authorization_list.is_some() { @@ -306,7 +379,7 @@ impl MorphTransactionParts { } if let Some(txbytes) = txbytes { tx = tx.with_rlp_bytes(txbytes); - } else if !tx.blob_hashes.is_empty() { + } else if !self.blob_versioned_hashes.is_empty() { // morph-reth has no Eip4844 envelope variant — see // crates/primitives/src/transaction/envelope.rs. A blob tx // arriving here without post.txbytes cannot be encoded for @@ -327,32 +400,33 @@ impl MorphTransactionParts { tx = tx.with_rlp_bytes(rlp_bytes); } - Ok(tx) + Ok(FixtureTx { env: tx, caller }) } - fn tx_type(&self, access_list_index: usize) -> Option { + /// Returns the raw type byte the JSON specifies, or infers it from the fields present. + fn tx_type(&self, access_list_index: usize) -> Option { if let Some(tx_type) = self.tx_type { - return Some(TransactionType::from(tx_type)); + return Some(tx_type); } - let mut tx_type = TransactionType::Legacy; + let mut tx_type = LEGACY_TX_TYPE; if self .access_lists .get(access_list_index) .is_some_and(Option::is_some) { - tx_type = TransactionType::Eip2930; + tx_type = EIP2930_TX_TYPE; } if self.max_fee_per_gas.is_some() { - tx_type = TransactionType::Eip1559; + tx_type = EIP1559_TX_TYPE; } if self.max_fee_per_blob_gas.is_some() { self.to?; - return Some(TransactionType::Eip4844); + return Some(EIP4844_TX_TYPE); } if self.authorization_list.is_some() { self.to?; - return Some(TransactionType::Eip7702); + return Some(EIP7702_TX_TYPE); } Some(tx_type) } @@ -484,7 +558,8 @@ mod tests { let post = &unit.post["Jade"][0]; let tx = unit .morph_tx_env(post, MorphHardfork::Jade) - .expect("tx env should build"); + .expect("tx env should build") + .env; assert!( tx.rlp_bytes.as_ref().is_some_and(|bytes| !bytes.is_empty()), @@ -551,7 +626,8 @@ mod tests { let post = &unit.post["Celadon"][0]; let tx = unit .morph_tx_env(post, MorphHardfork::Celadon) - .expect("tx env should build"); + .expect("tx env should build") + .env; assert!(tx.is_morph_tx()); assert_eq!(tx.version, Some(MORPH_TX_VERSION_2)); diff --git a/bin/morph-statetest/src/trace.rs b/bin/morph-statetest/src/trace.rs new file mode 100644 index 00000000..eb3afa93 --- /dev/null +++ b/bin/morph-statetest/src/trace.rs @@ -0,0 +1,98 @@ +//! EIP-3155 execution tracer for debugging fixtures. +//! +//! Streams one JSON struct log per executed opcode, in the line format of `geth --json`. + +use evm2::{ + EvmTypesHost, Inspector, + interpreter::{Interpreter, Message, MessageResult, opcode::OpCode}, +}; +use serde_json::json; +use std::io::Write; + +use alloy_primitives::U256; + +/// Per-opcode state captured in `step`, emitted once its gas cost is known. +#[derive(Debug)] +struct PendingStep { + pc: usize, + op: u8, + gas: u64, + stack: Vec, + depth: u16, + mem_size: usize, + refund: i64, +} + +/// EIP-3155 struct-log tracer writing to `out`. +#[derive(Debug)] +pub(crate) struct Eip3155Tracer { + out: W, + pending: Option, +} + +impl Eip3155Tracer { + pub(crate) const fn new(out: W) -> Self { + Self { out, pending: None } + } + + /// Emits the pending step with the gas spent since it was captured. + /// + /// CALL- and CREATE-family opcodes never reach `step_end`: dispatch unwinds into the frame + /// machinery instead, so their step is flushed from the `call`/`create` hooks. + fn flush_pending(&mut self, interp: &mut Interpreter<'_, '_, T>) { + let Some(step) = self.pending.take() else { + return; + }; + let gas_cost = step.gas.saturating_sub(interp.gas().remaining()); + let line = json!({ + "pc": step.pc, + "op": step.op, + "gas": format!("{:#x}", step.gas), + "gasCost": format!("{gas_cost:#x}"), + "stack": step.stack, + "depth": u64::from(step.depth) + 1, + "returnData": "0x", + "refund": format!("{:#x}", step.refund.max(0)), + "memSize": step.mem_size, + "opName": OpCode::new_or_unknown(step.op).as_str(), + }); + // Diagnostic output only: a broken pipe must not abort execution. + let _ = writeln!(self.out, "{line}"); + } +} + +impl Inspector for Eip3155Tracer { + fn step(&mut self, interp: &mut Interpreter<'_, '_, T>) { + self.pending = Some(PendingStep { + pc: interp.pc(), + op: interp.opcode(), + gas: interp.gas().remaining(), + stack: interp.stack().as_slice().to_vec(), + depth: interp.message().depth, + mem_size: interp.memory().len(), + refund: interp.gas().refunded(), + }); + } + + fn step_end(&mut self, interp: &mut Interpreter<'_, '_, T>) { + self.flush_pending(interp); + } + + fn call( + &mut self, + interp: &mut Interpreter<'_, '_, T>, + _message: &mut Message, + ) -> Option> { + self.flush_pending(interp); + None + } + + fn create( + &mut self, + interp: &mut Interpreter<'_, '_, T>, + _message: &mut Message, + ) -> Option> { + self.flush_pending(interp); + None + } +} diff --git a/crates/consensus/src/validation.rs b/crates/consensus/src/validation.rs index 4033b47d..47f26886 100644 --- a/crates/consensus/src/validation.rs +++ b/crates/consensus/src/validation.rs @@ -39,7 +39,6 @@ use crate::MorphConsensusError; use alloy_consensus::{BlockHeader as _, EMPTY_OMMER_ROOT_HASH, TxReceipt}; use alloy_eips::eip2718::Encodable2718; -use alloy_evm::block::BlockExecutionResult; use alloy_primitives::{B256, Bloom}; use morph_chainspec::{ MINIMUM_GAS_LIMIT, MORPH_MAX_TX_PAYLOAD_BYTES_PER_BLOCK, MorphChainSpec, MorphHardforks, @@ -52,6 +51,7 @@ use reth_consensus::{Consensus, ConsensusError, FullConsensus, HeaderValidator, use reth_consensus_common::validation::{ validate_against_parent_hash_number, validate_body_against_header, }; +use reth_execution_types::BlockExecutionResult; use reth_primitives_traits::{ BlockBody as BlockBodyTrait, BlockHeader, GotExpected, RecoveredBlock, SealedBlock, SealedHeader, @@ -2372,7 +2372,7 @@ mod tests { U256::ZERO, )); - let result = alloy_evm::block::BlockExecutionResult { + let result = BlockExecutionResult { receipts: vec![receipt], requests: Default::default(), gas_used: 21000, diff --git a/crates/evm/Cargo.toml b/crates/evm/Cargo.toml index 7e79b1ec..d9853e6f 100644 --- a/crates/evm/Cargo.toml +++ b/crates/evm/Cargo.toml @@ -28,7 +28,6 @@ reth-rpc-eth-api = { workspace = true, optional = true } evm2 = { workspace = true, features = ["std"] } alloy-consensus.workspace = true -alloy-eips.workspace = true alloy-eip7928.workspace = true alloy-primitives.workspace = true alloy-rpc-types-eth.workspace = true @@ -47,4 +46,4 @@ default = [] serde-bincode-compat = [ "morph-primitives/serde-bincode-compat", ] -rpc = ["dep:reth-rpc-eth-api", "morph-revm/rpc"] +rpc = ["dep:reth-rpc-eth-api"] diff --git a/crates/evm/src/assemble.rs b/crates/evm/src/assemble.rs index afa775fe..21a95455 100644 --- a/crates/evm/src/assemble.rs +++ b/crates/evm/src/assemble.rs @@ -1,12 +1,11 @@ use crate::MorphEvmConfig; use alloy_consensus::{BlockBody, EMPTY_OMMER_ROOT_HASH, Header, TxReceipt, proofs}; -use alloy_evm::block::{BlockExecutionError, BlockExecutionResult}; use alloy_primitives::{Address, B64, logs_bloom}; use morph_chainspec::MorphChainSpec; use morph_primitives::{MorphHeader, receipt::calculate_receipt_root_no_memo}; use reth_chainspec::EthereumHardforks; -use reth_evm::execute::{BlockAssembler, BlockAssemblerInput}; -use revm::context::Block; +use reth_evm::{BlockAssembler, BlockAssemblerInput, BlockExecutionError, EvmEnv as _}; +use reth_execution_types::BlockExecutionResult; use std::sync::Arc; /// Assembler for Morph blocks. @@ -78,8 +77,9 @@ impl BlockAssembler for MorphBlockAssembler { .. } = input; - let timestamp = evm_env.block_env.timestamp(); - let block_number: u64 = evm_env.block_env.number().to(); + let block = evm_env.block_env(); + let timestamp = block.timestamp.to::(); + let block_number = block.number.to::(); // Calculate roots and bloom let transactions_root = proofs::calculate_transaction_root(&transactions); @@ -99,15 +99,15 @@ impl BlockAssembler for MorphBlockAssembler { receipts_root, withdrawals_root: None, logs_bloom, - timestamp: timestamp.to(), + timestamp, // Morph L2 keeps mix_hash fixed to zero, matching geth's L2 header shape. mix_hash: Default::default(), nonce: B64::ZERO, // Only include base_fee_per_gas after London (EIP-1559) - base_fee_per_gas: is_london_active.then_some(evm_env.block_env.basefee()), + base_fee_per_gas: is_london_active.then(|| block.basefee.to::()), number: block_number, - gas_limit: evm_env.block_env.gas_limit(), - difficulty: evm_env.block_env.difficulty(), + gas_limit: block.gas_limit.to(), + difficulty: block.difficulty, gas_used: *gas_used, extra_data: execution_ctx.extra_data, parent_beacon_block_root: None, diff --git a/crates/evm/src/block/factory.rs b/crates/evm/src/block/factory.rs deleted file mode 100644 index a1219465..00000000 --- a/crates/evm/src/block/factory.rs +++ /dev/null @@ -1,79 +0,0 @@ -//! Block executor factory for Morph. -//! -//! This module provides the [`MorphBlockExecutorFactory`] which creates block executors -//! that can execute Morph L2 blocks with proper L1 fee calculation and receipt building. - -use crate::{ - block::{DefaultMorphReceiptBuilder, MorphBlockExecutor, MorphTxResult}, - evm::MorphEvm, -}; -use alloy_evm::{ - block::{BlockExecutorFactory, StateDB}, - eth::EthBlockExecutionCtx, - revm::Inspector, -}; -use morph_chainspec::MorphChainSpec; -use morph_primitives::{MorphReceipt, MorphTxEnvelope}; -use morph_revm::evm::MorphContext; -use std::sync::Arc; - -use crate::evm::MorphEvmFactory; - -/// Block executor factory for Morph. -#[derive(Debug, Clone)] -pub(crate) struct MorphBlockExecutorFactory { - /// Receipt builder - receipt_builder: DefaultMorphReceiptBuilder, - /// Chain specification - spec: Arc, - /// EVM factory - evm_factory: MorphEvmFactory, -} - -impl MorphBlockExecutorFactory { - /// Creates a new [`MorphBlockExecutorFactory`]. - pub(crate) fn new(spec: Arc, evm_factory: MorphEvmFactory) -> Self { - Self { - receipt_builder: DefaultMorphReceiptBuilder, - spec, - evm_factory, - } - } - - /// Returns the chain spec. - pub(crate) const fn spec(&self) -> &Arc { - &self.spec - } - - /// Returns the EVM factory. - pub(crate) const fn evm_factory(&self) -> &MorphEvmFactory { - &self.evm_factory - } -} - -impl BlockExecutorFactory for MorphBlockExecutorFactory { - type EvmFactory = MorphEvmFactory; - type ExecutionCtx<'a> = EthBlockExecutionCtx<'a>; - type Transaction = MorphTxEnvelope; - type Receipt = MorphReceipt; - type TxExecutionResult = MorphTxResult; - // The Morph executor owns its EVM and receipt builder by value rather than - // borrowing them from the factory, so the lifetime parameter is unused. - type Executor<'a, DB: StateDB, I: Inspector>> = MorphBlockExecutor; - - fn evm_factory(&self) -> &Self::EvmFactory { - &self.evm_factory - } - - fn create_executor<'a, DB, I>( - &'a self, - evm: MorphEvm, - _ctx: Self::ExecutionCtx<'a>, - ) -> Self::Executor<'a, DB, I> - where - DB: StateDB, - I: Inspector>, - { - MorphBlockExecutor::new(evm, self.receipt_builder) - } -} diff --git a/crates/evm/src/block/mod.rs b/crates/evm/src/block/mod.rs index fbdecf02..2eba5d1b 100644 --- a/crates/evm/src/block/mod.rs +++ b/crates/evm/src/block/mod.rs @@ -2,60 +2,132 @@ //! //! This module provides block execution functionality for Morph, including: //! - [`MorphBlockExecutor`]: The main block executor -//! - [`MorphBlockExecutorFactory`]: Factory for creating block executors //! - [`MorphReceiptBuilder`]: Receipt construction for transactions -mod factory; mod receipt; -pub(crate) use factory::MorphBlockExecutorFactory; pub(crate) use receipt::{ DefaultMorphReceiptBuilder, MorphReceiptBuilder, MorphReceiptBuilderCtx, MorphReceiptTxFields, }; use crate::evm::MorphEvm; -use alloy_consensus::Transaction; -use alloy_consensus::transaction::TxHashRef; -use alloy_evm::{ - Database, Evm, RecoveredTx, - block::{ - BlockExecutionError, BlockExecutionResult, BlockExecutor, ExecutableTx, GasOutput, TxResult, - }, +use alloy_consensus::{Transaction, transaction::TxHashRef}; +use alloy_eip7928::{BlockAccessIndex, BlockAccessList}; +use alloy_primitives::{Address, B256}; +use evm2::{TxResultWithState, evm::Bal, registry::HandlerError}; +use morph_primitives::{MorphReceipt, MorphTxEnvelope, MorphTxType}; +use morph_revm::{ + L1_GAS_PRICE_ORACLE_ADDRESS, MorphEvmTypes, MorphInvalidTransaction, TokenFeeInfo, }; -use alloy_primitives::{Address, Log, U256}; -use morph_primitives::{MorphReceipt, MorphTxEnvelope}; -use morph_revm::{L1_GAS_PRICE_ORACLE_ADDRESS, MorphHaltReason, TokenFeeInfo, evm::MorphContext}; -use reth_primitives_traits::Recovered; -use reth_revm::{DatabaseCommit, Inspector, context::result::ResultAndState}; -use revm::context::Block; +use reth_evm::{ + BlockExecutionError, BlockExecutionOutput, BlockExecutor, BlockTransactionResult, + BlockValidationError, ExecutorTx, GasOutput, InternalBlockExecutionError, InvalidTxError, + RecoveredTx, execute::map_database_error, +}; +use reth_execution_types::{BlockExecutionResult, BlockState, StateUpdate}; +use std::{any::Any, sync::Arc}; + +/// A transaction validation failure reported by the Morph EVM. +#[derive(Debug, Clone, PartialEq, Eq)] +struct MorphInvalidTxError(HandlerError); + +impl core::fmt::Display for MorphInvalidTxError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + self.0.fmt(f) + } +} + +impl core::error::Error for MorphInvalidTxError {} + +impl InvalidTxError for MorphInvalidTxError { + fn is_nonce_too_low(&self) -> bool { + matches!(self.0, HandlerError::InvalidNonce { expected, got } if got < expected) + } + + fn is_gas_limit_too_high(&self) -> bool { + matches!( + self.0, + HandlerError::GasLimitMoreThanBlock { .. } + | HandlerError::TxGasLimitGreaterThanCap { .. } + ) + } + + fn is_gas_limit_too_low(&self) -> bool { + matches!(self.0, HandlerError::IntrinsicGasTooLow { .. }) + } + + /// Exposes the wrapped [`HandlerError`] so RPC layers can recover the structured error. + fn as_any(&self) -> &(dyn Any + 'static) { + &self.0 + } +} + +/// Maps a handler error for transaction `hash` onto reth's block execution errors. +/// +/// Rejections of the transaction, Morph's own included, are block validation errors. A failed +/// state read is not a verdict on the transaction, so it stays an internal error unless the +/// database classifies it as invalid input. +fn map_transaction_error(error: HandlerError, hash: B256) -> BlockExecutionError { + match error { + HandlerError::Database(ref database_error) if !database_error.is_fatal() => { + BlockValidationError::EVM { + hash, + error: Box::new(error), + } + .into() + } + HandlerError::Database(_) + | HandlerError::Fatal(_) + | HandlerError::WrongTransactionType { .. } => InternalBlockExecutionError::EVM { + hash, + error: Box::new(error), + } + .into(), + error => BlockValidationError::InvalidTx { + hash, + error: Box::new(MorphInvalidTxError(error)), + } + .into(), + } +} + +/// Returns the Morph error carried by a block execution error, if there is one. +pub fn morph_invalid_tx_error(error: &BlockExecutionError) -> Option<&MorphInvalidTransaction> { + let BlockExecutionError::Validation(BlockValidationError::InvalidTx { error, .. }) = error + else { + return None; + }; + error + .as_any() + .downcast_ref::()? + .external_ref::() +} + +/// The fields a receipt needs from the transaction itself. +#[derive(Debug, Clone)] +struct TxReceiptInput { + tx_type: MorphTxType, + is_l1_msg: bool, + gas_limit: u64, + sender: Address, + morph_tx_fields: Option, +} /// The result of executing a Morph transaction. /// -/// Carries the EVM result together with the recovered transaction and cached fee -/// information that are needed during [`MorphBlockExecutor::commit_transaction`]. +/// Carries the EVM result together with the transaction data needed to build its receipt +/// during [`MorphBlockExecutor::commit_transaction`]. +#[derive(Debug)] pub struct MorphTxResult { /// The raw EVM execution result and state diff. - pub result: ResultAndState, - /// Recovered transaction (consensus tx + signer). - pub recovered: Recovered, - /// L1 data fee read from the handler cache immediately after execution. - pub l1_fee: U256, - /// Token-fee deduction Transfer logs (survive main-tx revert). - pub pre_fee_logs: Vec, - /// Token-fee reimbursement Transfer logs (survive main-tx revert). - pub post_fee_logs: Vec, + result: TxResultWithState, + input: TxReceiptInput, } -impl TxResult for MorphTxResult { - type HaltReason = MorphHaltReason; - - fn result(&self) -> &ResultAndState { +impl BlockTransactionResult for MorphTxResult { + fn result(&self) -> &TxResultWithState { &self.result } - - fn into_result(self) -> ResultAndState { - self.result - } } /// Block executor for Morph L2 blocks. @@ -78,11 +150,12 @@ impl TxResult for MorphTxResult { /// ## Execution Flow /// 1. `apply_pre_execution_changes`: Set up state and load contracts /// 2. `execute_transaction_without_commit`: Execute transaction in EVM -/// 3. `commit_transaction`: Calculate fees, build receipt, commit state +/// 3. `commit_transaction`: Build the receipt, commit state /// 4. `finish`: Return final execution result with all receipts -pub struct MorphBlockExecutor { +#[expect(missing_debug_implementations)] +pub struct MorphBlockExecutor<'a> { /// The EVM used by executor (owned, not a reference) - evm: MorphEvm, + evm: MorphEvm<'a>, /// Receipt builder receipt_builder: DefaultMorphReceiptBuilder, /// Receipts of executed transactions @@ -94,25 +167,31 @@ pub struct MorphBlockExecutor { /// Unlike receipt gas, L1 messages reserve their full gas limit because Morph geth does not /// return their unused gas to the block gas pool. gas_pool_used: u64, + /// Accumulated state changes of the block. + block_state: BlockState, + state_update_hook: Option>, } -impl MorphBlockExecutor -where - DB: Database, - I: Inspector>, -{ +impl<'a> MorphBlockExecutor<'a> { /// Creates a new [`MorphBlockExecutor`]. /// /// # Arguments /// * `evm` - The EVM instance configured for Morph execution /// * `receipt_builder` - Builder for constructing transaction receipts - pub(crate) fn new(evm: MorphEvm, receipt_builder: DefaultMorphReceiptBuilder) -> Self { + /// * `tx_count_hint` - Expected number of transactions, when known + pub(crate) fn new( + evm: MorphEvm<'a>, + receipt_builder: DefaultMorphReceiptBuilder, + tx_count_hint: Option, + ) -> Self { Self { evm, receipt_builder, - receipts: Vec::new(), + receipts: Vec::with_capacity(tx_count_hint.unwrap_or_default()), gas_used: 0, gas_pool_used: 0, + block_state: BlockState::new(), + state_update_hook: None, } } @@ -121,10 +200,8 @@ where /// MorphTx transactions include: /// - Token fee information (when using ERC20 for gas payment) /// - Transaction metadata (version, reference, memo) - fn get_morph_tx_fields( - &mut self, + fn morph_tx_fields( tx: &MorphTxEnvelope, - sender: Address, ) -> Result, BlockExecutionError> { if !tx.is_morph_tx() { return Ok(None); @@ -137,54 +214,104 @@ where .fee_limit() .ok_or_else(|| BlockExecutionError::msg("MorphTx missing fee_limit"))?; - let version = tx.version().unwrap_or(0); - let reference = tx.reference(); - let memo = tx.memo().cloned(); - - if fee_token_id == 0 { - return Ok(Some(MorphReceiptTxFields { - version, - fee_token_id: 0, - fee_rate: None, - token_scale: None, - fee_limit, - reference, - memo, - })); + Ok(Some(MorphReceiptTxFields { + version: tx.version().unwrap_or(0), + fee_token_id, + fee_rate: None, + token_scale: None, + fee_limit, + reference: tx.reference(), + memo: tx.memo().cloned(), + })) + } + + /// Completes `fields` with the token's exchange rate. + /// + /// Reuses the registry data the handler charged the fee with. Execution that did not charge + /// a fee has none, so the rate comes straight from registry storage; only `price_ratio` and + /// `scale` are read, and no temporary EVM is built to resolve a balance this receipt has no + /// use for. + fn fill_token_fee_fields( + &mut self, + mut fields: MorphReceiptTxFields, + sender: Address, + charged: Option, + ) -> Result, BlockExecutionError> { + if fields.fee_token_id == 0 { + return Ok(Some(fields)); } - let token_info = match self.evm.cached_token_fee_info() { + let token_info = match charged { Some(info) => Some(info), - // Only `price_ratio` and `scale` are read below, and both come straight from - // registry storage. `load_storage_only` reads exactly that and never builds a - // temporary EVM to resolve a balance this receipt has no use for. - None => TokenFeeInfo::load_storage_only(self.evm.db_mut(), fee_token_id, sender) - .map_err(|e| { - BlockExecutionError::msg(format!("Failed to fetch token fee info: {e:?}")) - })?, + None => { + let state = self.evm.state_mut(); + TokenFeeInfo::load_storage_only_with( + |address, slot| state.storage_slot_untracked(&address, &slot), + fields.fee_token_id, + sender, + ) + .map_err(map_database_error)? + } }; - Ok(token_info.map(|info| MorphReceiptTxFields { - version, - fee_token_id, - fee_rate: Some(info.price_ratio), - token_scale: Some(info.scale), - fee_limit, - reference, - memo, + Ok(token_info.map(|info| { + fields.fee_rate = Some(info.price_ratio); + fields.token_scale = Some(info.scale); + fields })) } + + fn emit_state(hook: &mut Option>, update: StateUpdate) { + if !update.is_empty() + && let Some(hook) = hook + { + hook(update); + } + } } -impl BlockExecutor for MorphBlockExecutor -where - DB: Database + DatabaseCommit, - I: Inspector>, -{ +impl<'a> BlockExecutor for MorphBlockExecutor<'a> { type Transaction = MorphTxEnvelope; type Receipt = MorphReceipt; - type Evm = MorphEvm; - type Result = MorphTxResult; + type Evm = MorphEvm<'a>; + type TransactionResultWithState = MorphTxResult; + type BlockAccessList = Bal; + + fn evm(&self) -> &Self::Evm { + &self.evm + } + + fn evm_mut(&mut self) -> &mut Self::Evm { + &mut self.evm + } + + fn set_state_hook(&mut self, hook: impl FnMut(StateUpdate) + Send + 'static) -> bool { + self.state_update_hook = Some(Box::new(hook)); + true + } + + fn convert_block_access_list( + block_access_list: &BlockAccessList, + ) -> Result { + Bal::try_from(block_access_list.as_slice()).map_err(BlockExecutionError::other) + } + + fn set_block_access_list(&mut self, block_access_list: Arc) { + self.evm.state_mut().set_bal(block_access_list); + } + + fn set_block_access_index(&mut self, index: BlockAccessIndex) { + self.evm.state_mut().set_bal_index(index); + } + + fn enable_block_access_list_builder(&mut self) { + self.evm.state_mut().enable_bal_builder(); + self.evm.state_mut().reset_bal_index(); + } + + fn take_block_access_list(&mut self) -> Option { + self.evm.state_mut().take_bal_builder().map(Into::into) + } /// Applies pre-execution state changes before processing transactions. /// @@ -201,140 +328,375 @@ where // subsequent per-tx L1BlockInfo reads in the handler are fast. let _ = self .evm - .db_mut() - .basic(L1_GAS_PRICE_ORACLE_ADDRESS) - .map_err(BlockExecutionError::other)?; + .read_account_info(&L1_GAS_PRICE_ORACLE_ADDRESS) + .map_err(map_database_error)?; Ok(()) } - fn execute_transaction_without_commit( - &mut self, - tx: impl ExecutableTx, - ) -> Result { - let (tx_env, recovered) = tx.into_parts(); + fn into_state(self) -> reth_evm::BundleState { + self.block_state.into_bundle() + } + fn validate_transaction_gas_limit( + &mut self, + gas_limit: u64, + ) -> Result<(), BlockExecutionError> { // Validate gas limit against the geth-compatible block gas pool. Receipt gas cannot be - // used here: L1 messages report their actual execution cost in receipts but reserve their - // full gas limit for block packing. + // used here: L1 messages report their actual execution cost in receipts but reserve + // their full gas limit for block packing. let block_available_gas = self .evm .block() - .gas_limit() + .gas_limit + .saturating_to::() .saturating_sub(self.gas_pool_used); - if recovered.tx().gas_limit() > block_available_gas { - return Err(BlockExecutionError::msg(format!( - "transaction gas limit {} exceeds block available gas {}", - recovered.tx().gas_limit(), - block_available_gas - ))); + if gas_limit > block_available_gas { + return Err( + BlockValidationError::TransactionGasLimitMoreThanAvailableBlockGas { + transaction_gas_limit: gas_limit, + block_available_gas, + } + .into(), + ); } + Ok(()) + } - // Clone the consensus tx and signer BEFORE transact (since we can't move out later). - let consensus_tx = recovered.tx().clone(); - let signer = *recovered.signer(); + fn execute_transaction_without_commit( + &mut self, + transaction: impl ExecutorTx, + ) -> Result { + let (transaction, tx) = transaction.into_parts(); + self.validate_transaction_gas_limit(tx.tx().gas_limit())?; + + let input = TxReceiptInput { + tx_type: tx.tx().tx_type(), + is_l1_msg: tx.tx().is_l1_msg(), + gas_limit: tx.tx().gas_limit(), + sender: *tx.signer(), + morph_tx_fields: Self::morph_tx_fields(tx.tx())?, + }; - // Execute the transaction - let result = self - .evm - .transact(tx_env) - .map_err(|err| BlockExecutionError::evm(err, *consensus_tx.tx_hash()))?; + let result = morph_revm::MorphEvm::transact(&mut self.evm, &transaction) + .map(|executed| executed.detach()) + .map_err(|err| map_transaction_error(err, *tx.tx().tx_hash()))?; - // Read caches from the EVM immediately after execution, before the next tx resets them. - let l1_fee = self.evm.cached_l1_data_fee(); - let pre_fee_logs = self.evm.take_pre_fee_logs(); - let post_fee_logs = self.evm.take_post_fee_logs(); + Ok(MorphTxResult { result, input }) + } - Ok(MorphTxResult { + fn commit_transaction( + &mut self, + output: Self::TransactionResultWithState, + ) -> Result { + let MorphTxResult { result, input } = output; + let TxResultWithState { result, - recovered: Recovered::new_unchecked(consensus_tx, signer), - l1_fee, - pre_fee_logs, - post_fee_logs, - }) - } - - fn commit_transaction(&mut self, output: Self::Result) -> GasOutput { - let MorphTxResult { - result: ResultAndState { result, state }, - recovered, - l1_fee, - pre_fee_logs, - post_fee_logs, - } = output; - - // EIP-8037 separates regular and state gas; pre-Amsterdam morph treats - // them as a single number, so use the unified `tx_gas_used` getter. - let gas_used = result.gas().tx_gas_used(); + pending_state, + .. + } = result; + + let gas_used = result.tx_gas_used(); self.gas_used += gas_used; // Morph geth's L1-message path deducts the full transaction gas limit from GasPool and // deliberately skips the refund path. Regular transactions return unused gas, so their // net gas-pool charge is the actual gas used. - self.gas_pool_used += if recovered.tx().is_l1_msg() { - recovered.tx().gas_limit() + self.gas_pool_used += if input.is_l1_msg { + input.gas_limit } else { gas_used }; - // Get MorphTx-specific fields using the recovered transaction. Errors here - // are tracing-only — the trait API no longer permits us to surface errors - // from `commit_transaction`. - let (tx, signer) = recovered.into_parts(); - let morph_tx_fields = match self.get_morph_tx_fields(&tx, signer) { - Ok(fields) => fields, - Err(err) => { - tracing::error!( - target: "morph::evm", - %err, - "failed to load MorphTx receipt fields; emitting receipt without them" - ); - None + let morph_tx_fields = match input.morph_tx_fields { + Some(fields) => { + self.fill_token_fee_fields(fields, input.sender, result.ext.token_fee_info)? } + None => None, }; // Build receipt. - let ctx: MorphReceiptBuilderCtx<'_, Self::Evm> = MorphReceiptBuilderCtx { - tx: &tx, + let ctx = MorphReceiptBuilderCtx { + tx_type: input.tx_type, result, cumulative_gas_used: self.gas_used, - l1_fee, morph_tx_fields, - pre_fee_logs, - post_fee_logs, }; self.receipts.push(self.receipt_builder.build_receipt(ctx)); - // Commit state changes - self.evm.db_mut().commit(state); + // Commit state changes. + let mut update = self.state_update_hook.is_some().then(StateUpdate::default); + for changes in pending_state.account_changes() { + self.block_state + .commit_account_changes(changes, update.as_mut()); + } + if let Some(update) = update { + Self::emit_state(&mut self.state_update_hook, update); + } + // Reattach the finalized transaction so evm2 retains its account capacity and recycles + // storage maps for the next transaction instead of dropping the detached allocations. + self.evm.state_mut().set_pending_state(pending_state); + self.evm.state_mut().commit_transaction(); // Morph is pre-EIP-8037, so all gas is regular gas (no state-gas tracking). - GasOutput::new(gas_used) + Ok(GasOutput::new(gas_used, 0)) } - fn finish( + fn receipts(&self) -> &[Self::Receipt] { + &self.receipts + } + + fn finish_with_block_access_list( self, - ) -> Result<(Self::Evm, BlockExecutionResult), BlockExecutionError> { + ) -> Result<(BlockExecutionOutput, Option), BlockExecutionError> + { Ok(( - self.evm, - BlockExecutionResult { - receipts: self.receipts, - requests: Default::default(), - gas_used: self.gas_used, - blob_gas_used: 0, + BlockExecutionOutput::new( + BlockExecutionResult { + receipts: self.receipts, + requests: Default::default(), + gas_used: self.gas_used, + blob_gas_used: 0, + }, + self.block_state.into_bundle(), + ), + None, + )) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{MorphEvmConfig, evm::MorphEvmFactory}; + use alloy_consensus::{Sealed, Signed, TxLegacy}; + use alloy_primitives::{Bytes, Signature, TxKind, U256}; + use evm2::evm::{AccountInfo, InMemoryDB}; + use morph_chainspec::{MorphChainSpec, hardfork::MorphHardfork}; + use morph_primitives::TxL1Msg; + use morph_revm::{MorphBlockEnv, MorphTxEnv, morph_evm_env}; + use reth_evm::{BlockExecutorFactory, ExecutableTxParts}; + use reth_primitives_traits::Recovered; + + const SENDER: Address = Address::with_last_byte(0xaa); + const TARGET: Address = Address::with_last_byte(0xbb); + + fn chain_spec() -> Arc { + let genesis: alloy_genesis::Genesis = serde_json::from_value(serde_json::json!({ + "config": { + "chainId": 1337, + "homesteadBlock": 0, + "eip150Block": 0, + "eip155Block": 0, + "eip158Block": 0, + "byzantiumBlock": 0, + "constantinopleBlock": 0, + "petersburgBlock": 0, + "istanbulBlock": 0, + "berlinBlock": 0, + "londonBlock": 0, + "mergeNetsplitBlock": 0, + "terminalTotalDifficulty": 0, + "terminalTotalDifficultyPassed": true, + "shanghaiTime": 0, + "cancunTime": 0, + "bernoulliBlock": 0, + "curieBlock": 0, + "morph203Time": 0, + "viridianTime": 0, + "morph": {} }, + "alloc": {} + })) + .unwrap(); + Arc::new(MorphChainSpec::from(genesis)) + } + + fn config() -> MorphEvmConfig { + MorphEvmConfig::new(chain_spec(), MorphEvmFactory) + } + + /// A signed transaction ready for the executor. + fn executable( + tx: MorphTxEnvelope, + ) -> impl ExecutableTxParts, MorphTxEnvelope> { + reth_evm::WithTxEnv { + tx_env: Recovered::new_unchecked(MorphTxEnv::from_envelope(&tx), SENDER), + tx: Arc::new(Recovered::new_unchecked(tx, SENDER)), + } + } + + fn legacy_tx(nonce: u64, gas_limit: u64) -> MorphTxEnvelope { + MorphTxEnvelope::Legacy(Signed::new_unhashed( + TxLegacy { + chain_id: Some(1337), + nonce, + gas_price: 1, + gas_limit, + to: TxKind::Call(TARGET), + value: U256::ZERO, + input: Bytes::new(), + }, + Signature::test_signature(), )) } - fn evm_mut(&mut self) -> &mut Self::Evm { - &mut self.evm + fn l1_msg_tx(queue_index: u64, gas_limit: u64) -> MorphTxEnvelope { + MorphTxEnvelope::L1Msg(Sealed::new(TxL1Msg { + queue_index, + gas_limit, + to: TARGET, + value: U256::ZERO, + input: Bytes::default(), + sender: SENDER, + })) } - fn evm(&self) -> &Self::Evm { - &self.evm + fn funded_db() -> InMemoryDB { + let mut db = InMemoryDB::default(); + db.insert_account_info( + &SENDER, + AccountInfo::default().with_balance(U256::from(1_000_000_000u64)), + ); + db } - fn receipts(&self) -> &[Self::Receipt] { - &self.receipts + fn evm_with_gas_limit(db: InMemoryDB, gas_limit: u64) -> MorphEvm<'static> { + MorphEvm::new( + db, + morph_evm_env( + MorphHardfork::default(), + 1337, + gas_limit, + MorphBlockEnv { + gas_limit: U256::from(gas_limit), + ..Default::default() + }, + ), + ) + } + + /// An L1 message reserves its whole gas limit in the block gas pool even though its receipt + /// reports only the gas it used, so a later transaction cannot be packed into the rest. + #[test] + fn l1_message_reserves_its_gas_limit_in_the_block_gas_pool() { + let mut executor = MorphBlockExecutor::new( + evm_with_gas_limit(funded_db(), 100_000), + DefaultMorphReceiptBuilder, + None, + ); + + let gas = executor + .execute_transaction(executable(l1_msg_tx(0, 90_000))) + .unwrap(); + assert_eq!(gas.tx_gas_used(), 21_000); + + let error = executor + .execute_transaction(executable(legacy_tx(0, 21_000))) + .unwrap_err(); + assert!( + matches!( + error, + BlockExecutionError::Validation( + BlockValidationError::TransactionGasLimitMoreThanAvailableBlockGas { + transaction_gas_limit: 21_000, + block_available_gas: 10_000, + } + ) + ), + "{error:?}" + ); + } + + #[test] + fn regular_transactions_return_unused_gas_to_the_block_gas_pool() { + let mut executor = MorphBlockExecutor::new( + evm_with_gas_limit(funded_db(), 100_000), + DefaultMorphReceiptBuilder, + None, + ); + + executor + .execute_transaction(executable(legacy_tx(0, 90_000))) + .unwrap(); + executor + .execute_transaction(executable(legacy_tx(1, 21_000))) + .unwrap(); + + assert_eq!(executor.receipts().len(), 2); + let output = executor.finish().unwrap(); + assert_eq!(output.result.gas_used, 42_000); + } + + #[test] + fn invalid_transactions_are_block_validation_errors() { + let mut executor = MorphBlockExecutor::new( + evm_with_gas_limit(funded_db(), 100_000), + DefaultMorphReceiptBuilder, + None, + ); + + let error = executor + .execute_transaction(executable(legacy_tx(7, 21_000))) + .unwrap_err(); + + let BlockExecutionError::Validation(BlockValidationError::InvalidTx { error, .. }) = error + else { + panic!("expected an invalid transaction, got {error:?}"); + }; + assert!(!error.is_nonce_too_low(), "nonce 7 is too high"); + } + + #[test] + fn database_failures_are_not_transaction_verdicts() { + let hash = B256::repeat_byte(1); + let fatal = evm2::DatabaseError::new(std::io::Error::other("read failed"), true); + assert!(matches!( + map_transaction_error(HandlerError::Database(fatal), hash), + BlockExecutionError::Internal(InternalBlockExecutionError::EVM { .. }) + )); + + let invalid_input = evm2::DatabaseError::new(std::io::Error::other("bad input"), false); + assert!(matches!( + map_transaction_error(HandlerError::Database(invalid_input), hash), + BlockExecutionError::Validation(BlockValidationError::EVM { .. }) + )); + } + + #[test] + fn morph_rejections_can_be_read_back() { + let error = map_transaction_error( + MorphInvalidTransaction::TokenNotActive(3).into(), + B256::repeat_byte(1), + ); + assert_eq!( + morph_invalid_tx_error(&error), + Some(&MorphInvalidTransaction::TokenNotActive(3)) + ); + } + + #[test] + fn factory_creates_an_executor_for_a_block() { + let config = config(); + let evm = config.evm_with_env( + funded_db(), + morph_evm_env( + MorphHardfork::default(), + 1337, + 30_000_000, + MorphBlockEnv::default(), + ), + ); + let ctx = reth_evm_ethereum::EthBlockExecutionCtx { + tx_count_hint: Some(3), + parent_hash: B256::ZERO, + parent_beacon_block_root: None, + ommers: &[], + withdrawals: None, + extra_data: Bytes::new(), + slot_number: None, + }; + let executor = config.create_executor(evm, ctx); + assert!(executor.receipts().is_empty()); } } diff --git a/crates/evm/src/block/receipt.rs b/crates/evm/src/block/receipt.rs index 6a9d415b..4d47e60d 100644 --- a/crates/evm/src/block/receipt.rs +++ b/crates/evm/src/block/receipt.rs @@ -10,9 +10,8 @@ //! - **L1 Data Fee**: The cost charged for posting transaction data to L1 //! - **Token Fee Info**: For MorphTx (0x7F), includes exchange rate, fee limit, reference, and memo //! -//! The standard `EthBlockExecutor` doesn't have access to L1 fee information -//! during receipt building. This module provides a custom builder that receives -//! the pre-calculated L1 fee as part of its context. +//! The standard `EthBlockExecutor` builds receipts generically over the EVM type family, so it +//! cannot read Morph's result extension. This module provides a custom builder that does. //! //! # Receipt Types //! @@ -26,44 +25,33 @@ //! | MorphTx (0x7F) | inner + l1_fee + token_fee_info + reference + memo | use alloy_consensus::Receipt; -use alloy_consensus::transaction::TxHashRef; -use alloy_evm::Evm; -use alloy_primitives::{B256, Bytes, Log, U256}; -use morph_primitives::{MorphReceipt, MorphTransactionReceipt, MorphTxEnvelope, MorphTxType}; -use revm::context::result::ExecutionResult; +use alloy_primitives::{B256, Bytes, U256}; +use evm2::TxResult; +use morph_primitives::{MorphReceipt, MorphTransactionReceipt, MorphTxType}; +use morph_revm::MorphEvmTypes; use tracing::warn; /// Context for building a Morph receipt. /// /// This struct aggregates all information needed to construct a receipt for /// an executed transaction. It is populated by the block executor after -/// transaction execution and L1 fee calculation. +/// transaction execution. /// /// # Fields -/// - `tx`: The original transaction (needed for determining receipt type) -/// - `result`: EVM execution result (success/failure, logs, gas used) +/// - `tx_type`: The type of the executed transaction (selects the receipt variant) +/// - `result`: EVM execution result (status, logs, L1 data fee) /// - `cumulative_gas_used`: Running total of gas used in the block -/// - `l1_fee`: Pre-calculated L1 data fee for this transaction /// - `morph_tx_fields`: MorphTx-specific fields (token fee info, version, reference, memo) -/// - `pre_fee_logs`: Transfer event logs from token fee deduction (survives tx revert) -/// - `post_fee_logs`: Transfer event logs from token fee reimbursement #[derive(Debug)] -pub(crate) struct MorphReceiptBuilderCtx<'a, E: Evm> { - /// The executed transaction - pub tx: &'a MorphTxEnvelope, +pub(crate) struct MorphReceiptBuilderCtx { + /// The type of the executed transaction + pub tx_type: MorphTxType, /// Result of transaction execution - pub result: ExecutionResult, + pub result: TxResult, /// Cumulative gas used in the block up to and including this transaction pub cumulative_gas_used: u64, - /// L1 data fee for this transaction - pub l1_fee: U256, /// MorphTx-specific fields (token fee info, version, reference, memo) pub morph_tx_fields: Option, - /// Transfer event logs from token fee deduction (before main tx execution). - /// Managed separately from the handler pipeline to survive main tx revert. - pub pre_fee_logs: Vec, - /// Transfer event logs from token fee reimbursement (after main tx execution). - pub post_fee_logs: Vec, } /// MorphTx (0x7F) specific fields for receipts. @@ -121,7 +109,7 @@ pub(crate) trait MorphReceiptBuilder: Send + Sync { /// /// # Returns /// A [`MorphReceipt`] variant appropriate for the transaction type. - fn build_receipt(&self, ctx: MorphReceiptBuilderCtx<'_, E>) -> MorphReceipt; + fn build_receipt(&self, ctx: MorphReceiptBuilderCtx) -> MorphReceipt; } /// Default builder for [`MorphReceipt`]. @@ -148,41 +136,27 @@ pub(crate) trait MorphReceiptBuilder: Send + Sync { pub(crate) struct DefaultMorphReceiptBuilder; impl MorphReceiptBuilder for DefaultMorphReceiptBuilder { - fn build_receipt(&self, ctx: MorphReceiptBuilderCtx<'_, E>) -> MorphReceipt { + fn build_receipt(&self, ctx: MorphReceiptBuilderCtx) -> MorphReceipt { let MorphReceiptBuilderCtx { - tx, + tx_type, result, cumulative_gas_used, - l1_fee, morph_tx_fields, - pre_fee_logs, - post_fee_logs, } = ctx; + let l1_fee = result.ext.l1_data_fee; - // Assemble logs in chronological order matching go-ethereum: + // The EVM reports logs in chronological order, matching go-ethereum: // [deduct Transfer] + [main tx logs] + [refund Transfer] - // The fee logs cannot come from `result`. The call-mode deduction runs a - // mid-transaction `finalize()` that clears the journal's logs, so the handler - // moves them out first, and it drains the refund's logs the same way. `result` - // carries only the main frame's logs, which a revert has already discarded, - // while the fee logs survive it as they do in go-ethereum, whose `StateDB.logs` - // sit outside the snapshot/revert mechanism. - let is_success = result.is_success(); - let main_logs = result.into_logs(); - let mut logs = - Vec::with_capacity(pre_fee_logs.len() + main_logs.len() + post_fee_logs.len()); - logs.extend(pre_fee_logs); - logs.extend(main_logs); - logs.extend(post_fee_logs); - + // A reverted main frame drops only its own logs: the fee logs were emitted outside + // its checkpoint, as they sit outside go-ethereum's snapshot/revert mechanism. let inner = Receipt { - status: is_success.into(), + status: result.status.into(), cumulative_gas_used, - logs, + logs: result.logs, }; // Create the appropriate receipt variant based on transaction type - match tx.tx_type() { + match tx_type { MorphTxType::Legacy => { MorphReceipt::Legacy(MorphTransactionReceipt::with_l1_fee(inner, l1_fee)) } @@ -223,7 +197,6 @@ impl MorphReceiptBuilder for DefaultMorphReceiptBuilder { } else { warn!( target: "morph::evm", - tx_hash = ?tx.tx_hash(), "MorphTx missing token fee fields - receipt will not include fee token info. \ This may indicate an unregistered/inactive token or a bug." ); @@ -237,133 +210,48 @@ impl MorphReceiptBuilder for DefaultMorphReceiptBuilder { #[cfg(test)] mod tests { use super::*; - use alloy_consensus::{Signed, TxLegacy, TxReceipt}; - use alloy_primitives::{Address, Log, Signature, TxKind}; - use morph_primitives::transaction::TxL1Msg; - use revm::context::result::ExecutionResult; - - // We use NoOpInspector-based MorphEvm for the generic E parameter. - // Since build_receipt only uses E::HaltReason, we can use any concrete Evm type. - type TestEvm = crate::evm::MorphEvm; - - // revm v38 reshaped `ResultGas`: the previous 5-arg constructor is gone, - // and the new 3-arg `new(total_gas_spent, refunded, floor_gas)` is itself - // deprecated in favor of `with_*` builders. Our receipt-builder tests only - // observe `gas_used()` (`= total_gas_spent`), so set just that field via - // the non-deprecated builder. State gas (EIP-8037) and refunds aren't - // exercised pre-Amsterdam. - fn result_gas(gas_used: u64) -> revm::context::result::ResultGas { - revm::context::result::ResultGas::default().with_total_gas_spent(gas_used) - } + use alloy_consensus::TxReceipt; + use alloy_primitives::{Address, Log}; + use evm2::{TxResultExt, interpreter::InstrStop}; + use morph_revm::MorphTxResultExt; - fn make_success_result(gas_used: u64) -> ExecutionResult { - ExecutionResult::Success { - reason: revm::context::result::SuccessReason::Stop, - gas: result_gas(gas_used), - logs: vec![], - output: revm::context::result::Output::Call(alloy_primitives::Bytes::new()), - } - } - - fn make_success_with_logs( + fn make_result( + status: bool, gas_used: u64, logs: Vec, - ) -> ExecutionResult { - ExecutionResult::Success { - reason: revm::context::result::SuccessReason::Stop, - gas: result_gas(gas_used), + l1_fee: U256, + ) -> TxResult { + TxResultExt { + status, + total_gas_spent: gas_used, + stop: if status { + InstrStop::Stop + } else { + InstrStop::Revert + }, logs, - output: revm::context::result::Output::Call(alloy_primitives::Bytes::new()), - } - } - - fn make_revert_result(gas_used: u64) -> ExecutionResult { - ExecutionResult::Revert { - gas: result_gas(gas_used), - logs: vec![], - output: alloy_primitives::Bytes::new(), + ext: MorphTxResultExt { + l1_data_fee: l1_fee, + token_fee_info: None, + }, + ..Default::default() } } - fn create_legacy_tx() -> MorphTxEnvelope { - let tx = TxLegacy { - chain_id: Some(1337), - nonce: 0, - gas_price: 1_000_000_000, - gas_limit: 21000, - to: TxKind::Call(Address::repeat_byte(0x01)), - value: U256::ZERO, - input: alloy_primitives::Bytes::new(), - }; - MorphTxEnvelope::Legacy(Signed::new_unhashed(tx, Signature::test_signature())) - } - - fn create_eip1559_tx() -> MorphTxEnvelope { - use alloy_consensus::TxEip1559; - let tx = TxEip1559 { - chain_id: 1337, - nonce: 0, - gas_limit: 21000, - max_fee_per_gas: 2_000_000_000, - max_priority_fee_per_gas: 1_000_000_000, - to: TxKind::Call(Address::repeat_byte(0x02)), - value: U256::ZERO, - input: alloy_primitives::Bytes::new(), - access_list: Default::default(), - }; - MorphTxEnvelope::Eip1559(Signed::new_unhashed(tx, Signature::test_signature())) - } - - fn create_l1_msg_tx() -> MorphTxEnvelope { - use alloy_consensus::Sealed; - let tx = TxL1Msg { - queue_index: 0, - gas_limit: 21000, - to: Address::ZERO, - value: U256::ZERO, - input: alloy_primitives::Bytes::default(), - sender: Address::ZERO, - }; - MorphTxEnvelope::L1Msg(Sealed::new(tx)) - } - - fn create_morph_tx() -> MorphTxEnvelope { - use morph_primitives::TxMorph; - use morph_primitives::transaction::morph_transaction::MORPH_TX_VERSION_0; - let tx = TxMorph { - chain_id: 1337, - nonce: 0, - gas_limit: 21000, - max_fee_per_gas: 2_000_000_000, - max_priority_fee_per_gas: 1_000_000_000, - to: TxKind::Call(Address::repeat_byte(0x03)), - value: U256::ZERO, - access_list: Default::default(), - version: MORPH_TX_VERSION_0, - fee_token_id: 1, - fee_limit: U256::from(1000u64), - reference: None, - memo: None, - authorization_list: Vec::new(), - input: alloy_primitives::Bytes::new(), - }; - MorphTxEnvelope::Morph(Signed::new_unhashed(tx, Signature::test_signature())) + fn make_success_result(gas_used: u64, l1_fee: U256) -> TxResult { + make_result(true, gas_used, vec![], l1_fee) } #[test] fn test_build_legacy_receipt() { let builder = DefaultMorphReceiptBuilder; - let tx = create_legacy_tx(); let l1_fee = U256::from(5000u64); - let ctx = MorphReceiptBuilderCtx:: { - tx: &tx, - result: make_success_result(21000), + let ctx = MorphReceiptBuilderCtx { + tx_type: MorphTxType::Legacy, + result: make_success_result(21000, l1_fee), cumulative_gas_used: 21000, - l1_fee, morph_tx_fields: None, - pre_fee_logs: vec![], - post_fee_logs: vec![], }; let receipt = builder.build_receipt(ctx); @@ -376,17 +264,13 @@ mod tests { #[test] fn test_build_eip1559_receipt() { let builder = DefaultMorphReceiptBuilder; - let tx = create_eip1559_tx(); let l1_fee = U256::from(8000u64); - let ctx = MorphReceiptBuilderCtx:: { - tx: &tx, - result: make_success_result(21000), + let ctx = MorphReceiptBuilderCtx { + tx_type: MorphTxType::Eip1559, + result: make_success_result(21000, l1_fee), cumulative_gas_used: 42000, - l1_fee, morph_tx_fields: None, - pre_fee_logs: vec![], - post_fee_logs: vec![], }; let receipt = builder.build_receipt(ctx); @@ -398,18 +282,14 @@ mod tests { #[test] fn test_build_l1_msg_receipt_no_l1_fee() { let builder = DefaultMorphReceiptBuilder; - let tx = create_l1_msg_tx(); - let ctx = MorphReceiptBuilderCtx:: { - tx: &tx, - result: make_success_result(21000), - cumulative_gas_used: 21000, + let ctx = MorphReceiptBuilderCtx { + tx_type: MorphTxType::L1Msg, // Pass a non-zero l1_fee to verify the builder ignores it for L1 messages. // L1 message gas is prepaid on L1, so no L1 fee should appear in the receipt. - l1_fee: U256::from(999_999), + result: make_success_result(21000, U256::from(999_999)), + cumulative_gas_used: 21000, morph_tx_fields: None, - pre_fee_logs: vec![], - post_fee_logs: vec![], }; let receipt = builder.build_receipt(ctx); @@ -421,7 +301,6 @@ mod tests { #[test] fn test_build_morph_tx_receipt_with_fields() { let builder = DefaultMorphReceiptBuilder; - let tx = create_morph_tx(); let l1_fee = U256::from(3000u64); let fields = MorphReceiptTxFields { @@ -434,14 +313,11 @@ mod tests { memo: None, }; - let ctx = MorphReceiptBuilderCtx:: { - tx: &tx, - result: make_success_result(21000), + let ctx = MorphReceiptBuilderCtx { + tx_type: MorphTxType::Morph, + result: make_success_result(21000, l1_fee), cumulative_gas_used: 21000, - l1_fee, morph_tx_fields: Some(fields), - pre_fee_logs: vec![], - post_fee_logs: vec![], }; let receipt = builder.build_receipt(ctx); @@ -466,18 +342,14 @@ mod tests { #[test] fn test_build_morph_tx_receipt_without_fields_fallback() { let builder = DefaultMorphReceiptBuilder; - let tx = create_morph_tx(); let l1_fee = U256::from(3000u64); // Missing morph_tx_fields => should fallback to with_l1_fee - let ctx = MorphReceiptBuilderCtx:: { - tx: &tx, - result: make_success_result(21000), + let ctx = MorphReceiptBuilderCtx { + tx_type: MorphTxType::Morph, + result: make_success_result(21000, l1_fee), cumulative_gas_used: 21000, - l1_fee, morph_tx_fields: None, - pre_fee_logs: vec![], - post_fee_logs: vec![], }; let receipt = builder.build_receipt(ctx); @@ -501,16 +373,12 @@ mod tests { #[test] fn test_build_receipt_reverted_tx() { let builder = DefaultMorphReceiptBuilder; - let tx = create_legacy_tx(); - let ctx = MorphReceiptBuilderCtx:: { - tx: &tx, - result: make_revert_result(15000), + let ctx = MorphReceiptBuilderCtx { + tx_type: MorphTxType::Legacy, + result: make_result(false, 15000, vec![], U256::from(100u64)), cumulative_gas_used: 15000, - l1_fee: U256::from(100u64), morph_tx_fields: None, - pre_fee_logs: vec![], - post_fee_logs: vec![], }; let receipt = builder.build_receipt(ctx); @@ -523,7 +391,6 @@ mod tests { #[test] fn test_build_receipt_with_logs() { let builder = DefaultMorphReceiptBuilder; - let tx = create_legacy_tx(); let log = Log::new( Address::repeat_byte(0x01), vec![B256::repeat_byte(0x02)], @@ -531,145 +398,32 @@ mod tests { ) .unwrap(); - let ctx = MorphReceiptBuilderCtx:: { - tx: &tx, - result: make_success_with_logs(21000, vec![log]), + let ctx = MorphReceiptBuilderCtx { + tx_type: MorphTxType::Legacy, + result: make_result(true, 21000, vec![log], U256::ZERO), cumulative_gas_used: 21000, - l1_fee: U256::ZERO, morph_tx_fields: None, - pre_fee_logs: vec![], - post_fee_logs: vec![], }; let receipt = builder.build_receipt(ctx); assert_eq!(TxReceipt::logs(&receipt).len(), 1); } - fn make_fee_log(marker: u8) -> Log { - Log::new( - Address::repeat_byte(marker), - vec![B256::repeat_byte(marker)], - alloy_primitives::Bytes::new(), - ) - .unwrap() - } - - /// Fee Transfer logs (pre/post) survive when the main transaction reverts. - /// - /// go-ethereum's StateDB.logs is independent of snapshot/revert — fee logs - /// are always included. revm's ExecutionResult::Revert carries no logs field, - /// so morph-reth caches fee logs in pre_fee_logs/post_fee_logs and merges - /// them unconditionally in the receipt builder. - #[test] - fn test_fee_logs_survive_main_tx_revert() { - let builder = DefaultMorphReceiptBuilder; - let tx = create_legacy_tx(); - - let pre_log = make_fee_log(0xAA); // fee deduction Transfer - let post_log = make_fee_log(0xBB); // fee refund Transfer - - let ctx = MorphReceiptBuilderCtx:: { - tx: &tx, - result: make_revert_result(20_000), - cumulative_gas_used: 20_000, - l1_fee: U256::ZERO, - morph_tx_fields: None, - pre_fee_logs: vec![pre_log.clone()], - post_fee_logs: vec![post_log.clone()], - }; - - let receipt = builder.build_receipt(ctx); - - assert!( - !TxReceipt::status(&receipt), - "reverted tx must have status=false" - ); - - let logs = TxReceipt::logs(&receipt); - // Main tx logs are absent (revert), but fee logs must still be present. - assert_eq!( - logs.len(), - 2, - "pre_fee_log + post_fee_log must appear despite revert" - ); - assert_eq!( - logs[0].address, pre_log.address, - "first log must be pre_fee_log" - ); - assert_eq!( - logs[1].address, post_log.address, - "second log must be post_fee_log" - ); - } - - /// Log ordering on successful tx: [pre_fee_log, main_tx_log, post_fee_log]. - /// - /// Matches go-ethereum's receipt log ordering where fee deduction comes - /// first (before main tx), and fee refund comes last (after main tx). - #[test] - fn test_fee_log_ordering_on_success() { - let builder = DefaultMorphReceiptBuilder; - let tx = create_legacy_tx(); - - let pre_log = make_fee_log(0xAA); - let main_log = make_fee_log(0xCC); - let post_log = make_fee_log(0xBB); - - let ctx = MorphReceiptBuilderCtx:: { - tx: &tx, - result: make_success_with_logs(21_000, vec![main_log.clone()]), - cumulative_gas_used: 21_000, - l1_fee: U256::ZERO, - morph_tx_fields: None, - pre_fee_logs: vec![pre_log.clone()], - post_fee_logs: vec![post_log.clone()], - }; - - let receipt = builder.build_receipt(ctx); - assert!(TxReceipt::status(&receipt)); - - let logs = TxReceipt::logs(&receipt); - assert_eq!(logs.len(), 3, "pre_fee + main + post_fee = 3 logs"); - assert_eq!( - logs[0].address, pre_log.address, - "pre_fee_log must be first" - ); - assert_eq!( - logs[1].address, main_log.address, - "main_tx_log must be second" - ); - assert_eq!( - logs[2].address, post_log.address, - "post_fee_log must be last" - ); - } - - /// Fee logs without refund: only pre_fee_log when no gas is refunded. - /// - /// If all gas is consumed exactly (no unused gas), the post_fee_log - /// may be empty. But the pre_fee_log must always appear. + /// A reverted token-fee transaction still reports the fee transfers the EVM kept. #[test] - fn test_pre_fee_log_only_no_post_fee() { + fn test_build_receipt_keeps_logs_of_a_failed_transaction() { let builder = DefaultMorphReceiptBuilder; - let tx = create_legacy_tx(); - - let pre_log = make_fee_log(0xAA); + let log = Log::new(Address::repeat_byte(0x01), vec![], Bytes::new()).unwrap(); - let ctx = MorphReceiptBuilderCtx:: { - tx: &tx, - result: make_revert_result(21_000), - cumulative_gas_used: 21_000, - l1_fee: U256::ZERO, + let ctx = MorphReceiptBuilderCtx { + tx_type: MorphTxType::Morph, + result: make_result(false, 15000, vec![log.clone(), log], U256::ZERO), + cumulative_gas_used: 15000, morph_tx_fields: None, - pre_fee_logs: vec![pre_log.clone()], - post_fee_logs: vec![], // no refund }; let receipt = builder.build_receipt(ctx); assert!(!TxReceipt::status(&receipt)); - - let logs = TxReceipt::logs(&receipt); - assert_eq!(logs.len(), 1, "only pre_fee_log when there is no refund"); - assert_eq!(logs[0].address, pre_log.address); + assert_eq!(TxReceipt::logs(&receipt).len(), 2); } } diff --git a/crates/evm/src/config.rs b/crates/evm/src/config.rs index 5eaf28fd..a19b096d 100644 --- a/crates/evm/src/config.rs +++ b/crates/evm/src/config.rs @@ -1,16 +1,14 @@ use crate::{MorphBlockAssembler, MorphEvmConfig, MorphEvmError, MorphNextBlockEnvAttributes}; use alloy_consensus::BlockHeader; -use alloy_primitives::B256; -use morph_chainspec::hardfork::{MorphHardfork, MorphHardforks}; +use alloy_primitives::{B256, U256}; +use morph_chainspec::hardfork::MorphHardforks; use morph_primitives::Block; use morph_primitives::{MorphHeader, MorphPrimitives}; -use morph_revm::MorphBlockEnv; +use morph_revm::{MorphBlockEnv, morph_evm_env}; use reth_chainspec::EthChainSpec; -use reth_evm::{ConfigureEvm, EvmEnv, EvmEnvFor, eth::EthBlockExecutionCtx}; +use reth_evm::{ConfigureEvm, EvmEnvFor, ExecutionCtxFor}; +use reth_evm_ethereum::EthBlockExecutionCtx; use reth_primitives_traits::{SealedBlock, SealedHeader}; -use revm::context::{BlockEnv, CfgEnv}; -use revm::context_interface::block::BlobExcessGasAndPrice; -use revm::primitives::U256; use std::borrow::Cow; impl ConfigureEvm for MorphEvmConfig { @@ -33,45 +31,34 @@ impl ConfigureEvm for MorphEvmConfig { .chain_spec() .morph_hardfork_at(header.number(), header.timestamp()); - let mut cfg_env = CfgEnv::::default() - .with_chain_id(self.chain_spec().chain().id()) - .with_spec_and_mainnet_gas_params(spec); - cfg_env.disable_eip7623 = true; - // Morph does not enforce EIP-7825 transaction gas limit cap. Historical mainnet - // transactions (e.g. block 20459477, gas_limit=21,165,068) exceed the EIP-7825 - // cap of 2^24 (16,777,216). Cap at block gas limit instead so all valid - // transactions can execute regardless of which SpecId is active. - cfg_env.tx_gas_limit_cap = Some(header.gas_limit()); - let fee_recipient = self .chain_spec() .fee_vault_address() .unwrap_or_else(|| header.beneficiary()); - // Morph doesn't support EIP-4844 blob transactions, but when SpecId >= CANCUN, - // revm requires `blob_excess_gas_and_price` to be set. We provide a placeholder - // value (excess_blob_gas = 0, blob_gasprice = 1) to satisfy the validation. - // This won't affect execution since Morph rejects blob transactions at the - // transaction pool level. - let block_env = BlockEnv { + let block_env = MorphBlockEnv { number: U256::from(header.number()), beneficiary: fee_recipient, timestamp: U256::from(header.timestamp()), difficulty: header.difficulty(), - prevrandao: header.mix_hash(), - gas_limit: header.gas_limit(), - basefee: header.base_fee_per_gas().unwrap_or_default(), - blob_excess_gas_and_price: Some(BlobExcessGasAndPrice { - excess_blob_gas: 0, - blob_gasprice: 1, // minimum blob gas price - }), - slot_num: 0, + prevrandao: header + .mix_hash() + .map(|hash| U256::from_be_bytes(hash.0)) + .unwrap_or_default(), + gas_limit: U256::from(header.gas_limit()), + basefee: U256::from(header.base_fee_per_gas().unwrap_or_default()), + // Morph doesn't support EIP-4844 blob transactions; this is the minimum blob gas + // price, which nothing observes because BLOBBASEFEE is disabled. + blob_basefee: U256::ONE, + ..Default::default() }; - Ok(EvmEnv { - cfg_env, - block_env: MorphBlockEnv { inner: block_env }, - }) + Ok(morph_evm_env( + spec, + self.chain_spec().chain().id(), + header.gas_limit(), + block_env, + )) } fn next_evm_env( @@ -84,51 +71,44 @@ impl ConfigureEvm for MorphEvmConfig { .chain_spec() .morph_hardfork_at(parent.number() + 1, attributes.timestamp); - let mut cfg_env = CfgEnv::::default() - .with_chain_id(self.chain_spec().chain().id()) - .with_spec_and_mainnet_gas_params(spec); - cfg_env.disable_eip7623 = true; - // Morph does not enforce EIP-7825 transaction gas limit cap — see evm_env() above. - cfg_env.tx_gas_limit_cap = Some(attributes.gas_limit); - let fee_recipient = self .chain_spec() .fee_vault_address() .unwrap_or(attributes.suggested_fee_recipient); - // Morph doesn't support EIP-4844 blob transactions, but when SpecId >= CANCUN, - // revm requires `blob_excess_gas_and_price` to be set. We provide a placeholder - // value to satisfy the validation. - let block_env = BlockEnv { + let block_env = MorphBlockEnv { number: U256::from(parent.number() + 1), beneficiary: fee_recipient, timestamp: U256::from(attributes.timestamp), difficulty: U256::ZERO, // Morph L2 follows geth's L2 path here: PREVRANDAO/mixHash is fixed to zero. - prevrandao: Some(B256::ZERO), - gas_limit: attributes.gas_limit, - basefee: attributes.base_fee_per_gas.unwrap_or_else(|| { + prevrandao: U256::from_be_bytes(B256::ZERO.0), + gas_limit: U256::from(attributes.gas_limit), + basefee: U256::from(attributes.base_fee_per_gas.unwrap_or_else(|| { self.chain_spec() .next_block_base_fee(parent, attributes.timestamp) .unwrap_or_default() - }), - blob_excess_gas_and_price: Some(BlobExcessGasAndPrice { - excess_blob_gas: 0, - blob_gasprice: 1, // minimum blob gas price - }), - slot_num: 0, + })), + // See `evm_env`. + blob_basefee: U256::ONE, + ..Default::default() }; - Ok(EvmEnv { - cfg_env, - block_env: MorphBlockEnv { inner: block_env }, - }) + Ok(morph_evm_env( + spec, + self.chain_spec().chain().id(), + attributes.gas_limit, + block_env, + )) } fn context_for_block<'a>( &self, block: &'a SealedBlock, - ) -> Result, Self::Error> { + ) -> Result, Self::Error> + where + Self: 'a, + { Ok(EthBlockExecutionCtx { parent_hash: block.header().parent_hash(), parent_beacon_block_root: block.header().parent_beacon_block_root(), @@ -137,7 +117,7 @@ impl ConfigureEvm for MorphEvmConfig { .body() .withdrawals .as_ref() - .map(|w| Cow::Borrowed(w.0.as_slice())), + .map(|w| Cow::Borrowed(w.as_slice())), extra_data: block.extra_data().clone(), tx_count_hint: Some(block.body().transactions.len()), // Morph L2 has no PoS slot semantics; introduced upstream in alloy 2.0. @@ -149,12 +129,15 @@ impl ConfigureEvm for MorphEvmConfig { &self, parent: &SealedHeader, attributes: Self::NextBlockEnvCtx, - ) -> Result, Self::Error> { + ) -> Result, Self::Error> { Ok(EthBlockExecutionCtx { parent_hash: parent.hash(), parent_beacon_block_root: attributes.parent_beacon_block_root, ommers: &[], - withdrawals: attributes.inner.withdrawals.map(|w| Cow::Owned(w.0)), + withdrawals: attributes + .inner + .withdrawals + .map(|w| Cow::Owned(w.into_inner())), extra_data: attributes.inner.extra_data, tx_count_hint: None, // Morph L2 has no PoS slot semantics; introduced upstream in alloy 2.0. @@ -224,7 +207,7 @@ mod tests { let header = create_morph_header(100, 1000); let env = config.evm_env(&header).unwrap(); - assert_eq!(env.cfg_env.chain_id, 1337); + assert_eq!(env.version.chain_id, 1337); } #[test] @@ -235,10 +218,10 @@ mod tests { let header = create_morph_header(100, 1000); let env = config.evm_env(&header).unwrap(); - assert_eq!(env.block_env.inner.number, U256::from(100u64)); - assert_eq!(env.block_env.inner.timestamp, U256::from(1000u64)); - assert_eq!(env.block_env.inner.gas_limit, 30_000_000); - assert_eq!(env.block_env.inner.basefee, 1_000_000); + assert_eq!(env.block.number, U256::from(100u64)); + assert_eq!(env.block.timestamp, U256::from(1000u64)); + assert_eq!(env.block.gas_limit, U256::from(30_000_000)); + assert_eq!(env.block.basefee, U256::from(1_000_000)); } #[test] @@ -249,10 +232,8 @@ mod tests { let header = create_morph_header(100, 1000); let env = config.evm_env(&header).unwrap(); - // Morph uses placeholder blob gas values - let blob_info = env.block_env.inner.blob_excess_gas_and_price.unwrap(); - assert_eq!(blob_info.excess_blob_gas, 0); - assert_eq!(blob_info.blob_gasprice, 1); + // Morph uses a placeholder blob base fee + assert_eq!(env.block.blob_basefee, U256::ONE); } #[test] @@ -263,7 +244,7 @@ mod tests { let header = create_morph_header(100, 1000); let env = config.evm_env(&header).unwrap(); - assert!(env.cfg_env.disable_eip7623); + assert!(!env.version.feature(evm2::EvmFeatures::EIP7623)); } #[test] @@ -288,9 +269,9 @@ mod tests { let env = config.next_evm_env(&parent, &attrs).unwrap(); - assert_eq!(env.block_env.inner.number, U256::from(100u64)); - assert_eq!(env.block_env.inner.timestamp, U256::from(1001u64)); - assert_eq!(env.block_env.inner.basefee, 500_000); + assert_eq!(env.block.number, U256::from(100u64)); + assert_eq!(env.block.timestamp, U256::from(1001u64)); + assert_eq!(env.block.basefee, U256::from(500_000)); } #[test] diff --git a/crates/evm/src/engine.rs b/crates/evm/src/engine.rs index 8ed9e581..f02a001f 100644 --- a/crates/evm/src/engine.rs +++ b/crates/evm/src/engine.rs @@ -4,15 +4,14 @@ //! enabling execution of engine payloads with proper transaction iteration and context setup. use crate::MorphEvmConfig; -use alloy_consensus::crypto::RecoveryError; -use alloy_evm::block::ExecutableTxParts; +use alloy_consensus::{crypto::RecoveryError, transaction::Recovered}; use alloy_primitives::Address; use morph_payload_types::MorphExecutionData; use morph_primitives::{Block, MorphTxEnvelope}; use morph_revm::MorphTxEnv; use reth_evm::{ - ConfigureEngineEvm, ConfigureEvm, EvmEnvFor, ExecutableTxIterator, ExecutionCtxFor, - RecoveredTx, ToTxEnv, + ConfigureEngineEvm, ConfigureEvm, EvmEnvFor, ExecutableTxIterator, ExecutableTxParts, + ExecutionCtxFor, RecoveredTx, }; use reth_primitives_traits::{SealedBlock, SignedTransaction}; use std::sync::Arc; @@ -82,17 +81,11 @@ impl RecoveredTx for RecoveredInBlock { } } -impl ToTxEnv for RecoveredInBlock { - fn to_tx_env(&self) -> MorphTxEnv { - MorphTxEnv::from_recovered_tx(self.tx(), *self.signer()) - } -} - -impl ExecutableTxParts for RecoveredInBlock { +impl ExecutableTxParts, MorphTxEnvelope> for RecoveredInBlock { type Recovered = Self; - fn into_parts(self) -> (MorphTxEnv, Self) { - let tx_env = MorphTxEnv::from_recovered_tx(self.tx(), *self.signer()); + fn into_parts(self) -> (Recovered, Self) { + let tx_env = Recovered::new_unchecked(MorphTxEnv::from_envelope(self.tx()), self.sender); (tx_env, self) } } @@ -242,14 +235,11 @@ mod tests { let evm_env = result.unwrap(); // Verify EVM environment fields - assert_eq!(evm_env.block_env.inner.number, U256::from(block.number())); - assert_eq!( - evm_env.block_env.inner.timestamp, - U256::from(block.timestamp()) - ); + assert_eq!(evm_env.block.number, U256::from(block.number())); + assert_eq!(evm_env.block.timestamp, U256::from(block.timestamp())); assert_eq!( - evm_env.block_env.inner.gas_limit, - block.header().gas_limit() + evm_env.block.gas_limit, + U256::from(block.header().gas_limit()) ); } } diff --git a/crates/evm/src/evm.rs b/crates/evm/src/evm.rs index 368f605d..d6940d73 100644 --- a/crates/evm/src/evm.rs +++ b/crates/evm/src/evm.rs @@ -1,282 +1,185 @@ -use alloy_evm::{ - Database, Evm, EvmEnv, EvmFactory, - precompiles::PrecompilesMap, - revm::{ - Context, ExecuteEvm, InspectEvm, Inspector, SystemCallEvm, - context::{ - CfgEnv, DBErrorMarker, - result::{EVMError, ResultAndState}, - }, - inspector::NoOpInspector, - }, +//! Morph EVM instance and factory. + +use alloy_consensus::transaction::Recovered; +use alloy_primitives::Address; +use evm2::{ + ExecutedTx, Inspector, TxResult, TxResultWithState, + evm::{AccountInfo, Cache, DynDatabase, PendingState}, + precompiles::{MovePrecompileError, PrecompileId}, }; -use alloy_primitives::{Address, Bytes}; -use morph_chainspec::hardfork::MorphHardfork; -use morph_revm::{MorphHaltReason, MorphInvalidTransaction, MorphTxEnv, evm::MorphContext}; +use morph_revm::{FeeFrameFilter, MorphEvmEnv, MorphEvmTypes, MorphTxEnv}; +use reth_evm::{BlockExecutionError, Evm}; use std::ops::{Deref, DerefMut}; -use crate::MorphBlockEnv; - +/// Marker for the EVM a [`crate::MorphEvmConfig`] creates. #[derive(Debug, Default, Clone, Copy)] #[non_exhaustive] pub struct MorphEvmFactory; -impl EvmFactory for MorphEvmFactory { - type Evm>> = MorphEvm; - type Context = MorphContext; - type Tx = MorphTxEnv; - type Error = EVMError; - type HaltReason = MorphHaltReason; - type Spec = MorphHardfork; - type BlockEnv = MorphBlockEnv; - type Precompiles = PrecompilesMap; - - fn create_evm( - &self, - db: DB, - input: EvmEnv, - ) -> Self::Evm { - MorphEvm::new(db, input) - } - - fn create_evm_with_inspector>>( - &self, - db: DB, - input: EvmEnv, - inspector: I, - ) -> Self::Evm { - MorphEvm::new(db, input).with_inspector(inspector) - } -} - -/// Morph EVM implementation. +/// A configured Morph EVM. /// -/// This is a wrapper type around the `revm` ethereum evm with optional [`Inspector`] (tracing) -/// support. [`Inspector`] support is configurable at runtime because it's part of the underlying -/// `RevmEvm` type. +/// Wraps the evm2 instance so that every inspector installed on it goes through +/// [`FeeFrameFilter`]: tracers must see a token-fee transaction without its fee frames. #[expect(missing_debug_implementations)] -pub struct MorphEvm { - inner: morph_revm::MorphEvm, - /// Precompiles wrapped as PrecompilesMap for reth compatibility - precompiles_map: PrecompilesMap, - inspect: bool, +pub struct MorphEvm<'a> { + inner: morph_revm::MorphEvm<'a>, } -impl MorphEvm { - /// Create a new [`MorphEvm`] instance. - pub fn new(db: DB, input: EvmEnv) -> Self { - let inner = morph_revm::MorphEvm::from_env(db, input, NoOpInspector {}); - let precompiles_map = PrecompilesMap::from_static(inner.precompiles.precompiles()); - +impl<'a> MorphEvm<'a> { + /// Creates a Morph EVM over `database`. + pub fn new(database: impl DynDatabase + 'a, env: MorphEvmEnv) -> Self { Self { - inner, - precompiles_map, - inspect: false, + inner: morph_revm::morph_evm(database, env), } } } -impl MorphEvm { - /// Provides a reference to the EVM context. - pub const fn ctx(&self) -> &MorphContext { - &self.inner.inner.ctx - } - - /// Provides a mutable reference to the EVM context. - pub fn ctx_mut(&mut self) -> &mut MorphContext { - &mut self.inner.inner.ctx - } - - /// Sets the inspector for the EVM. - pub fn with_inspector(self, inspector: OINSP) -> MorphEvm { - MorphEvm { - inner: self.inner.with_inspector(inspector), - precompiles_map: self.precompiles_map, - inspect: true, - } - } +impl<'a> Deref for MorphEvm<'a> { + type Target = morph_revm::MorphEvm<'a>; - /// Returns the cached token fee info from the handler's validation phase. - /// - /// Avoids redundant DB reads when the block executor needs token fee - /// parameters (e.g., for receipt construction). #[inline] - pub fn cached_token_fee_info(&self) -> Option { - self.inner.cached_token_fee_info() - } - - /// Returns the L1 data fee cached during handler validation. - /// - /// Avoids re-encoding the full transaction RLP in the block executor's - /// receipt-building path. - #[inline] - pub fn cached_l1_data_fee(&self) -> alloy_primitives::U256 { - self.inner.cached_l1_data_fee() - } - - /// Takes the cached pre-execution fee logs (token fee deduction Transfer events). - #[inline] - pub fn take_pre_fee_logs(&mut self) -> Vec { - self.inner.take_pre_fee_logs() + fn deref(&self) -> &Self::Target { + &self.inner } +} - /// Takes the cached post-execution fee logs (token fee reimbursement Transfer events). +impl DerefMut for MorphEvm<'_> { #[inline] - pub fn take_post_fee_logs(&mut self) -> Vec { - self.inner.take_post_fee_logs() + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.inner } } -impl Deref for MorphEvm -where - DB: Database, - I: Inspector>, -{ - type Target = MorphContext; +impl<'a> Evm for MorphEvm<'a> { + type EvmTypes = MorphEvmTypes; + type Transaction = MorphTxEnv; - #[inline] - fn deref(&self) -> &Self::Target { - self.ctx() + fn transact( + &mut self, + transaction: &Recovered, + ) -> Result, BlockExecutionError> { + Evm::transact(&mut self.inner, transaction) } -} -impl DerefMut for MorphEvm -where - DB: Database, - I: Inspector>, -{ - #[inline] - fn deref_mut(&mut self) -> &mut Self::Target { - self.ctx_mut() + fn transact_commit( + &mut self, + transaction: &Recovered, + ) -> Result, BlockExecutionError> { + Evm::transact_commit(&mut self.inner, transaction) } -} -impl Evm for MorphEvm -where - DB: Database, - I: Inspector>, -{ - type DB = DB; - type Tx = MorphTxEnv; - type Error = EVMError; - type HaltReason = MorphHaltReason; - type Spec = MorphHardfork; - type BlockEnv = MorphBlockEnv; - type Precompiles = PrecompilesMap; - type Inspector = I; + fn transact_result( + &mut self, + transaction: &Recovered, + ) -> Result, BlockExecutionError> { + Evm::transact_result(&mut self.inner, transaction) + } - fn block(&self) -> &Self::BlockEnv { - &self.block + fn transact_with_inspector( + &mut self, + transaction: &Recovered, + inspector: I, + ) -> Result<(I, TxResultWithState), BlockExecutionError> + where + I: Inspector + 'static, + { + let (filter, result) = Evm::transact_with_inspector( + &mut self.inner, + transaction, + FeeFrameFilter::new(inspector), + )?; + Ok((filter.into_inner(), result)) } - fn cfg_env(&self) -> &CfgEnv { - &self.inner.inner.ctx.cfg + fn set_inspector(&mut self, inspector: I) + where + I: Inspector + 'static, + { + Evm::set_inspector(&mut self.inner, FeeFrameFilter::new(inspector)); } - fn chain_id(&self) -> u64 { - self.cfg.chain_id + fn state_db_mut(&mut self) -> &mut dyn DynDatabase { + Evm::state_db_mut(&mut self.inner) } - fn transact_raw( - &mut self, - tx: Self::Tx, - ) -> Result, Self::Error> { - if self.inspect { - self.inner.inspect_tx(tx) - } else { - self.inner.transact(tx) - } + fn commit_state(&mut self, state: &PendingState) { + Evm::commit_state(&mut self.inner, state); } - fn transact_system_call( - &mut self, - caller: Address, - contract: Address, - data: Bytes, - ) -> Result, Self::Error> { - self.inner.system_call_with_caller(caller, contract, data) + fn take_state_cache(&mut self) -> Cache { + Evm::take_state_cache(&mut self.inner) } - fn finish(self) -> (Self::DB, EvmEnv) { - let Context { - block: block_env, - cfg: cfg_env, - journaled_state, - .. - } = self.inner.inner.ctx; + fn precompile_ids(&self) -> Vec<(Address, PrecompileId)> { + Evm::precompile_ids(&self.inner) + } - (journaled_state.database, EvmEnv { block_env, cfg_env }) + fn has_precompile(&self, address: &Address) -> bool { + Evm::has_precompile(&self.inner, address) } - fn set_inspector_enabled(&mut self, enabled: bool) { - self.inspect = enabled; + fn account_info( + &mut self, + address: &Address, + ) -> Result, BlockExecutionError> { + Evm::account_info(&mut self.inner, address) } - fn components(&self) -> (&Self::DB, &Self::Inspector, &Self::Precompiles) { - ( - &self.inner.inner.ctx.journaled_state.database, - &self.inner.inner.inspector, - &self.precompiles_map, - ) + fn move_precompiles( + &mut self, + moves: impl IntoIterator, + ) -> Result<(), MovePrecompileError> { + Evm::move_precompiles(&mut self.inner, moves) } - fn components_mut(&mut self) -> (&mut Self::DB, &mut Self::Inspector, &mut Self::Precompiles) { - ( - &mut self.inner.inner.ctx.journaled_state.database, - &mut self.inner.inner.inspector, - &mut self.precompiles_map, - ) + fn transact_and_discard( + &mut self, + transaction: &Recovered, + observe: impl FnOnce(&ExecutedTx<'_, '_, MorphEvmTypes>) -> R, + ) -> Result { + Evm::transact_and_discard(&mut self.inner, transaction, observe) } } #[cfg(test)] mod tests { - use alloy_primitives::U256; - use reth_revm::context::BlockEnv; - use revm::{ - context::TxEnv, - database::{CacheDB, EmptyDB}, - state::AccountInfo, - }; - use super::*; + use alloy_primitives::{TxKind, U256}; + use evm2::evm::InMemoryDB; + use morph_chainspec::hardfork::MorphHardfork; + use morph_revm::{MorphBlockEnv, morph_evm_env}; #[test] fn can_execute_tx() { // Create a database with the caller having sufficient balance - let mut db = CacheDB::new(EmptyDB::default()); + let mut db = InMemoryDB::default(); db.insert_account_info( - Address::ZERO, - AccountInfo { - balance: U256::from(1_000_000), - ..Default::default() - }, + &Address::ZERO, + AccountInfo::default().with_balance(U256::from(1_000_000)), ); - let mut evm = MorphEvm::new( - db, - EvmEnv { - block_env: MorphBlockEnv { - inner: BlockEnv { - basefee: 1, - ..Default::default() - }, - }, + let env = morph_evm_env( + MorphHardfork::default(), + 1, + 30_000_000, + MorphBlockEnv { + basefee: U256::from(1), ..Default::default() }, ); - let result = evm - .transact(MorphTxEnv { - inner: TxEnv { - caller: Address::ZERO, - gas_price: 1, // Must be >= basefee - gas_limit: 21000, - ..Default::default() - }, + let mut evm = MorphEvm::new(db, env); + let tx = Recovered::new_unchecked( + MorphTxEnv { + gas_price: 1, // Must be >= basefee + gas_limit: 21000, + kind: TxKind::Call(Address::with_last_byte(0xff)), ..Default::default() - }) - .unwrap(); + }, + Address::ZERO, + ); + + let result = Evm::transact(&mut evm, &tx).unwrap(); - assert!(result.result.is_success()); + assert!(result.result.status); } } diff --git a/crates/evm/src/lib.rs b/crates/evm/src/lib.rs index 62e90949..2ce4b5a0 100644 --- a/crates/evm/src/lib.rs +++ b/crates/evm/src/lib.rs @@ -74,22 +74,19 @@ pub use error::MorphEvmError; pub mod evm; use std::sync::Arc; -use alloy_evm::{ - block::{BlockExecutorFactory, StateDB}, - eth::EthBlockExecutionCtx, - revm::Inspector, -}; -pub use evm::MorphEvmFactory; +pub use evm::{MorphEvm, MorphEvmFactory}; +use evm2::evm::DynDatabase; use morph_primitives::{MorphReceipt, MorphTxEnvelope}; +use reth_evm::BlockExecutorFactory; +use reth_evm_ethereum::EthBlockExecutionCtx; // Re-export types that surface in `BlockExecutorFactory` associated types so // downstream crates can name them. They are constructed via the factory. -pub use crate::block::{MorphBlockExecutor, MorphTxResult}; -use crate::{block::MorphBlockExecutorFactory, evm::MorphEvm}; +use crate::block::DefaultMorphReceiptBuilder; +pub use crate::block::{MorphBlockExecutor, MorphTxResult, morph_invalid_tx_error}; use morph_chainspec::MorphChainSpec; -use morph_revm::evm::MorphContext; -pub use morph_revm::{MorphBlockEnv, MorphHaltReason}; +pub use morph_revm::{MorphBlockEnv, MorphEvmEnv, MorphEvmTypes}; /// Morph EVM configuration and block executor factory. /// @@ -114,8 +111,10 @@ pub use morph_revm::{MorphBlockEnv, MorphHaltReason}; /// The internal executor factory is lightweight and stateless. #[derive(Debug, Clone)] pub struct MorphEvmConfig { - /// Internal block executor factory that creates `MorphBlockExecutor` instances. - executor_factory: MorphBlockExecutorFactory, + /// Chain specification. + chain_spec: Arc, + /// EVM factory. + evm_factory: MorphEvmFactory, /// Block assembler for building `MorphHeader` blocks from execution results. pub block_assembler: MorphBlockAssembler, @@ -127,10 +126,10 @@ impl MorphEvmConfig { /// This is the primary constructor that allows specifying a custom EVM factory /// for advanced use cases (e.g., custom inspector or precompile configuration). pub fn new(chain_spec: Arc, evm_factory: MorphEvmFactory) -> Self { - let executor_factory = MorphBlockExecutorFactory::new(chain_spec.clone(), evm_factory); Self { - executor_factory, - block_assembler: MorphBlockAssembler::new(chain_spec), + block_assembler: MorphBlockAssembler::new(chain_spec.clone()), + chain_spec, + evm_factory, } } @@ -139,46 +138,56 @@ impl MorphEvmConfig { /// This is the recommended constructor for most use cases. It uses the default /// Morph EVM factory with standard configuration. pub fn new_with_default_factory(chain_spec: Arc) -> Self { - Self::new(chain_spec, MorphEvmFactory::default()) + Self::new(chain_spec, MorphEvmFactory) } /// Returns a reference to the Morph chain specification. /// /// The chain spec contains hardfork configuration and network parameters. pub const fn chain_spec(&self) -> &Arc { - self.executor_factory.spec() + &self.chain_spec } /// Returns a reference to the Morph EVM factory. /// /// The factory is used to create EVM instances for block execution. pub const fn evm_factory(&self) -> &MorphEvmFactory { - self.executor_factory.evm_factory() + &self.evm_factory } } impl BlockExecutorFactory for MorphEvmConfig { type EvmFactory = MorphEvmFactory; - type ExecutionCtx<'a> = EthBlockExecutionCtx<'a>; + type EvmTypes = MorphEvmTypes; type Transaction = MorphTxEnvelope; type Receipt = MorphReceipt; - type TxExecutionResult = MorphTxResult; - type Executor<'a, DB: StateDB, I: Inspector>> = MorphBlockExecutor; + type Evm<'a> = MorphEvm<'a>; + type EvmEnv = MorphEvmEnv; + type ExecutionCtx<'a> = EthBlockExecutionCtx<'a>; + // The Morph executor owns its EVM and receipt builder by value rather than + // borrowing them from the factory. + type Executor<'a> = MorphBlockExecutor<'a>; + + fn create_executor<'a>( + &'a self, + evm: Self::Evm<'a>, + ctx: Self::ExecutionCtx<'a>, + ) -> Self::Executor<'a> + where + Self: 'a, + { + MorphBlockExecutor::new(evm, DefaultMorphReceiptBuilder, ctx.tx_count_hint) + } fn evm_factory(&self) -> &Self::EvmFactory { - self.executor_factory.evm_factory() + &self.evm_factory } - fn create_executor<'a, DB, I>( - &'a self, - evm: MorphEvm, - ctx: Self::ExecutionCtx<'a>, - ) -> Self::Executor<'a, DB, I> + fn evm_with_env<'a, DB>(&self, db: DB, evm_env: Self::EvmEnv) -> Self::Evm<'a> where - DB: StateDB, - I: Inspector>, + DB: DynDatabase + 'a, { - self.executor_factory.create_executor(evm, ctx) + MorphEvm::new(db, evm_env) } } diff --git a/crates/node/Cargo.toml b/crates/node/Cargo.toml index afd76993..4154fc58 100644 --- a/crates/node/Cargo.toml +++ b/crates/node/Cargo.toml @@ -50,6 +50,7 @@ reth-trie.workspace = true # Alloy alloy-consensus.workspace = true +alloy-eip7928.workspace = true alloy-eips.workspace = true alloy-genesis.workspace = true alloy-hardforks.workspace = true diff --git a/crates/node/src/test_utils.rs b/crates/node/src/test_utils.rs index 44c19b4e..bfe4eb6f 100644 --- a/crates/node/src/test_utils.rs +++ b/crates/node/src/test_utils.rs @@ -336,7 +336,7 @@ impl TestNodeBuilder { // can carry `--builder.gaslimit`, which `setup_engine` gives no way to set. let is_dev = self.is_dev; let desired_gas_limit = self.desired_gas_limit; - reth_e2e_test_utils::E2ETestSetupBuilder::::new( + reth_e2e_test_utils::E2ETestSetupBuilder::::new_with_attributes_generator( self.num_nodes, Arc::new(chain_spec), morph_payload_attributes, diff --git a/crates/node/src/validator.rs b/crates/node/src/validator.rs index bcbccc01..776c87fa 100644 --- a/crates/node/src/validator.rs +++ b/crates/node/src/validator.rs @@ -25,7 +25,7 @@ use reth_engine_tree::tree::{ }, }; use reth_errors::{ConsensusError, ProviderResult}; -use reth_evm::{ConfigureEvm, revm::context::Block as _}; +use reth_evm::{ConfigureEvm, EvmEnv as _}; use reth_node_api::{ AddOnsContext, FullNodeComponents, InvalidPayloadAttributesError, NewPayloadError, NodeTypes, PayloadAttributes, PayloadTypes, PayloadValidator, @@ -35,13 +35,14 @@ use reth_node_builder::{ rpc::{EngineValidatorBuilder, PayloadValidatorBuilder}, }; use reth_payload_primitives::BuiltPayloadExecutedBlock; -use reth_primitives_traits::{RecoveredBlock, SealedBlock}; +use reth_primitives_traits::{RecoveredBlock, SealedBlock, SealedBlockWith}; use reth_provider::{ - BlockExecutionOutput, BlockNumReader, BlockReader, ChainSpecProvider, DatabaseProviderFactory, - PruneCheckpointReader, StageCheckpointReader, StateProviderFactory, StateReader, - StateRootProvider, StorageSettingsCache, TryIntoHistoricalStateProvider, + BlockExecutionOutput, BlockNumReader, BlockReader, ChainSpecProvider, ChangeSetReader, + DatabaseProviderFactory, DatabaseProviderROFactory, PruneCheckpointReader, + StageCheckpointReader, StateProviderFactory, StateReader, StateRootProvider, + StorageChangeSetReader, StorageSettingsCache, }; -use reth_storage_overlay::OverlayManager; +use reth_storage_overlay::{OverlayManager, OverlayStateProviderFactory}; use reth_tracing::tracing; use reth_transaction_pool::{ BestTransactions, BestTransactionsAttributes, PoolTransaction, TransactionPool, @@ -126,7 +127,11 @@ where let provider = ctx.node.provider().clone(); let state_root_strategy: Arc< dyn StateRootStrategy, - > = Arc::new(MorphStateRootStrategy::new(chain_spec.clone())); + > = Arc::new(MorphStateRootStrategy::new( + chain_spec.clone(), + provider.clone(), + overlay_manager.clone(), + )); let tree_config = strict_morph_tree_config(tree_config); let txpool_prewarming = tree_config.txpool_prewarming(); let mut validator = BasicEngineValidator::new( @@ -388,11 +393,11 @@ where fn validate_block( &mut self, - block: SealedBlock, + block: SealedBlockWith>, ctx: TreeCtx<'_, MorphPrimitives>, ) -> reth_engine_tree::tree::ValidationOutcome { - let block_hash = block.hash(); - let l1_validation = self.validate_next_l1_msg_index_for_block(&block, &ctx); + let block_hash = block.block().hash(); + let l1_validation = self.validate_next_l1_msg_index_for_block(block.block(), &ctx); self.post_execution_validator .clear_withdraw_trie_root_expectation_on_error(block_hash, l1_validation)?; @@ -440,21 +445,29 @@ where /// computes and persists the real MPT updates but trusts the historical header /// root, which is a ZK-trie commitment and cannot be compared to the MPT root. #[derive(Debug)] -struct MorphStateRootStrategy { +struct MorphStateRootStrategy

{ chain_spec: Arc, default: DefaultStateRootStrategy, + provider: P, + overlay_manager: OverlayManager, } -impl MorphStateRootStrategy { - fn new(chain_spec: Arc) -> Self { +impl

MorphStateRootStrategy

{ + fn new( + chain_spec: Arc, + provider: P, + overlay_manager: OverlayManager, + ) -> Self { Self { chain_spec, default: DefaultStateRootStrategy::default(), + provider, + overlay_manager, } } } -impl StateRootStrategy for MorphStateRootStrategy +impl StateRootStrategy for MorphStateRootStrategy

where P: DatabaseProviderFactory + BlockReader

@@ -467,8 +480,9 @@ where P::Provider: BlockNumReader + PruneCheckpointReader + StageCheckpointReader + + ChangeSetReader + + StorageChangeSetReader + StorageSettingsCache - + TryIntoHistoricalStateProvider + 'static, Evm: ConfigureEvm + 'static, DefaultStateRootStrategy: StateRootStrategy, @@ -477,14 +491,18 @@ where &self, ctx: StateRootJobContext<'_, MorphPrimitives, P, Evm>, ) -> ProviderResult> { - let timestamp: u64 = ctx.env().evm_env.block_env.timestamp().saturating_to(); + let timestamp: u64 = ctx.env().evm_env.block_env().timestamp.saturating_to(); if self.chain_spec.is_jade_active_at_timestamp(timestamp) { return self.default.prepare(ctx); } Ok(PreparedStateRootJob::new( Box::new(PreJadeStateRootJob { - provider_builder: ctx.provider_builder(), + state_provider_factory: OverlayStateProviderFactory::new( + self.provider.clone(), + self.overlay_manager + .overlay_builder(ctx.parent_header().hash()), + ), }), None, )) @@ -502,24 +520,18 @@ where } struct PreJadeStateRootJob

{ - provider_builder: reth_engine_tree::tree::StateProviderBuilder, + state_provider_factory: OverlayStateProviderFactory, } impl

StateRootJob for PreJadeStateRootJob

where - P: DatabaseProviderFactory - + BlockReader - + StateProviderFactory - + StateReader - + Clone - + Send - + Sync - + 'static, + P: DatabaseProviderFactory + Clone + Send + Sync + 'static, P::Provider: BlockNumReader + PruneCheckpointReader + StageCheckpointReader + + ChangeSetReader + + StorageChangeSetReader + StorageSettingsCache - + TryIntoHistoricalStateProvider + 'static, { fn name(&self) -> &'static str { @@ -532,7 +544,7 @@ where _output: Arc>, hashed_state: &LazyHashedPostState, ) -> ProviderResult { - let provider = self.provider_builder.build()?; + let provider = self.state_provider_factory.database_provider_ro()?; let (_mpt_root, trie_updates) = provider.state_root_with_updates(hashed_state.get().as_ref().clone())?; Ok(StateRootJobOutcome::new( diff --git a/crates/node/tests/it/proof_history.rs b/crates/node/tests/it/proof_history.rs index f7041c58..7d6aceee 100644 --- a/crates/node/tests/it/proof_history.rs +++ b/crates/node/tests/it/proof_history.rs @@ -7,7 +7,7 @@ use std::{sync::Arc, time::Duration}; -use alloy_consensus::{SignableTransaction, TxEip1559, constants::KECCAK_EMPTY}; +use alloy_consensus::{SignableTransaction, TxEip1559}; use alloy_eips::{Encodable2718, NumHash, eip1898::BlockWithParent}; use alloy_genesis::Genesis; use alloy_primitives::{Address, B256, Bytes, TxKind, U256}; @@ -474,11 +474,11 @@ fn assert_outside_window(error: &str, requested: u64) { "expected window error for block {requested}, got: {error}" ); // The window conditions are client conditions, so they must not arrive as internal server - // errors. `MorphEthApiError::STATE_NOT_AVAILABLE_CODE`, kept as a literal here because the test - // asserts the wire contract rather than the constant. + // errors. They use the pruned-history code, kept as a literal here because the test asserts + // the wire contract rather than the constant. assert!( - error.contains("-32005"), - "expected error code -32005 for block {requested}, got: {error}" + error.contains("4444"), + "expected error code 4444 for block {requested}, got: {error}" ); } @@ -782,10 +782,8 @@ async fn proof_history_multi_proof_uses_one_historical_state() -> eyre::Result<( /// is `None` **and** `storage_root` is the empty root. A response that invented either field, or /// an implementation that returned an existing neighbour's leaf, would fail verification here. /// -/// `KECCAK_EMPTY` / `EMPTY_ROOT_HASH` are asserted because they are the values the absent account -/// *would* hash to, which is what keeps the response self-consistent: a verifier can recompute the -/// leaf that must be missing. Zero hashes would carry no such meaning, and only signal absence -/// out-of-band. +/// `codeHash` and `storageHash` are zero, as for the default `eth_getProof`: the account has no leaf +/// in the trie, which is what separates it from an existing account with empty code and storage. #[tokio::test(flavor = "multi_thread")] async fn proof_history_proves_absent_accounts() -> eyre::Result<()> { reth_tracing::init_test_tracing(); @@ -805,8 +803,8 @@ async fn proof_history_proves_absent_accounts() -> eyre::Result<()> { verify_against_state_root(&single, block_1.header.state_root)?; assert_eq!(single.nonce, 0); assert_eq!(single.balance, U256::ZERO); - assert_eq!(single.code_hash, KECCAK_EMPTY); - assert_eq!(single.storage_hash, EMPTY_ROOT_HASH); + assert_eq!(single.code_hash, B256::ZERO); + assert_eq!(single.storage_hash, B256::ZERO); // A slot on a missing account still gets an entry, proving zero rather than omitting it. assert_eq!(storage_entry(&single, absent_slot), U256::ZERO); diff --git a/crates/node/tests/it/rpc.rs b/crates/node/tests/it/rpc.rs index 6613e466..42f701c4 100644 --- a/crates/node/tests/it/rpc.rs +++ b/crates/node/tests/it/rpc.rs @@ -949,10 +949,10 @@ async fn debug_trace_replay_apis_work_for_standard_jade_block() -> eyre::Result< /// `eth_estimateGas` rejects a request whose sender cannot cover the L1 data fee. /// -/// Exercises the `MorphEthApi::caller_gas_allowance` override. In reth v2.0.0 -/// the upstream `estimate_gas_with` sets `cfg_env.disable_fee_charge = true`, -/// so the EVM handler short-circuits and never checks balance — the L1 fee -/// cap must instead be enforced in the gas-allowance pre-check. +/// Exercises the `MorphEthApi::caller_gas_allowance` override. The upstream +/// `estimate_gas_with` removes `EvmFeatures::FEE_CHARGE`, so the EVM handler +/// short-circuits and never checks balance — the L1 fee cap must instead be +/// enforced in the gas-allowance pre-check. /// /// Setup: /// - An unfunded random sender (`balance = 0`). diff --git a/crates/node/tests/it/txpool.rs b/crates/node/tests/it/txpool.rs index acd3e31d..72e79c41 100644 --- a/crates/node/tests/it/txpool.rs +++ b/crates/node/tests/it/txpool.rs @@ -13,6 +13,7 @@ use morph_node::test_utils::{ L1MessageBuilder, TestNodeBuilder, advance_chain, make_eip4844_tx, make_transfer_tx, }; use morph_primitives::MorphTxEnvelope; +use reth_e2e_test_utils::wallet::Wallet; use reth_payload_primitives::BuiltPayload; use super::helpers::wallet_to_arc; @@ -270,6 +271,74 @@ async fn tx_gas_limit_exceeds_block_limit_rejected() -> eyre::Result<()> { Ok(()) } +/// Signs an EIP-1559 call to an account without code. +fn signed_call(wallet: &Wallet, gas_limit: u64, input: Bytes) -> eyre::Result { + use alloy_consensus::{SignableTransaction, TxEip1559}; + use alloy_signer::SignerSync; + + let tx = TxEip1559 { + chain_id: wallet.chain_id, + nonce: 0, + gas_limit, + max_fee_per_gas: 20_000_000_000u128, + max_priority_fee_per_gas: 20_000_000_000u128, + to: TxKind::Call(Address::with_last_byte(0x42)), + value: U256::ZERO, + access_list: Default::default(), + input, + }; + let sig = wallet + .inner + .sign_hash_sync(&tx.signature_hash()) + .map_err(|e| eyre::eyre!("{e}"))?; + Ok(MorphTxEnvelope::Eip1559(tx.into_signed(sig)) + .encoded_2718() + .into()) +} + +/// A transaction above the EIP-7825 gas cap is admitted and mined. +/// +/// Morph caps a transaction at the block gas limit only, while the upstream default for a recent +/// spec is 2^24. Historical transactions exceed that, so losing the override would reject blocks +/// as well as pool transactions. +#[tokio::test(flavor = "multi_thread")] +async fn tx_gas_limit_above_eip7825_cap_is_mined() -> eyre::Result<()> { + reth_tracing::init_test_tracing(); + let (mut nodes, wallet) = TestNodeBuilder::new().build().await?; + let mut node = nodes.pop().unwrap(); + + node.rpc + .inject_tx(signed_call(&wallet, (1 << 24) + 1, Bytes::new())?) + .await?; + let payload = node.advance_block().await?; + + assert_eq!(payload.block().body().transactions.len(), 1); + Ok(()) +} + +/// A transaction with a gas limit below the EIP-7623 calldata floor is admitted and mined. +/// +/// Morph does not adopt EIP-7623, so regular intrinsic gas is the only lower bound. +#[tokio::test(flavor = "multi_thread")] +async fn tx_gas_limit_below_eip7623_floor_is_mined() -> eyre::Result<()> { + reth_tracing::init_test_tracing(); + let (mut nodes, wallet) = TestNodeBuilder::new().build().await?; + let mut node = nodes.pop().unwrap(); + + // 1000 non-zero bytes: intrinsic gas is 37_000, the EIP-7623 floor would be 61_000. + node.rpc + .inject_tx(signed_call( + &wallet, + 40_000, + Bytes::from(vec![0xff; 1_000]), + )?) + .await?; + let payload = node.advance_block().await?; + + assert_eq!(payload.block().body().transactions.len(), 1); + Ok(()) +} + #[tokio::test(flavor = "multi_thread")] async fn tx_max_fee_below_base_fee_accepted_for_queuing() -> eyre::Result<()> { reth_tracing::init_test_tracing(); diff --git a/crates/payload/builder/src/builder.rs b/crates/payload/builder/src/builder.rs index b3da4b7f..35557e62 100644 --- a/crates/payload/builder/src/builder.rs +++ b/crates/payload/builder/src/builder.rs @@ -5,6 +5,7 @@ use crate::{MorphBuilderConfig, MorphPayloadBuilderError, config::PayloadBuildin use alloy_consensus::{BlockHeader, Transaction, Typed2718}; use alloy_eips::eip2718::Encodable2718; use alloy_primitives::{B256, Bytes, U256}; +use evm2::{DatabaseError, evm::State}; use morph_chainspec::MorphChainSpec; use morph_chainspec::{L2_MESSAGE_QUEUE_ADDRESS, L2_MESSAGE_QUEUE_WITHDRAW_TRIE_ROOT_SLOT}; use morph_evm::{MorphEvmConfig, MorphNextBlockEnvAttributes}; @@ -18,9 +19,8 @@ use reth_basic_payload_builder::{ }; use reth_chainspec::ChainSpecProvider; use reth_evm::{ - ConfigureEvm, Database, Evm, NextBlockEnvAttributes, - block::{BlockExecutionError, BlockValidationError}, - execute::{BlockBuilder, BlockBuilderOutcome}, + BlockBuilder, BlockBuilderOutcome, BlockExecutionError, BlockValidationError, ConfigureEvm, + Database, EvmEnv as _, NextBlockEnvAttributes, OnStateHook, database::StateProviderDatabase, }; use reth_execution_cache::{CachedStateMetrics, CachedStateMetricsSource, CachedStateProvider}; use reth_execution_types::BlockExecutionOutput; @@ -28,17 +28,16 @@ use reth_payload_builder::PayloadId; use reth_payload_primitives::{BuiltPayloadExecutedBlock, PayloadBuilderError}; use reth_payload_util::{BestPayloadTransactions, NoopPayloadTransactions, PayloadTransactions}; use reth_primitives_traits::{FastInstant as Instant, RecoveredBlock, SealedHeader}; -use reth_revm::{database::StateProviderDatabase, db::State}; -use reth_storage_api::{StateProvider, StateProviderFactory}; +use reth_storage_api::{EvmStateProvider, StateProvider, StateProviderFactory}; +use reth_tasks::CancelOnDrop; use reth_transaction_pool::{BestTransactionsAttributes, PoolTransaction, TransactionPool}; -use revm::context_interface::Block as RevmBlock; use std::sync::Arc; /// Reads the withdraw trie root from the L2MessageQueue contract storage. -fn read_withdraw_trie_root(db: &mut DB) -> Result { - let value = db.storage( - L2_MESSAGE_QUEUE_ADDRESS, - L2_MESSAGE_QUEUE_WITHDRAW_TRIE_ROOT_SLOT, +fn read_withdraw_trie_root(state: &mut State<'_>) -> Result { + let value = state.storage_slot_untracked( + &L2_MESSAGE_QUEUE_ADDRESS, + &L2_MESSAGE_QUEUE_WITHDRAW_TRIE_ROOT_SLOT, )?; Ok(B256::from(value)) } @@ -208,22 +207,27 @@ where // block. Wrap the state provider so account/storage/code reads consult // the cache before hitting the DB — amortizes cross-block cost when the // payload builder and engine both touch overlapping state. - let mut state_provider: Box = - self.client.state_by_block_hash(ctx.parent().hash())?; - if let Some(execution_cache) = execution_cache { - // reth v2.2.0 dropped `SavedCache::metrics`; the canonical pattern - // (see `reth-ethereum-payload`) is to materialize a fresh zeroed - // metrics handle on every payload build — cheap because morph-reth - // builds payloads on demand rather than every 12s like upstream. - state_provider = Box::new(CachedStateProvider::new( - state_provider, + let state_provider = self.client.state_by_block_hash(ctx.parent().hash())?; + let evm_state_provider = (&state_provider).into_evm_state_provider(); + // reth v2.2.0 dropped `SavedCache::metrics`; the canonical pattern + // (see `reth-ethereum-payload`) is to materialize a fresh zeroed + // metrics handle on every payload build — cheap because morph-reth + // builds payloads on demand rather than every 12s like upstream. + let cached_state_provider = execution_cache.map(|execution_cache| { + CachedStateProvider::new( + &evm_state_provider, execution_cache.cache().clone(), Some(CachedStateMetrics::zeroed( CachedStateMetricsSource::Builder, )), - )); - } - let state = StateProviderDatabase::new(state_provider.as_ref()); + ) + }); + let state = StateProviderDatabase::new( + cached_state_provider + .as_ref() + .map(|provider| provider as &dyn EvmStateProvider) + .unwrap_or(&evm_state_provider), + ); // Reuse cached reads from previous runs for incremental payload building build_payload_inner( @@ -293,7 +297,7 @@ struct MorphPayloadBuilderCtx { /// Payload configuration. config: PayloadConfig, /// Marker to check whether the job has been cancelled. - cancel: reth_revm::cancelled::CancelOnDrop, + cancel: CancelOnDrop, /// The currently best payload. best_payload: Option, /// Builder configuration with limits. @@ -349,8 +353,12 @@ impl MorphPayloadBuilderCtx { builder: &mut impl BlockBuilder, info: &mut ExecutionInfo, ) -> Result, PayloadBuilderError> { - let block_gas_limit = builder.evm().block().gas_limit(); - let base_fee = builder.evm().block().basefee(); + let block_gas_limit = builder + .evm_env() + .block_env() + .gas_limit + .saturating_to::(); + let base_fee = builder.evm_env().block_base_fee(); let supplied_tx_count = self.attributes().transactions.len(); let mut executed_txs: Vec = Vec::with_capacity(supplied_tx_count); let mut saw_l2_transaction = false; @@ -431,9 +439,9 @@ impl MorphPayloadBuilderCtx { // Execute the transaction and record EVM execution time. let apply_started = Instant::now(); - // `BlockBuilder::execute_transaction` returns `GasOutput` from - // alloy-evm 0.34; pre-Amsterdam morph treats regular and state gas - // as a single number, so collapse to `tx_gas_used()` immediately. + // `BlockBuilder::execute_transaction` returns a `GasOutput`; pre-Amsterdam morph + // treats regular and state gas as a single number, so collapse to + // `tx_gas_used()` immediately. let gas_used = match builder.execute_transaction(recovered_tx.clone()) { Ok(gas_output) => gas_output.tx_gas_used(), Err(BlockExecutionError::Validation(BlockValidationError::InvalidTx { @@ -539,11 +547,17 @@ impl MorphPayloadBuilderCtx { where BestTxs: PayloadTransactions>, { - let block_gas_limit = builder.evm().block().gas_limit(); - let base_fee = builder.evm().block().basefee(); + let block_gas_limit = builder + .evm_env() + .block_env() + .gas_limit + .saturating_to::(); + let base_fee = builder.evm_env().block_base_fee(); while let Some(tx) = best_txs.next(()) { - // Check if the job was cancelled + // Check if the job was cancelled. This must stay `is_cancelled`: `is_interrupted` + // also reports a requested finalization, which every `engine_assembleL2Block` + // issues right after the job starts and would truncate the block. if self.cancel.is_cancelled() { return Ok(Some(())); } @@ -750,7 +764,7 @@ fn build_payload_inner<'a, DB, BestTxs>( mut state_root_handle: Option, ) -> Result, PayloadBuilderError> where - DB: Database, + DB: Database + 'a, BestTxs: PayloadTransactions> + 'a, { let build_started = Instant::now(); @@ -764,11 +778,6 @@ where "building new payload" ); - let mut db = State::builder() - .with_database(db) - .with_bundle_update() - .build(); - // Build next block env attributes let next_block_attrs = MorphNextBlockEnvAttributes { inner: NextBlockEnvAttributes { @@ -790,7 +799,7 @@ where // Create block builder let mut builder = ctx .evm_config - .builder_for_next_block(&mut db, ctx.parent(), next_block_attrs) + .builder_for_next_block(db, ctx.parent(), next_block_attrs) .map_err(PayloadBuilderError::other)?; // If the engine tree provided a sparse-trie state root handle, wire the @@ -798,10 +807,8 @@ where // during execution. The final `state_root()` recv() at finish time will // return quickly since most work is done concurrently. if let Some(handle) = state_root_handle.as_mut() { - builder - .evm_mut() - .db_mut() - .set_state_hook(Some(Box::new(handle.take_state_hook()))); + let mut hook = handle.take_state_hook(); + builder.set_state_hook(move |state| hook.on_state(state)); } // 1. Apply pre-execution changes (system contracts, etc.) @@ -815,8 +822,12 @@ where ctx.parent().next_l1_msg_index, ctx.builder_config.max_da_block_size, ); - let base_fee = builder.evm().block().basefee(); - let block_gas_limit = builder.evm().block().gas_limit(); + let base_fee = builder.evm_env().block_base_fee(); + let block_gas_limit = builder + .evm_env() + .block_env() + .gas_limit + .saturating_to::(); // Create breaker for early exit from pool transaction execution let breaker = ctx.builder_config.breaker(block_gas_limit); @@ -880,31 +891,28 @@ where // Read withdraw_trie_root from L2MessageQueue contract storage // This must be done before finish() consumes the builder let withdraw_trie_root = - read_withdraw_trie_root(builder.evm_mut().db_mut()).map_err(|err| { + read_withdraw_trie_root(builder.evm_mut().state_mut()).map_err(|err| { PayloadBuilderError::other(MorphPayloadBuilderError::Storage(err.to_string())) })?; // 6. Finish building the block. // - // When `trie_handle` is provided, drop the state hook to signal FinishedStateUpdates - // to the background sparse trie task (via StateHookSender's Drop impl), then wait for - // the final root. Fall back to synchronous state root if the task fails. + // Finishing consumes the executor, which drops the state hook and so signals + // FinishedStateUpdates to the background sparse trie task before the closure waits + // for the final root. Fall back to a synchronous state root if the task fails. let BlockBuilderOutcome { execution_result, + execution_state, hashed_state, trie_updates, mut block, block_access_list: _, } = if let Some(mut handle) = state_root_handle { - builder.evm_mut().db_mut().set_state_hook(None); - match handle.state_root() { - Ok(outcome) => builder.finish( - state_provider, - Some(( - outcome.state_root, - Arc::unwrap_or_clone(outcome.trie_updates), - )), - )?, + builder.finish_with_state_root(state_provider, |_| match handle.state_root() { + Ok(outcome) => Ok(Some(( + outcome.state_root, + Arc::unwrap_or_clone(outcome.trie_updates), + ))), Err(err) => { tracing::warn!( target: "payload_builder", @@ -912,9 +920,9 @@ where %err, "sparse trie task failed, falling back to sync state root", ); - builder.finish(state_provider, None)? + Ok(None) } - } + })? } else { builder.finish(state_provider, None)? }; @@ -963,7 +971,7 @@ where let execution_output = BlockExecutionOutput { result: execution_result, - state: db.take_bundle(), + state: execution_state, }; let executed = BuiltPayloadExecutedBlock { @@ -1228,65 +1236,35 @@ mod tests { // read_withdraw_trie_root tests (requires mock DB) // ========================================================================= - struct MockDb { - storage_value: U256, - } - - impl revm::Database for MockDb { - type Error = std::convert::Infallible; - - fn basic( - &mut self, - _address: alloy_primitives::Address, - ) -> Result, Self::Error> { - Ok(None) - } - - fn code_by_hash( - &mut self, - _code_hash: B256, - ) -> Result { - Ok(revm::bytecode::Bytecode::default()) - } - - fn storage( - &mut self, - _address: alloy_primitives::Address, - _index: U256, - ) -> Result { - Ok(self.storage_value) - } - - fn block_hash(&mut self, _number: u64) -> Result { - Ok(B256::ZERO) - } + fn state_with_withdraw_trie_root(value: U256) -> State<'static> { + let mut db = evm2::evm::InMemoryDB::default(); + db.insert_account_storage( + &L2_MESSAGE_QUEUE_ADDRESS, + &L2_MESSAGE_QUEUE_WITHDRAW_TRIE_ROOT_SLOT, + &value, + ); + State::new(db) } #[test] fn test_read_withdraw_trie_root_zero() { - let mut db = MockDb { - storage_value: U256::ZERO, - }; - let root = read_withdraw_trie_root(&mut db).unwrap(); + let mut state = state_with_withdraw_trie_root(U256::ZERO); + let root = read_withdraw_trie_root(&mut state).unwrap(); assert_eq!(root, B256::ZERO); } #[test] fn test_read_withdraw_trie_root_nonzero() { let expected = B256::from([0xAB; 32]); - let mut db = MockDb { - storage_value: expected.into(), - }; - let root = read_withdraw_trie_root(&mut db).unwrap(); + let mut state = state_with_withdraw_trie_root(expected.into()); + let root = read_withdraw_trie_root(&mut state).unwrap(); assert_eq!(root, expected); } #[test] fn test_read_withdraw_trie_root_max_value() { - let mut db = MockDb { - storage_value: U256::MAX, - }; - let root = read_withdraw_trie_root(&mut db).unwrap(); + let mut state = state_with_withdraw_trie_root(U256::MAX); + let root = read_withdraw_trie_root(&mut state).unwrap(); assert_eq!(root, B256::from(U256::MAX)); } } diff --git a/crates/payload/builder/src/error.rs b/crates/payload/builder/src/error.rs index 6c3d8511..2572a97e 100644 --- a/crates/payload/builder/src/error.rs +++ b/crates/payload/builder/src/error.rs @@ -45,7 +45,7 @@ pub enum MorphPayloadBuilderError { block_gas_limit: u64, }, - /// Generic storage error (e.g. from revm EvmDatabaseError, ProviderError). + /// Generic storage error (e.g. an EVM database error or a `ProviderError`). #[error("storage error: {0}")] Storage(String), } diff --git a/crates/proofs-exex/src/lib.rs b/crates/proofs-exex/src/lib.rs index 036b8853..72d36b98 100644 --- a/crates/proofs-exex/src/lib.rs +++ b/crates/proofs-exex/src/lib.rs @@ -798,7 +798,7 @@ mod tests { use reth_execution_types::{Chain, ExecutionOutcome}; use reth_primitives_traits::RecoveredBlock; use reth_trie::{ - ComputedTrieData, HashedPostStateSorted, LazyTrieData, updates::TrieUpdatesSorted, + HashedPostStateSorted, LazyTrieData, SortedTrieData, updates::TrieUpdatesSorted, }; use super::*; @@ -839,7 +839,7 @@ mod tests { } blocks.push(b); - let data = LazyTrieData::ready(ComputedTrieData::new( + let data = LazyTrieData::ready(SortedTrieData::new( Arc::new(HashedPostStateSorted::default()), Arc::new(TrieUpdatesSorted::default()), )); @@ -1376,7 +1376,7 @@ mod tests { hash_for_num(num.saturating_sub(1)), NumHash::new(num, hash_for_num(num)), ), - trie_data: LazyTrieData::ready(ComputedTrieData::new( + trie_data: LazyTrieData::ready(SortedTrieData::new( Arc::new(HashedPostStateSorted::default()), Arc::new(TrieUpdatesSorted::default()), )), diff --git a/crates/proofs-exex/src/sync_target.rs b/crates/proofs-exex/src/sync_target.rs index f1707b7d..03c56a5c 100644 --- a/crates/proofs-exex/src/sync_target.rs +++ b/crates/proofs-exex/src/sync_target.rs @@ -340,7 +340,7 @@ mod tests { use alloy_consensus::private::alloy_primitives::B256; use alloy_eips::{NumHash, eip1898::BlockWithParent}; use reth_trie::{ - ComputedTrieData, HashedPostStateSorted, LazyTrieData, updates::TrieUpdatesSorted, + HashedPostStateSorted, LazyTrieData, SortedTrieData, updates::TrieUpdatesSorted, }; use super::*; @@ -359,7 +359,7 @@ mod tests { fn dummy_cached_data(num: u64) -> CachedBlockTrieData { CachedBlockTrieData { block_with_parent: block_with_parent(num), - trie_data: LazyTrieData::ready(ComputedTrieData::new( + trie_data: LazyTrieData::ready(SortedTrieData::new( Arc::new(HashedPostStateSorted::default()), Arc::new(TrieUpdatesSorted::default()), )), diff --git a/crates/proofs/src/api.rs b/crates/proofs/src/api.rs index 792c69c7..d8f53b74 100644 --- a/crates/proofs/src/api.rs +++ b/crates/proofs/src/api.rs @@ -201,9 +201,6 @@ pub trait MorphProofsStore: Send + Sync + Debug { 'db: 'tx; /// Store a batch of trie updates. - /// - /// If wiped is true, the entire storage trie is wiped, but this is unsupported going forward, - /// so should only happen for legacy reasons. fn store_trie_updates( &self, block_ref: BlockWithParent, diff --git a/crates/proofs/src/batch_provider.rs b/crates/proofs/src/batch_provider.rs index 3bfd33e4..a8600caa 100644 --- a/crates/proofs/src/batch_provider.rs +++ b/crates/proofs/src/batch_provider.rs @@ -4,7 +4,7 @@ use std::fmt::Debug; use alloy_primitives::{ - keccak256, + Address, B256, BlockNumber, Bytes, StorageValue, keccak256, map::{B256Map, HashMap}, }; use derive_more::Constructor; @@ -13,21 +13,19 @@ use reth_provider::{ AccountReader, BlockHashReader, BytecodeReader, HashedPostStateProvider, ProviderError, ProviderResult, StateProofProvider, StateProvider, StateRootProvider, StorageRootProvider, }; -use reth_revm::{ - db::BundleState, - primitives::{Address, B256, Bytes, StorageValue, alloy_primitives::BlockNumber}, -}; use reth_trie::{ StateRoot, StorageRoot, TrieType, hashed_cursor::{HashedCursor, HashedPostStateCursorFactory, zero_destroyed_account_storage}, metrics::TrieRootMetrics, proof, + proof_v2::MultiProofCalculator, trie_cursor::InMemoryTrieCursorFactory, witness::TrieWitness, }; use reth_trie_common::{ - AccountProof, ExecutionWitnessMode, HashedPostState, HashedPostStateSorted, HashedStorage, - KeccakKeyHasher, MultiProof, MultiProofTargets, StorageMultiProof, StorageProof, TrieInput, + AccountProof, DecodedMultiProofV2, ExecutionWitnessMode, HashedPostState, + HashedPostStateSorted, HashedStorage, KeccakKeyHasher, MultiProof, MultiProofTargets, + MultiProofTargetsV2, StorageMultiProof, StorageProof, TrieInput, bundle_state::BundleState, updates::TrieUpdates, }; @@ -177,14 +175,14 @@ impl StorageRootProvider for MorphProofsBatchStatePr HashMap::from_iter([(hashed_address, hashed_storage.into_sorted())]), ); let (trie_factory, hashed_factory) = self.factories(); - proof::StorageProof::new(trie_factory, hashed_factory.clone(), address) - .with_hashed_cursor_factory(HashedPostStateCursorFactory::new( - hashed_factory, - &state_sorted, - )) - .with_prefix_set_mut(prefix_set) - .storage_proof(slot) - .map_err(ProviderError::from) + proof::StorageProof::new( + trie_factory, + HashedPostStateCursorFactory::new(hashed_factory, &state_sorted), + address, + ) + .with_prefix_set_mut(prefix_set) + .storage_proof(slot) + .map_err(ProviderError::from) } fn storage_multiproof( @@ -201,14 +199,14 @@ impl StorageRootProvider for MorphProofsBatchStatePr HashMap::from_iter([(hashed_address, hashed_storage.into_sorted())]), ); let (trie_factory, hashed_factory) = self.factories(); - proof::StorageProof::new(trie_factory, hashed_factory.clone(), address) - .with_hashed_cursor_factory(HashedPostStateCursorFactory::new( - hashed_factory, - &state_sorted, - )) - .with_prefix_set_mut(prefix_set) - .storage_multiproof(targets) - .map_err(ProviderError::from) + proof::StorageProof::new( + trie_factory, + HashedPostStateCursorFactory::new(hashed_factory, &state_sorted), + address, + ) + .with_prefix_set_mut(prefix_set) + .storage_multiproof(targets) + .map_err(ProviderError::from) } } @@ -222,15 +220,13 @@ impl StateProofProvider for MorphProofsBatchStatePro let nodes_sorted = input.nodes.into_sorted(); let state_sorted = input.state.into_sorted(); let (trie_factory, hashed_factory) = self.factories(); - proof::Proof::new(trie_factory.clone(), hashed_factory.clone()) - .with_trie_cursor_factory(InMemoryTrieCursorFactory::new(trie_factory, &nodes_sorted)) - .with_hashed_cursor_factory(HashedPostStateCursorFactory::new( - hashed_factory, - &state_sorted, - )) - .with_prefix_sets_mut(input.prefix_sets) - .account_proof(address, slots) - .map_err(ProviderError::from) + proof::Proof::new( + InMemoryTrieCursorFactory::new(trie_factory, &nodes_sorted), + HashedPostStateCursorFactory::new(hashed_factory, &state_sorted), + ) + .with_prefix_sets_mut(input.prefix_sets) + .account_proof(address, slots) + .map_err(ProviderError::from) } fn multiproof( @@ -241,15 +237,31 @@ impl StateProofProvider for MorphProofsBatchStatePro let nodes_sorted = input.nodes.into_sorted(); let state_sorted = input.state.into_sorted(); let (trie_factory, hashed_factory) = self.factories(); - proof::Proof::new(trie_factory.clone(), hashed_factory.clone()) - .with_trie_cursor_factory(InMemoryTrieCursorFactory::new(trie_factory, &nodes_sorted)) - .with_hashed_cursor_factory(HashedPostStateCursorFactory::new( - hashed_factory, - &state_sorted, - )) - .with_prefix_sets_mut(input.prefix_sets) - .multiproof(targets) - .map_err(ProviderError::from) + proof::Proof::new( + InMemoryTrieCursorFactory::new(trie_factory, &nodes_sorted), + HashedPostStateCursorFactory::new(hashed_factory, &state_sorted), + ) + .with_prefix_sets_mut(input.prefix_sets) + .multiproof(targets) + .map_err(ProviderError::from) + } + + fn multiproof_v2( + &self, + targets: MultiProofTargetsV2, + _requires_masks: bool, + ) -> ProviderResult { + // The session's versioned trie at `block_number` is the exact trie persisted for that + // block, so masks always match and `requires_masks` needs no special handling. + let (trie_factory, hashed_factory) = self.factories(); + MultiProofCalculator::new( + trie_factory, + hashed_factory, + Default::default(), + Default::default(), + ) + .multiproof(targets) + .map_err(ProviderError::from) } fn witness( @@ -261,16 +273,14 @@ impl StateProofProvider for MorphProofsBatchStatePro let nodes_sorted = input.nodes.into_sorted(); let state_sorted = input.state.into_sorted(); let (trie_factory, hashed_factory) = self.factories(); - let result: B256Map = TrieWitness::new(trie_factory.clone(), hashed_factory.clone()) - .with_trie_cursor_factory(InMemoryTrieCursorFactory::new(trie_factory, &nodes_sorted)) - .with_hashed_cursor_factory(HashedPostStateCursorFactory::new( - hashed_factory, - &state_sorted, - )) - .with_prefix_sets_mut(input.prefix_sets) - .always_include_root_node() - .compute(target) - .map_err(ProviderError::from)?; + let result: B256Map = TrieWitness::new( + InMemoryTrieCursorFactory::new(trie_factory, &nodes_sorted), + HashedPostStateCursorFactory::new(hashed_factory, &state_sorted), + ) + .with_prefix_sets_mut(input.prefix_sets) + .always_include_root_node() + .compute(target) + .map_err(ProviderError::from)?; Ok(result.into_values().collect()) } } @@ -325,16 +335,51 @@ impl BytecodeReader for MorphProofsBatchStateProvide #[cfg(test)] mod tests { + use std::sync::Arc; + use alloy_eips::BlockNumHash; use alloy_primitives::U256; use reth_provider::noop::NoopProvider; - use reth_revm::{ - db::{AccountStatus, BundleAccount}, - state::AccountInfo, - }; + use reth_trie_common::bundle_state::{AccountStatus, BundleAccount}; use super::*; - use crate::{InMemoryProofsStorage, MorphProofsBatchStore, MorphProofsInitialStateStore}; + use crate::{ + InMemoryProofsStorage, MdbxProofsStorage, MorphProofsBatchStore, + MorphProofsInitialStateStore, MorphProofsStore, + provider::tests::{assert_multiproof_v2_matches_proof, store_two_contracts}, + }; + + fn assert_session_multiproof_v2_matches_proof(storage: S) + where + S: MorphProofsStore + MorphProofsBatchStore + MorphProofsInitialStateStore + Clone, + { + let (state_root, contracts) = store_two_contracts(&storage); + + storage + .with_batch_session(|session| { + let provider = MorphProofsBatchStateProviderRef::new( + Box::::default(), + session, + 1, + ); + assert_multiproof_v2_matches_proof(&provider, state_root, &contracts); + Ok(()) + }) + .unwrap(); + } + + #[test] + fn multiproof_v2_matches_proof_in_memory() { + assert_session_multiproof_v2_matches_proof(InMemoryProofsStorage::new()); + } + + #[test] + fn multiproof_v2_matches_proof_in_mdbx() { + let directory = tempfile::tempdir().unwrap(); + assert_session_multiproof_v2_matches_proof(Arc::new( + MdbxProofsStorage::new(directory.path()).unwrap(), + )); + } #[test] fn hashed_post_state_zeros_parent_storage_for_destroyed_account() { @@ -354,7 +399,7 @@ mod tests { bundle_state.state.insert( address, BundleAccount::new( - Some(AccountInfo::default()), + Some(Default::default()), None, Default::default(), AccountStatus::Destroyed, diff --git a/crates/proofs/src/db/models/mod.rs b/crates/proofs/src/db/models/mod.rs index de5b9786..fdd6661f 100644 --- a/crates/proofs/src/db/models/mod.rs +++ b/crates/proofs/src/db/models/mod.rs @@ -14,20 +14,88 @@ pub use storage::*; mod change_set; mod kv; mod metadata; -use std::fmt; use alloy_primitives::B256; pub use change_set::*; pub use kv::*; pub use metadata::*; use reth_db::{ - TableSet, TableType, TableViewer, - table::{DupSort, TableInfo}, - tables, + TableSet, + table::{DupSort, Table, TableInfo}, }; use reth_primitives_traits::Account; use reth_trie_common::{BranchNodeCompact, StoredNibbles}; +/// Declares this database's tables: a marker type with a [`Table`] impl per entry, plus the +/// [`Tables`] set passed to `init_db_for`. +/// +/// `reth_db::tables!` cannot be used here: it sets [`Table::TABLE`] to the enum it generates, +/// while that constant has to name an entry of reth's own `Tables`. Tables defined outside that +/// enum leave it at its default of `None`, which makes MDBX resolve them by name. +macro_rules! tables { + (@is_dupsort) => { false }; + (@is_dupsort $subkey:ty) => { true }; + + ($($(#[$attr:meta])* table $name:ident { + type Key = $key:ty; + type Value = $value:ty; + $(type SubKey = $subkey:ty;)? + })*) => { + $( + $(#[$attr])* + #[derive(Debug)] + pub enum $name {} + + impl Table for $name { + const NAME: &'static str = stringify!($name); + const DUPSORT: bool = tables!(@is_dupsort $($subkey)?); + + type Key = $key; + type Value = $value; + } + + $( + impl DupSort for $name { + type SubKey = $subkey; + } + )? + )* + + /// A table in this database. + #[derive(Clone, Copy, Debug)] + pub enum Tables { + $( + #[doc = concat!("The [`", stringify!($name), "`] table.")] + $name, + )* + } + + impl TableInfo for Tables { + fn name(&self) -> &'static str { + match self { + $(Self::$name => stringify!($name),)* + } + } + + fn is_dupsort(&self) -> bool { + match self { + $(Self::$name => tables!(@is_dupsort $($subkey)?),)* + } + } + } + + impl TableSet for Tables { + fn tables() -> Box>> { + Box::new( + [$(Self::$name,)*] + .into_iter() + .map(|table| Box::new(table) as Box), + ) + } + } + }; +} + tables! { /// Stores historical branch nodes for the account state trie. /// diff --git a/crates/proofs/src/db/store.rs b/crates/proofs/src/db/store.rs index 369ded65..a9abb825 100644 --- a/crates/proofs/src/db/store.rs +++ b/crates/proofs/src/db/store.rs @@ -1,4 +1,4 @@ -use std::{collections::BTreeMap, ops::RangeBounds, path::Path, time::Duration}; +use std::{ops::RangeBounds, path::Path, time::Duration}; use alloy_eips::{BlockNumHash, NumHash, eip1898::BlockWithParent}; use alloy_primitives::{B256, U256, map::HashMap}; @@ -10,7 +10,6 @@ use reth_db::{ transaction::{DbTx, DbTxMut}, }; use reth_primitives_traits::Account; -use reth_trie::{hashed_cursor::HashedCursor, trie_cursor::TrieCursor}; use reth_trie_common::{ BranchNodeCompact, HashedPostState, Nibbles, StoredNibbles, updates::{StorageTrieUpdates, TrieUpdates}, @@ -33,8 +32,8 @@ use crate::{ cursor::Dup, models::{ AccountTrieHistory, BlockChangeSet, ChangeSet, HashedAccountHistory, - HashedStorageHistory, HashedStorageKey, IntoKV, MaybeDeleted, StorageTrieHistory, - StorageTrieKey, StorageValue, VersionedValue, + HashedStorageHistory, HashedStorageKey, IntoKV, StorageTrieHistory, StorageTrieKey, + StorageValue, VersionedValue, }, }, }; @@ -603,50 +602,6 @@ impl MdbxProofsStorage { Ok(deleted_count) } - /// Tombstone every key returned by `next`, then overlay `new_entries` so collisions - /// resolve in favor of `new_entries`, and `append_dup` the merged set in sorted-key order at - /// `block_number`. Used by the wipe branches of `store_trie_updates_for_block` to keep new - /// slots / nodes that arrive in the same block as a `wiped`/`is_deleted` entry — - /// `HashedStorage::from_plain_storage` sets `wiped = was_destroyed()` (true for - /// `DestroyedChanged`), so a SELFDESTRUCT + same-block recreate produces both at once. - fn wipe_and_overlay( - &self, - tx: &(impl DbTxMut + DbTx), - block_number: u64, - hashed_address: B256, - mut next: Next, - new_entries: I, - ) -> MorphProofsStorageResult> - where - T: Table> + DupSort, - Next: FnMut() -> MorphProofsStorageResult>, - I: IntoIterator)>, - (B256, K, Option): IntoKV, - T::Key: Clone, - K: Ord, - { - let mut merged: BTreeMap> = BTreeMap::new(); - while let Some((k, _vv)) = next()? { - merged.insert(k, None); - } - for (k, v) in new_entries { - merged.insert(k, v); - } - - let mut cur = tx.cursor_dup_write::()?; - let mut keys: Vec = Vec::with_capacity(merged.len()); - for (k, value) in merged { - let key: T::Key = (hashed_address, k, Option::::None).into_key(); - let vv: T::Value = VersionedValue { - block_number, - value: MaybeDeleted(value), - }; - cur.append_dup(key.clone(), vv)?; - keys.push(key); - } - Ok(keys) - } - /// Collect versioned history over `block_range` using `BlockChangeSet`. fn collect_history_ranged( &self, @@ -765,27 +720,6 @@ impl MdbxProofsStorage { let mut storage_trie_keys = Vec::::with_capacity(storage_trie_len); for (hashed_address, nodes) in sorted_trie_updates.storage_tries_ref() { - if nodes.is_deleted && append_mode { - // Lookback must use the active tx so it sees uncommitted writes from earlier - // blocks in the same batch session. Opening a fresh RO tx here would read the - // pre-batch committed snapshot and emit wrong tombstones for wipe blocks whose - // parent is staged in the same batch. - let mut ro = MdbxTrieCursor::::new( - tx.cursor_dup_read::()?, - block_number - 1, - Some(*hashed_address), - ); - let keys = self.wipe_and_overlay( - tx, - block_number, - *hashed_address, - || Ok(ro.next()?), - nodes.storage_nodes_ref().iter().cloned(), - )?; - storage_trie_keys.extend(keys); - continue; - } - let keys = self.persist_history_batch( tx, block_number, @@ -801,26 +735,6 @@ impl MdbxProofsStorage { let mut hashed_storage_keys = Vec::::with_capacity(hashed_storage_len); for (hashed_address, storage) in sorted_post_state.storages { - if append_mode && storage.is_wiped() { - // See lookback note above: must use the active tx, not a fresh RO tx. - let mut ro = MdbxStorageCursor::new( - tx.cursor_dup_read::()?, - block_number - 1, - hashed_address, - ); - let keys = self.wipe_and_overlay( - tx, - block_number, - hashed_address, - || Ok(ro.next()?), - storage - .storage_slots_ref() - .iter() - .map(|(slot, val)| (*slot, Some(StorageValue(*val)))), - )?; - hashed_storage_keys.extend(keys); - continue; - } let keys = self.persist_history_batch( tx, block_number, @@ -1138,8 +1052,6 @@ impl MorphProofsStore for MdbxProofsStorage { .entry(key.hashed_address) .or_insert_with(StorageTrieUpdates::default); - // handle is_deleted scenario - // Issue: https://github.com/op-rs/op-reth/issues/323 if let Some(value) = entry { stu.storage_nodes.insert(key.path.0, value); } else { @@ -1178,8 +1090,6 @@ impl MorphProofsStore for MdbxProofsStorage { let hs = post_state.storages.entry(key.hashed_address).or_default(); - // handle wiped storage scenario - // Issue: https://github.com/op-rs/op-reth/issues/323 if let Some(value) = entry { hs.storage.insert(key.hashed_storage_key, value.0); } else { @@ -1533,6 +1443,7 @@ mod tests { }; use reth_trie::{ BranchNodeCompact, HashedPostStateSorted, HashedStorage, Nibbles, StoredNibbles, + hashed_cursor::HashedCursor, updates::{StorageTrieUpdates, TrieUpdatesSorted}, }; use tempfile::TempDir; @@ -1540,7 +1451,7 @@ mod tests { use super::*; use crate::db::{ StorageTrieKey, - models::{AccountTrieHistory, StorageTrieHistory}, + models::{AccountTrieHistory, MaybeDeleted, StorageTrieHistory}, }; const B0: u64 = 0; @@ -3698,301 +3609,69 @@ mod tests { assert!(vv.value.0.is_none(), "expected storage trie deletion"); } + /// A destroyed account's storage reaches the store as one zero-valued update per slot, so + /// a block must hide those slots from its own version onwards while leaving earlier versions + /// and unrelated accounts readable. #[test] - fn store_trie_updates_wiped_storage_trie_nodes() { + fn store_trie_updates_zero_valued_slots_hide_destroyed_storage() { let dir = TempDir::new().unwrap(); let store = MdbxProofsStorage::new(dir.path()).expect("env"); - let addr_wiped = B256::from([0x10; 32]); + let addr_destroyed = B256::from([0x01; 32]); let addr_live = B256::from([0xF0; 32]); - // Seed some storage-trie nodes at block 0 for the address that will be wiped. - let p1 = Nibbles::from_nibbles_unchecked([0x01, 0x02]); - let p2 = Nibbles::from_nibbles_unchecked([0x0A, 0x0B, 0x0C]); - let n1 = BranchNodeCompact::default(); - let n2 = BranchNodeCompact::default(); - - store - .store_storage_branches(addr_wiped, vec![(p1, Some(n1)), (p2, Some(n2))]) - .expect("seed wiped addr trie nodes"); - - // Build a BlockStateDiff that wipes addr_wiped's storage trie, and - // also adds a normal storage-trie node for addr_live. - const BLOCK: BlockWithParent = - BlockWithParent::new(B256::ZERO, NumHash::new(123, B256::ZERO)); - let mut diff_trie_updates = TrieUpdates::default(); - - // Wipe for addr_wiped - let mut wiped_updates = StorageTrieUpdates::default(); - wiped_updates.set_deleted(true); - diff_trie_updates - .storage_tries - .insert(addr_wiped, wiped_updates); - - // Normal update for addr_live - let live_path = Nibbles::from_nibbles_unchecked([0xEE, 0xFF]); - let live_node = BranchNodeCompact::default(); - let mut live_updates = StorageTrieUpdates::default(); - live_updates.storage_nodes.insert(live_path, live_node); - diff_trie_updates - .storage_tries - .insert(addr_live, live_updates); - - // Execute the store - let diff = BlockStateDiff { - sorted_trie_updates: diff_trie_updates.into_sorted(), - sorted_post_state: HashedPostStateSorted::default(), - }; - store.store_trie_updates(BLOCK, diff).expect("store"); - - // Verify: for addr_wiped, each previously existing path now has a deletion tombstone at - // BLOCK. - { - let tx = store.env.tx().expect("tx"); - let mut cur = tx.new_cursor::().expect("cursor"); - - for path in [p1, p2] { - let key = StorageTrieKey::new(addr_wiped, StoredNibbles::from(path)); - let vv = cur - .seek_by_key_subkey(key, BLOCK.block.number) - .expect("seek") - .expect("exists"); - assert_eq!(vv.block_number, BLOCK.block.number); - assert!( - vv.value.0.is_none(), - "expected tombstone at wipe block for path {path:?}" - ); - } - } - - // Verify: addr_live got its normal node written at BLOCK (not a deletion). - { - let tx = store.env.tx().expect("tx"); - let mut cur = tx.new_cursor::().expect("cursor"); - - let key = StorageTrieKey::new(addr_live, StoredNibbles::from(live_path)); - let vv = cur - .seek_by_key_subkey(key, BLOCK.block.number) - .expect("seek") - .expect("exists"); - assert_eq!(vv.block_number, BLOCK.block.number); - assert!( - vv.value.0.is_some(), - "expected normal node for non-wiped address at BLOCK" - ); - } - } - - /// Mirror of `tests/lib.rs::test_store_trie_updates_with_wiped_storage_and_new_slots` for - /// the storage *trie* path. When `StorageTrieUpdates::is_deleted` is true AND - /// `storage_nodes` is non-empty (the shape revm/reth produce when a contract is destroyed - /// and recreated with a fresh trie in the same block), the wipe branch must tombstone every - /// pre-existing path for the address AND persist the new post-recreation nodes — with new - /// nodes winning on path collision. - #[test] - fn store_trie_updates_wiped_storage_trie_with_new_nodes() { - let dir = TempDir::new().unwrap(); - let store = MdbxProofsStorage::new(dir.path()).expect("env"); - - let addr = B256::from([0x77; 32]); - let pre_path_dropped = Nibbles::from_nibbles_unchecked([0x01, 0x02]); - let pre_path_overwritten = Nibbles::from_nibbles_unchecked([0x0A, 0x0B]); - let new_path_kept = Nibbles::from_nibbles_unchecked([0xCC, 0xDD]); - - store - .store_storage_branches( - addr, - vec![ - (pre_path_dropped, Some(BranchNodeCompact::default())), - (pre_path_overwritten, Some(BranchNodeCompact::default())), - ], - ) - .expect("seed"); - - const BLOCK: BlockWithParent = - BlockWithParent::new(B256::ZERO, NumHash::new(123, B256::ZERO)); - let mut diff_trie_updates = TrieUpdates::default(); - let mut wiped_with_new = StorageTrieUpdates::default(); - wiped_with_new.set_deleted(true); - wiped_with_new - .storage_nodes - .insert(new_path_kept, BranchNodeCompact::default()); - wiped_with_new - .storage_nodes - .insert(pre_path_overwritten, BranchNodeCompact::default()); - diff_trie_updates.storage_tries.insert(addr, wiped_with_new); - - let diff = BlockStateDiff { - sorted_trie_updates: diff_trie_updates.into_sorted(), - sorted_post_state: HashedPostStateSorted::default(), - }; - store.store_trie_updates(BLOCK, diff).expect("store"); - - let tx = store.env.tx().expect("tx"); - let mut cur = tx.new_cursor::().expect("cursor"); - - let dropped_key = StorageTrieKey::new(addr, StoredNibbles::from(pre_path_dropped)); - let dropped_vv = cur - .seek_by_key_subkey(dropped_key, BLOCK.block.number) - .expect("seek") - .expect("tombstone exists"); - assert_eq!(dropped_vv.block_number, BLOCK.block.number); - assert!( - dropped_vv.value.0.is_none(), - "pre-existing path with no new node must tombstone" - ); - - let overwritten_key = StorageTrieKey::new(addr, StoredNibbles::from(pre_path_overwritten)); - let overwritten_vv = cur - .seek_by_key_subkey(overwritten_key, BLOCK.block.number) - .expect("seek") - .expect("overlay exists"); - assert_eq!(overwritten_vv.block_number, BLOCK.block.number); - assert!( - overwritten_vv.value.0.is_some(), - "collision path must reflect the new node, not the wipe tombstone", - ); - - let new_key = StorageTrieKey::new(addr, StoredNibbles::from(new_path_kept)); - let new_vv = cur - .seek_by_key_subkey(new_key, BLOCK.block.number) - .expect("seek") - .expect("new node exists"); - assert_eq!(new_vv.block_number, BLOCK.block.number); - assert!( - new_vv.value.0.is_some(), - "new path must be persisted, not dropped by the wipe" - ); - } - - #[test] - fn store_trie_updates_wiped_storage() { - let dir = TempDir::new().unwrap(); - let store = MdbxProofsStorage::new(dir.path()).expect("env"); - - // We'll pre-seed storage at block 0, then issue a wipe at BLOCK. - const BLOCK: BlockWithParent = - BlockWithParent::new(B256::ZERO, NumHash::new(42, B256::ZERO)); - - let addr = B256::from([0x55; 32]); - let s1 = B256::from([0x01; 32]); - let s2 = B256::from([0x02; 32]); - let v1 = U256::from(111u64); - let v2 = U256::from(222u64); - - // Seed prior storage (block_number = 0 in store_hashed_storages) - store - .store_hashed_storages(addr, vec![(s1, v1), (s2, v2)]) - .expect("seed"); - - // Build BlockStateDiff that marks this address as wiped at BLOCK - let mut diff_post_state = HashedPostState::default(); - - let wiped = reth_trie::HashedStorage::new(true); - - diff_post_state.storages.insert(addr, wiped); - - // Execute - let diff = BlockStateDiff { - sorted_trie_updates: TrieUpdatesSorted::default(), - sorted_post_state: diff_post_state.into_sorted(), - }; - store.store_trie_updates(BLOCK, diff).expect("store"); + let slot_a = B256::from([0xA1; 32]); + let slot_b = B256::from([0xA2; 32]); + let value_a = U256::from(111u64); + let value_b = U256::from(222u64); - // Verify: for each pre-existing slot, there should be a tombstone (MaybeDeleted(None)) at - // BLOCK. - let tx = store.env.tx().expect("tx"); - let mut cur = tx.new_cursor::().expect("cursor"); + let live_slot = B256::from([0xB1; 32]); + let live_value_old = U256::from(333u64); + let live_value_new = U256::from(999u64); - for slot in [s1, s2] { - let key = HashedStorageKey::new(addr, slot); - let vv = cur - .seek_by_key_subkey(key, BLOCK.block.number) - .expect("seek") - .expect("exists"); - assert_eq!(vv.block_number, BLOCK.block.number); - assert!( - vv.value.0.is_none(), - "expected deletion tombstone for slot {:?} at block {}", - slot, - BLOCK.block.number, - ); - } - } - - #[test] - fn store_trie_updates_wiped_and_non_wiped_mixed_order() { - let dir = TempDir::new().unwrap(); - let store = MdbxProofsStorage::new(dir.path()).expect("env"); - - // Choose addresses so that wiped < non_wiped in sort order (your impl sorts by address) - let addr_wiped = B256::from([0x01; 32]); // will sort first - let addr_live = B256::from([0xF0; 32]); // will sort later - - // Slots & values - let ws1 = B256::from([0xA1; 32]); - let ws2 = B256::from([0xA2; 32]); - let wv1 = U256::from(111u64); - let wv2 = U256::from(222u64); - - let ls1 = B256::from([0xB1; 32]); - let lv1_old = U256::from(333u64); - let lv1_new = U256::from(999u64); // will be written at BLOCK - - // Seed prior storage at block 0 for BOTH addresses store - .store_hashed_storages(addr_wiped, vec![(ws1, wv1), (ws2, wv2)]) - .expect("seed wiped addr"); + .store_hashed_storages(addr_destroyed, vec![(slot_a, value_a), (slot_b, value_b)]) + .expect("seed destroyed addr"); store - .store_hashed_storages(addr_live, vec![(ls1, lv1_old)]) + .store_hashed_storages(addr_live, vec![(live_slot, live_value_old)]) .expect("seed live addr"); - // Build diff: wiped first (by address sort), then non-wiped with a write const BLOCK: BlockWithParent = BlockWithParent::new(B256::ZERO, NumHash::new(77, B256::ZERO)); let mut diff_post_state = HashedPostState::default(); + diff_post_state.storages.insert( + addr_destroyed, + reth_trie::HashedStorage::from_iter([(slot_a, U256::ZERO), (slot_b, U256::ZERO)]), + ); + diff_post_state.storages.insert( + addr_live, + reth_trie::HashedStorage::from_iter([(live_slot, live_value_new)]), + ); - // Wiped storage for addr_wiped - let wiped = reth_trie::HashedStorage::new(true); - diff_post_state.storages.insert(addr_wiped, wiped); - - // Non-wiped storage for addr_live (append new value) - let mut live = reth_trie::HashedStorage::default(); - live.storage.insert(ls1, lv1_new); - diff_post_state.storages.insert(addr_live, live); - - // Execute let diff = BlockStateDiff { sorted_trie_updates: TrieUpdatesSorted::default(), sorted_post_state: diff_post_state.into_sorted(), }; store.store_trie_updates(BLOCK, diff).expect("store"); - // Verify: wiped address got tombstones at BLOCK for each pre-existing slot { let tx = store.env.tx().expect("tx"); let mut cur = tx.new_cursor::().expect("cursor"); - for slot in [ws1, ws2] { - let key = HashedStorageKey::new(addr_wiped, slot); + for slot in [slot_a, slot_b] { + let key = HashedStorageKey::new(addr_destroyed, slot); let vv = cur .seek_by_key_subkey(key, BLOCK.block.number) .expect("seek") .expect("exists"); assert_eq!(vv.block_number, BLOCK.block.number); - assert!( - vv.value.0.is_none(), - "expected deletion tombstone for wiped slot {:?} at block {}", - slot, - BLOCK.block.number, + assert_eq!( + vv.value.0.map(|value| value.0), + Some(U256::ZERO), + "expected zero-valued version for destroyed slot {slot:?}" ); } - } - // Verify: non-wiped address got the new value at BLOCK (not a deletion) - { - let tx = store.env.tx().expect("tx"); - let mut cur = tx.new_cursor::().expect("cursor"); - let key = HashedStorageKey::new(addr_live, ls1); + let key = HashedStorageKey::new(addr_live, live_slot); let vv = cur .seek_by_key_subkey(key, BLOCK.block.number) .expect("seek") @@ -4000,10 +3679,33 @@ mod tests { assert_eq!(vv.block_number, BLOCK.block.number); let inner = vv.value.0.as_ref().expect("Some(StorageValue)"); assert_eq!( - inner.0, lv1_new, - "expected updated value for non-wiped address" + inner.0, live_value_new, + "expected updated value for live address" ); } + + let mut at_block = store + .storage_hashed_cursor(addr_destroyed, BLOCK.block.number) + .expect("cursor at block"); + assert_eq!( + at_block.seek(B256::ZERO).expect("seek"), + None, + "zero-valued slots must read as deleted at the destroying block" + ); + + let mut before_block = store + .storage_hashed_cursor(addr_destroyed, BLOCK.block.number - 1) + .expect("cursor before block"); + assert_eq!( + before_block.seek(B256::ZERO).expect("seek"), + Some((slot_a, value_a)), + "earlier versions must stay readable" + ); + assert_eq!( + before_block.next().expect("next"), + Some((slot_b, value_b)), + "earlier versions must stay readable" + ); } #[test] diff --git a/crates/proofs/src/in_memory.rs b/crates/proofs/src/in_memory.rs index be9be05d..d4114f9b 100644 --- a/crates/proofs/src/in_memory.rs +++ b/crates/proofs/src/in_memory.rs @@ -92,37 +92,6 @@ impl InMemoryStorageInner { } for (hashed_address, storage) in &block_state_diff.sorted_post_state.storages { - // Handle wiped storage: iterate all existing values and mark them as deleted - // This is an expensive operation and should never happen for blocks going forward. - if storage.wiped { - // Collect latest values for each slot up to the current block - let mut slot_to_latest: std::collections::BTreeMap = - std::collections::BTreeMap::new(); - - for ((block, address, slot), value) in &self.hashed_storages { - if *block < block_number && *address == *hashed_address { - if let Some((existing_block, _)) = slot_to_latest.get(slot) { - if *block > *existing_block { - slot_to_latest.insert(*slot, (*block, *value)); - } - } else { - slot_to_latest.insert(*slot, (*block, *value)); - } - } - } - - // Store zero values for all non-zero slots to mark them as deleted - for (slot, (_, value)) in slot_to_latest { - if !value.is_zero() { - self.hashed_storages - .insert((block_number, *hashed_address, slot), U256::ZERO); - result.hashed_storages_written_total += 1; - } - } - } - // Persist any new slots that arrive in the same block as the wipe (e.g. SELFDESTRUCT - // + same-block re-CREATE2 produces `wiped = true` together with fresh - // `storage_slots_ref()` for the recreated contract). Mirrors the MDBX backend. for (slot, value) in storage.storage_slots_ref() { self.hashed_storages .insert((block_number, *hashed_address, *slot), *value); diff --git a/crates/proofs/src/live.rs b/crates/proofs/src/live.rs index d2fbb71d..f2a09d6c 100644 --- a/crates/proofs/src/live.rs +++ b/crates/proofs/src/live.rs @@ -4,12 +4,12 @@ use std::{sync::Arc, time::Instant}; use alloy_eips::{BlockNumHash, NumHash, eip1898::BlockWithParent}; use derive_more::Constructor; -use reth_evm::{ConfigureEvm, execute::Executor}; +use reth_evm::{ConfigureEvm, database::StateProviderDatabase, execute::Executor}; use reth_primitives_traits::{AlloyBlockHeader, BlockTy, NodePrimitives, RecoveredBlock}; use reth_provider::{ - DatabaseProviderFactory, HashedPostStateProvider, StateProviderFactory, StateRootProvider, + DatabaseProviderFactory, HashedPostStateProvider, StateProvider, StateProviderFactory, + StateRootProvider, }; -use reth_revm::database::StateProviderDatabase; use reth_trie_common::{HashedPostStateSorted, updates::TrieUpdatesSorted}; use tracing::{info, warn}; @@ -89,7 +89,7 @@ where parent_block_number, ); - let db = StateProviderDatabase::new(&state_provider); + let db = StateProviderDatabase::new((&state_provider).into_evm_state_provider()); let block_executor = self.evm_config.batch_executor(db); let execution_result = block_executor.execute(block)?; @@ -405,7 +405,7 @@ where parent_block_number, ); - let db = StateProviderDatabase::new(&state_provider); + let db = StateProviderDatabase::new((&state_provider).into_evm_state_provider()); let block_executor = self.evm_config.batch_executor(db); let execution_result = block_executor.execute(block)?; diff --git a/crates/proofs/src/proof.rs b/crates/proofs/src/proof.rs index 1e1889dc..fad318a1 100644 --- a/crates/proofs/src/proof.rs +++ b/crates/proofs/src/proof.rs @@ -120,14 +120,12 @@ where let nodes_sorted = input.nodes.into_sorted(); let state_sorted = input.state.into_sorted(); let (trie_factory, hashed_factory) = from_tx(storage, tx, block_number); - Proof::new(trie_factory.clone(), hashed_factory.clone()) - .with_trie_cursor_factory(InMemoryTrieCursorFactory::new(trie_factory, &nodes_sorted)) - .with_hashed_cursor_factory(HashedPostStateCursorFactory::new( - hashed_factory, - &state_sorted, - )) - .with_prefix_sets_mut(input.prefix_sets) - .account_proof(address, slots) + Proof::new( + InMemoryTrieCursorFactory::new(trie_factory, &nodes_sorted), + HashedPostStateCursorFactory::new(hashed_factory, &state_sorted), + ) + .with_prefix_sets_mut(input.prefix_sets) + .account_proof(address, slots) } fn overlay_multiproof( @@ -153,14 +151,12 @@ where let nodes_sorted = input.nodes.into_sorted(); let state_sorted = input.state.into_sorted(); let (trie_factory, hashed_factory) = from_tx(storage, tx, block_number); - Proof::new(trie_factory.clone(), hashed_factory.clone()) - .with_trie_cursor_factory(InMemoryTrieCursorFactory::new(trie_factory, &nodes_sorted)) - .with_hashed_cursor_factory(HashedPostStateCursorFactory::new( - hashed_factory, - &state_sorted, - )) - .with_prefix_sets_mut(input.prefix_sets) - .multiproof(targets) + Proof::new( + InMemoryTrieCursorFactory::new(trie_factory, &nodes_sorted), + HashedPostStateCursorFactory::new(hashed_factory, &state_sorted), + ) + .with_prefix_sets_mut(input.prefix_sets) + .multiproof(targets) } } @@ -187,7 +183,6 @@ pub trait DatabaseStorageProof<'tx, S: MorphProofsStore + 'tx> { impl<'tx, S> DatabaseStorageProof<'tx, S> for proof::StorageProof< - 'static, MorphProofsTrieCursorFactory<'tx, 'tx, S>, MorphProofsHashedAccountCursorFactory<'tx, 'tx, S>, > @@ -209,13 +204,13 @@ where ); let tx = storage.ro_tx().map_err(Into::::into)?; let (trie_factory, hashed_factory) = from_tx(storage, &tx, block_number); - proof::StorageProof::new(trie_factory, hashed_factory.clone(), address) - .with_hashed_cursor_factory(HashedPostStateCursorFactory::new( - hashed_factory, - &state_sorted, - )) - .with_prefix_set_mut(prefix_set) - .storage_proof(slot) + proof::StorageProof::new( + trie_factory, + HashedPostStateCursorFactory::new(hashed_factory, &state_sorted), + address, + ) + .with_prefix_set_mut(prefix_set) + .storage_proof(slot) } fn overlay_storage_multiproof( @@ -234,13 +229,13 @@ where ); let tx = storage.ro_tx().map_err(Into::::into)?; let (trie_factory, hashed_factory) = from_tx(storage, &tx, block_number); - proof::StorageProof::new(trie_factory, hashed_factory.clone(), address) - .with_hashed_cursor_factory(HashedPostStateCursorFactory::new( - hashed_factory, - &state_sorted, - )) - .with_prefix_set_mut(prefix_set) - .storage_multiproof(targets) + proof::StorageProof::new( + trie_factory, + HashedPostStateCursorFactory::new(hashed_factory, &state_sorted), + address, + ) + .with_prefix_set_mut(prefix_set) + .storage_multiproof(targets) } } @@ -461,14 +456,12 @@ where let nodes_sorted = input.nodes.into_sorted(); let state_sorted = input.state.into_sorted(); let (trie_factory, hashed_factory) = from_tx(storage, tx, block_number); - let witness = TrieWitness::new(trie_factory.clone(), hashed_factory.clone()) - .with_trie_cursor_factory(InMemoryTrieCursorFactory::new(trie_factory, &nodes_sorted)) - .with_hashed_cursor_factory(HashedPostStateCursorFactory::new( - hashed_factory, - &state_sorted, - )) - .with_prefix_sets_mut(input.prefix_sets) - .with_execution_witness_mode(mode); + let witness = TrieWitness::new( + InMemoryTrieCursorFactory::new(trie_factory, &nodes_sorted), + HashedPostStateCursorFactory::new(hashed_factory, &state_sorted), + ) + .with_prefix_sets_mut(input.prefix_sets) + .with_execution_witness_mode(mode); // Deliberate divergence from the vendored Base source, which force-includes the root node // unconditionally: only the legacy shape carries it, and a canonical witness is defined // without it. Aligned with reth's own `HistoricalStateProviderRef::witness` so a caller diff --git a/crates/proofs/src/provider.rs b/crates/proofs/src/provider.rs index d28181d9..38c01743 100644 --- a/crates/proofs/src/provider.rs +++ b/crates/proofs/src/provider.rs @@ -2,32 +2,29 @@ use std::fmt::Debug; -use alloy_primitives::keccak256; +use alloy_primitives::{Address, B256, BlockNumber, Bytes, StorageValue, keccak256}; use parking_lot::{MappedMutexGuard, Mutex, MutexGuard}; use reth_primitives_traits::{Account, Bytecode}; use reth_provider::{ AccountReader, BlockHashReader, BytecodeReader, HashedPostStateProvider, ProviderError, ProviderResult, StateProofProvider, StateProvider, StateRootProvider, StorageRootProvider, }; -use reth_revm::{ - db::BundleState, - primitives::{Address, B256, Bytes, StorageValue, alloy_primitives::BlockNumber}, -}; use reth_trie::{ StateRoot, StorageRoot, hashed_cursor::{HashedCursor, zero_destroyed_account_storage}, proof::{self, Proof}, + proof_v2::MultiProofCalculator, witness::TrieWitness, }; use reth_trie_common::{ - AccountProof, ExecutionWitnessMode, HashedPostState, HashedStorage, KeccakKeyHasher, - MultiProof, MultiProofTargets, StorageMultiProof, StorageProof, TrieInput, - updates::TrieUpdates, + AccountProof, DecodedMultiProofV2, ExecutionWitnessMode, HashedPostState, HashedStorage, + KeccakKeyHasher, MultiProof, MultiProofTargets, MultiProofTargetsV2, StorageMultiProof, + StorageProof, TrieInput, bundle_state::BundleState, updates::TrieUpdates, }; use crate::{ MorphProofsHashedAccountCursorFactory, MorphProofsStorage, MorphProofsStorageError, - MorphProofsStore, + MorphProofsStore, MorphProofsTrieCursorFactory, proof::{ DatabaseProof, DatabaseStateRoot, DatabaseStorageProof, DatabaseStorageRoot, DatabaseTrieWitness, @@ -259,6 +256,24 @@ impl<'a, Storage: MorphProofsStore + Clone> StateProofProvider .map_err(ProviderError::from) } + fn multiproof_v2( + &self, + targets: MultiProofTargetsV2, + _requires_masks: bool, + ) -> ProviderResult { + // The versioned trie at `block_number` is the exact trie persisted for that block, so + // masks always match and `requires_masks` needs no special handling. + let tx = self.ensure_tx()?; + MultiProofCalculator::new( + MorphProofsTrieCursorFactory::new(self.storage, &tx, self.block_number), + MorphProofsHashedAccountCursorFactory::new(self.storage, &tx, self.block_number), + Default::default(), + Default::default(), + ) + .multiproof(targets) + .map_err(ProviderError::from) + } + fn witness( &self, input: TrieInput, @@ -337,17 +352,137 @@ impl<'a, Storage: MorphProofsStore> BytecodeReader for MorphProofsStateProviderR } #[cfg(test)] -mod tests { - use alloy_eips::BlockNumHash; +pub(crate) mod tests { + use std::sync::Arc; + + use alloy_eips::{BlockNumHash, NumHash, eip1898::BlockWithParent}; use alloy_primitives::U256; use reth_provider::noop::NoopProvider; - use reth_revm::{ - db::{AccountStatus, BundleAccount}, - state::AccountInfo, + use reth_trie_common::{ + ProofV2Target, + bundle_state::{AccountStatus, BundleAccount}, }; use super::*; - use crate::{InMemoryProofsStorage, MorphProofsInitialStateStore}; + use crate::{ + BlockStateDiff, InMemoryProofsStorage, MdbxProofsStorage, MorphProofsInitialStateStore, + }; + + /// Stores two contracts as block 1, each with a storage trie deep enough to persist branch + /// nodes, and returns the state root together with every contract's slots. + pub(crate) fn store_two_contracts(storage: &S) -> (B256, Vec<(Address, Vec)>) + where + S: MorphProofsStore + MorphProofsInitialStateStore + Clone, + { + let genesis_hash = B256::repeat_byte(0x01); + storage + .set_initial_state_anchor(BlockNumHash::new(0, genesis_hash)) + .unwrap(); + storage.commit_initial_state().unwrap(); + + let contracts: Vec<(Address, Vec)> = [0x11, 0x22] + .map(|byte| { + let slots = (0..32).map(B256::with_last_byte).collect(); + (Address::repeat_byte(byte), slots) + }) + .into(); + + let mut post_state = HashedPostState::default(); + for (address, slots) in &contracts { + let hashed_address = keccak256(address); + let account = Account { + nonce: 1, + balance: U256::from(1), + bytecode_hash: None, + }; + post_state.accounts.insert(hashed_address, Some(account)); + post_state.storages.insert( + hashed_address, + HashedStorage::from_iter(slots.iter().map(|slot| (keccak256(slot), U256::from(1)))), + ); + } + + let (state_root, trie_updates) = + StateRoot::overlay_root_with_updates(storage, 0, post_state.clone()).unwrap(); + assert!( + trie_updates.storage_tries_ref().len() == contracts.len() + && trie_updates + .storage_tries_ref() + .values() + .all(|trie| !trie.storage_nodes_ref().is_empty()), + "every contract must persist storage trie nodes for the cursors to read" + ); + + storage + .store_trie_updates( + BlockWithParent::new(genesis_hash, NumHash::new(1, B256::repeat_byte(0x02))), + BlockStateDiff { + sorted_trie_updates: trie_updates.into_sorted(), + sorted_post_state: post_state.into_sorted(), + }, + ) + .unwrap(); + + (state_root, contracts) + } + + /// Proves every contract in a single request, which makes the calculator retarget its shared + /// storage cursors between accounts, and checks the result against the legacy proof path. + pub(crate) fn assert_multiproof_v2_matches_proof( + provider: &P, + state_root: B256, + contracts: &[(Address, Vec)], + ) { + let mut targets = MultiProofTargetsV2::default(); + for (address, slots) in contracts { + let hashed_address = keccak256(address); + targets + .account_targets + .push(ProofV2Target::new(hashed_address)); + targets.storage_targets.insert( + hashed_address, + slots + .iter() + .map(|slot| ProofV2Target::new(keccak256(slot))) + .collect(), + ); + } + + let multiproof = provider.multiproof_v2(targets, false).unwrap(); + + for (address, slots) in contracts { + let proof = multiproof.account_proof(*address, slots).unwrap(); + assert_eq!(proof.storage_proofs.len(), slots.len()); + proof.verify(state_root).unwrap(); + assert_eq!( + proof, + provider + .proof(TrieInput::default(), *address, slots) + .unwrap() + ); + } + } + + #[test] + fn multiproof_v2_matches_proof_in_memory() { + let storage = InMemoryProofsStorage::new(); + let (state_root, contracts) = store_two_contracts(&storage); + let provider = + MorphProofsStateProviderRef::new(Box::::default(), &storage, 1); + + assert_multiproof_v2_matches_proof(&provider, state_root, &contracts); + } + + #[test] + fn multiproof_v2_matches_proof_in_mdbx() { + let directory = tempfile::tempdir().unwrap(); + let storage = Arc::new(MdbxProofsStorage::new(directory.path()).unwrap()); + let (state_root, contracts) = store_two_contracts(&storage); + let provider = + MorphProofsStateProviderRef::new(Box::::default(), &storage, 1); + + assert_multiproof_v2_matches_proof(&provider, state_root, &contracts); + } #[test] fn test_morph_proofs_state_provider_ref_debug() { @@ -382,7 +517,7 @@ mod tests { bundle_state.state.insert( address, BundleAccount::new( - Some(AccountInfo::default()), + Some(Default::default()), None, Default::default(), AccountStatus::Destroyed, diff --git a/crates/reference-index/src/tables.rs b/crates/reference-index/src/tables.rs index 4cd8bf88..ac3a739f 100644 --- a/crates/reference-index/src/tables.rs +++ b/crates/reference-index/src/tables.rs @@ -5,12 +5,10 @@ use alloy_primitives::B256; use reth_codecs::DecompressError; use reth_db_api::{ - DatabaseError, TableSet, TableType, TableViewer, - table::{Compress, Decode, Decompress, Encode, TableInfo}, - tables, + DatabaseError, TableSet, + table::{Compress, Decode, Decompress, Encode, Table, TableInfo}, }; use serde::{Deserialize, Serialize}; -use std::fmt; /// Key for looking up transactions by Morph transaction reference. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] @@ -246,6 +244,64 @@ impl Decompress for MetaValue { } } +/// Declares this database's tables: a marker type with a [`Table`] impl per entry, plus the +/// [`Tables`] set passed to `init_db_for`. +/// +/// `reth_db::tables!` cannot be used here: it sets [`Table::TABLE`] to the enum it generates, +/// while that constant has to name an entry of reth's own `Tables`. Tables defined outside that +/// enum leave it at its default of `None`, which makes MDBX resolve them by name. +macro_rules! tables { + ($($(#[$attr:meta])* table $name:ident { + type Key = $key:ty; + type Value = $value:ty; + })*) => { + $( + $(#[$attr])* + #[derive(Debug)] + pub enum $name {} + + impl Table for $name { + const NAME: &'static str = stringify!($name); + const DUPSORT: bool = false; + + type Key = $key; + type Value = $value; + } + )* + + /// A table in this database. + #[derive(Clone, Copy, Debug)] + pub enum Tables { + $( + #[doc = concat!("The [`", stringify!($name), "`] table.")] + $name, + )* + } + + impl TableInfo for Tables { + fn name(&self) -> &'static str { + match self { + $(Self::$name => stringify!($name),)* + } + } + + fn is_dupsort(&self) -> bool { + false + } + } + + impl TableSet for Tables { + fn tables() -> Box>> { + Box::new( + [$(Self::$name,)*] + .into_iter() + .map(|table| Box::new(table) as Box), + ) + } + } + }; +} + tables! { /// Maps reference query keys to their block timestamp. table ReferenceIndex { diff --git a/crates/revm/Cargo.toml b/crates/revm/Cargo.toml index 572eee7d..82710f5a 100644 --- a/crates/revm/Cargo.toml +++ b/crates/revm/Cargo.toml @@ -15,26 +15,18 @@ morph-primitives.workspace = true morph-chainspec.workspace = true reth-evm.workspace = true -reth-ethereum-primitives = { workspace = true, features = ["std", "serde"] } -reth-storage-api = { workspace = true, optional = true } -reth-rpc-eth-types = { workspace = true, optional = true } +reth-evm-ethereum.workspace = true evm2 = { workspace = true, features = ["std"] } +evm2-macros.workspace = true alloy-primitives.workspace = true alloy-consensus.workspace = true -alloy-sol-types.workspace = true alloy-eips.workspace = true -auto_impl.workspace = true -derive_more.workspace = true tracing.workspace = true thiserror.workspace = true [dev-dependencies] eyre.workspace = true alloy-primitives = { workspace = true, features = ["rand"] } - -[features] -reth = ["dep:reth-storage-api"] -rpc = ["dep:reth-rpc-eth-types"] diff --git a/crates/revm/src/block.rs b/crates/revm/src/block.rs index a957da6a..158917e5 100644 --- a/crates/revm/src/block.rs +++ b/crates/revm/src/block.rs @@ -1,63 +1,7 @@ -use alloy_evm::env::BlockEnvironment; -use alloy_primitives::{Address, B256, U256}; -use revm::{ - context::{Block, BlockEnv}, - context_interface::block::BlobExcessGasAndPrice, -}; +use crate::evm::MorphEvmTypes; /// Morph block environment. -#[derive(Debug, Clone, Default, derive_more::Deref, derive_more::DerefMut)] -pub struct MorphBlockEnv { - /// Inner [`BlockEnv`]. - #[deref] - #[deref_mut] - pub inner: BlockEnv, -} - -impl Block for MorphBlockEnv { - #[inline] - fn number(&self) -> U256 { - self.inner.number() - } - - #[inline] - fn beneficiary(&self) -> Address { - self.inner.beneficiary() - } - - #[inline] - fn timestamp(&self) -> U256 { - self.inner.timestamp() - } - - #[inline] - fn gas_limit(&self) -> u64 { - self.inner.gas_limit() - } - - #[inline] - fn basefee(&self) -> u64 { - self.inner.basefee() - } - - #[inline] - fn difficulty(&self) -> U256 { - self.inner.difficulty() - } - - #[inline] - fn prevrandao(&self) -> Option { - self.inner.prevrandao() - } - - #[inline] - fn blob_excess_gas_and_price(&self) -> Option { - self.inner.blob_excess_gas_and_price() - } -} - -impl BlockEnvironment for MorphBlockEnv { - fn inner_mut(&mut self) -> &mut BlockEnv { - &mut self.inner - } -} +/// +/// Morph currently needs nothing beyond the standard fields; the extension point stays +/// `MorphEvmTypes::BlockEnvExt`, so block-scoped data can be added without renaming this type. +pub type MorphBlockEnv = evm2::env::BlockEnv; diff --git a/crates/revm/src/common.rs b/crates/revm/src/common.rs deleted file mode 100644 index 1e52cb6b..00000000 --- a/crates/revm/src/common.rs +++ /dev/null @@ -1,67 +0,0 @@ -use crate::MorphTxEnv; -use alloy_primitives::{Address, U256}; -use revm::{Database, context::JournalTr, state::AccountInfo}; - -/// Helper trait to abstract over different representations of Morph transactions. -#[auto_impl::auto_impl(&)] -pub trait MorphTx { - /// Returns the transaction's caller address. - fn caller(&self) -> Address; -} - -impl MorphTx for MorphTxEnv { - fn caller(&self) -> Address { - revm::context::Transaction::caller(self) - } -} - -/// Helper trait to perform Morph-specific operations on top of different state providers. -pub trait MorphStateAccess { - type Error; - - /// Returns [`AccountInfo`] for the given address. - fn basic(&mut self, address: Address) -> Result; - - /// Returns the storage value for the given address and key. - fn sload(&mut self, address: Address, key: U256) -> Result; -} - -impl MorphStateAccess<()> for DB { - type Error = DB::Error; - - fn basic(&mut self, address: Address) -> Result { - self.basic(address).map(Option::unwrap_or_default) - } - - fn sload(&mut self, address: Address, key: U256) -> Result { - self.storage(address, key) - } -} - -impl MorphStateAccess<((), ())> for T { - type Error = ::Error; - - fn basic(&mut self, address: Address) -> Result { - self.load_account(address).map(|s| s.data.info.clone()) - } - - fn sload(&mut self, address: Address, key: U256) -> Result { - JournalTr::sload(self, address, key).map(|s| s.data) - } -} - -#[cfg(feature = "reth")] -impl MorphStateAccess<((), (), ())> for T { - type Error = reth_evm::execute::ProviderError; - - fn basic(&mut self, address: Address) -> Result { - self.basic_account(&address) - .map(Option::unwrap_or_default) - .map(Into::into) - } - - fn sload(&mut self, address: Address, key: U256) -> Result { - self.storage(address, key.into()) - .map(Option::unwrap_or_default) - } -} diff --git a/crates/revm/src/error.rs b/crates/revm/src/error.rs index 7f9190ca..762ee491 100644 --- a/crates/revm/src/error.rs +++ b/crates/revm/src/error.rs @@ -1,16 +1,15 @@ //! Morph-specific transaction validation errors. -use alloy_evm::error::InvalidTxError; use alloy_primitives::U256; -use revm::context::result::{EVMError, HaltReason, InvalidTransaction}; +use evm2::registry::HandlerError; /// Morph-specific invalid transaction errors. +/// +/// These travel through evm2 as [`HandlerError::External`]; read them back with +/// [`HandlerError::external_ref`]. Standard Ethereum rejections stay plain [`HandlerError`] +/// variants, so generic consumers keep classifying them without knowing about Morph. #[derive(Debug, Clone, PartialEq, Eq, Hash, thiserror::Error)] pub enum MorphInvalidTransaction { - /// Standard Ethereum transaction validation error. - #[error(transparent)] - EthInvalidTransaction(#[from] InvalidTransaction), - /// Token is not registered in the Token Registry. #[error("Token with ID {0} is not registered")] TokenNotRegistered(u16), @@ -65,46 +64,19 @@ pub enum MorphInvalidTransaction { /// Same rule as `ErrSetCodeTxCreate` for `0x04` transactions. #[error("MorphTx with an authorization list cannot create a contract")] AuthorizationListCreate, -} -impl InvalidTxError for MorphInvalidTransaction { - fn is_nonce_too_low(&self) -> bool { - match self { - Self::EthInvalidTransaction(err) => err.is_nonce_too_low(), - _ => false, - } - } + /// A MorphTx carries an authorization list before EIP-7702 is active. + #[error("EIP-7702 is not supported by the active hardfork")] + Eip7702NotSupported, - fn as_invalid_tx_err(&self) -> Option<&InvalidTransaction> { - match self { - Self::EthInvalidTransaction(err) => Some(err), - _ => None, - } - } + /// The maximum fee of the transaction overflows the balance arithmetic. + #[error("overflow payment in transaction")] + OverflowPaymentInTransaction, } -impl From for EVMError { +impl From for HandlerError { fn from(err: MorphInvalidTransaction) -> Self { - Self::Transaction(err) - } -} - -/// Morph-specific halt reason. -#[derive(Debug, Clone, PartialEq, Eq, Hash, derive_more::From)] -pub enum MorphHaltReason { - /// Basic Ethereum halt reason. - #[from] - Ethereum(HaltReason), -} - -#[cfg(feature = "rpc")] -impl reth_rpc_eth_types::error::api::FromEvmHalt - for reth_rpc_eth_types::EthApiError -{ - fn from_evm_halt(halt_reason: MorphHaltReason, gas_limit: u64) -> Self { - match halt_reason { - MorphHaltReason::Ethereum(halt_reason) => Self::from_evm_halt(halt_reason, gas_limit), - } + Self::external(err) } } @@ -149,59 +121,12 @@ mod tests { } #[test] - fn test_is_nonce_too_low() { - // Morph-specific errors are not nonce-too-low - assert!(!MorphInvalidTransaction::TokenNotRegistered(1).is_nonce_too_low()); - assert!(!MorphInvalidTransaction::TokenIdZeroNotSupported.is_nonce_too_low()); - assert!(!MorphInvalidTransaction::TokenNotActive(1).is_nonce_too_low()); - assert!(!MorphInvalidTransaction::InvalidTokenConfig(1).is_nonce_too_low()); - - // Wrapped Ethereum nonce-too-low should be detected - let eth_err = InvalidTransaction::NonceTooLow { tx: 5, state: 10 }; - let morph_err = MorphInvalidTransaction::EthInvalidTransaction(eth_err); - assert!(morph_err.is_nonce_too_low()); - } - - #[test] - fn test_as_invalid_tx_err() { - // Morph-specific errors return None - assert!( - MorphInvalidTransaction::TokenNotRegistered(1) - .as_invalid_tx_err() - .is_none() + fn morph_error_round_trips_through_handler_error() { + let handler_err: HandlerError = MorphInvalidTransaction::TokenNotRegistered(1).into(); + assert_eq!( + handler_err.external_ref::(), + Some(&MorphInvalidTransaction::TokenNotRegistered(1)) ); - - // Wrapped Ethereum errors return Some - let eth_err = InvalidTransaction::NonceTooLow { tx: 5, state: 10 }; - let morph_err = MorphInvalidTransaction::EthInvalidTransaction(eth_err.clone()); - assert_eq!(morph_err.as_invalid_tx_err(), Some(ð_err)); - } - - #[test] - fn test_from_invalid_transaction() { - let eth_err = InvalidTransaction::NonceTooLow { tx: 5, state: 10 }; - let morph_err: MorphInvalidTransaction = eth_err.into(); - assert!(matches!( - morph_err, - MorphInvalidTransaction::EthInvalidTransaction(_) - )); - } - - #[test] - fn test_into_evm_error() { - let morph_err = MorphInvalidTransaction::TokenNotRegistered(1); - let evm_err: EVMError = morph_err.into(); - assert!(matches!( - evm_err, - EVMError::Transaction(MorphInvalidTransaction::TokenNotRegistered(1)) - )); - } - - #[test] - fn test_morph_halt_reason_from_ethereum() { - let halt = HaltReason::OutOfGas(revm::context::result::OutOfGasError::Basic); - let morph_halt: MorphHaltReason = halt.clone().into(); - assert_eq!(morph_halt, MorphHaltReason::Ethereum(halt)); } #[test] diff --git a/crates/revm/src/evm.rs b/crates/revm/src/evm.rs index e8034f29..eb8c4dce 100644 --- a/crates/revm/src/evm.rs +++ b/crates/revm/src/evm.rs @@ -1,59 +1,144 @@ +//! The Morph EVM type family and its construction. + use crate::{ - MorphBlockEnv, MorphTxEnv, l1block::L1BlockInfo, precompiles::MorphPrecompiles, + MorphBlockEnv, MorphTxEnv, handler::morph_tx_registry, precompiles::morph_precompiles, token_fee::TokenFeeInfo, }; -use alloy_evm::Database; -use alloy_primitives::{U256, keccak256}; -use morph_chainspec::hardfork::MorphHardfork; -use revm::{ - Context, Inspector, - context::{CfgEnv, ContextError, Evm, FrameStack, Journal}, - handler::{ - EthFrame, EvmTr, FrameInitOrResult, FrameTr, ItemOrResult, instructions::EthInstructions, - }, - inspector::InspectorEvmTr, - interpreter::{ - Host, Instruction, InstructionContext, InstructionExecResult, InstructionResult, - gas::BLOCKHASH, interpreter::EthInterpreter, interpreter_types::StackTr, - }, - primitives::BLOCK_HASH_HISTORY, +use alloy_primitives::{Address, Log, U256, keccak256}; +use evm2::{ + EvmConfig, EvmConfigSelector, EvmFeatures, EvmTypesHost, ExecutionConfig, Inspector, + OpcodeConfig, SpecId, Version, + constants::BLOCK_HASH_HISTORY, + evm::DynDatabase, + interpreter::{Interpreter, Message, MessageResult, Word, instructions::invalid, op}, }; +use evm2_macros::instruction; +use morph_chainspec::hardfork::MorphHardfork; + +/// The Morph runtime EVM type family. +#[derive(Clone, Copy, Debug)] +#[non_exhaustive] +pub struct MorphEvmTypes; + +impl EvmTypesHost for MorphEvmTypes { + type ConfigSelector = MorphConfigSelector; + type SpecId = MorphHardfork; + type Tx = MorphTxEnv; + type EvmExt = (); + type MessageExt = MorphMessageExt; + type MessageResultExt = (); + type TxEnvExt = (); + type TxResultExt = MorphTxResultExt; + type BlockEnvExt = (); + type Host<'a> = evm2::Evm<'a, Self>; +} + +/// An evm2 EVM configured with the Morph type family. +pub type MorphEvm<'a> = evm2::Evm<'a, MorphEvmTypes>; -/// The Morph EVM context type. +/// Environment a Morph EVM runs under: hardfork, runtime version and block fields. /// -/// Uses [`L1BlockInfo`] as the `CHAIN` type parameter. Note that L1 fee -/// parameters are fetched **per-transaction** (not per-block) because the -/// L1 Gas Price Oracle can be updated by a regular transaction mid-block. -pub type MorphContext = - Context, DB, Journal, L1BlockInfo>; +/// Built by `ConfigureEvm::evm_env` for execution. The pool uses the same type so that the +/// balance it resolves for a call-mode fee token matches what execution would see; go-ethereum +/// likewise builds a `vm.BlockContext` from the header before querying one +/// (`pool.getBalanceFunc`, core/tx_pool.go:330). +pub type MorphEvmEnv = reth_evm_ethereum::EthEvmEnv; -#[inline] -fn as_u64_saturated(value: U256) -> u64 { - let limbs = value.as_limbs(); - if limbs[1] == 0 && limbs[2] == 0 && limbs[3] == 0 { - limbs[0] - } else { - u64::MAX +/// Morph data carried by frame messages. +/// +/// Default for every frame the interpreter creates, so it only ever identifies the top-level +/// frames the handler starts on behalf of the protocol. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct MorphMessageExt { + /// Whether this is a fee-token `balanceOf`/`transfer` frame. + pub fee_frame: bool, +} + +/// Morph data carried by a transaction result, for receipts and RPC. +#[derive(Clone, Copy, Debug, Default)] +pub struct MorphTxResultExt { + /// The L1 data fee charged, zero for L1 messages and when fee charging is disabled. + pub l1_data_fee: U256, + /// The registry data used to charge a token fee, absent when the fee was paid in ETH. + pub token_fee_info: Option, +} + +/// Morph EVM configuration for one inherited base [`SpecId`]. +#[derive(Clone, Copy, Debug)] +#[non_exhaustive] +pub struct MorphConfig; + +impl EvmConfig + for MorphConfig +{ + const BASE_SPEC_ID: SpecId = SpecId::try_from_u32(BASE_SPEC_ID).unwrap(); + const OPCODE_CONFIG: &'static OpcodeConfig = + &morph_opcode_config::(); +} + +/// Applies Morph's opcode differences to the table of the inherited base spec. +const fn morph_opcode_config() +-> OpcodeConfig { + let mut config = + OpcodeConfig::::base::>(); + // Morph geth does not read header hashes for BLOCKHASH. + let blockhash_gas = config.static_gas(op::BLOCKHASH); + config.set_instruction::(op::BLOCKHASH, blockhash_gas); + // SELFDESTRUCT, BLOBHASH and BLOBBASEFEE are disabled on Morph: they halt like an + // undefined opcode, which consumes all gas of the frame. + config.set_instruction::>(op::SELFDESTRUCT, 0); + config.set_instruction::>(op::BLOBHASH, 0); + config.set_instruction::>(op::BLOBBASEFEE, 0); + config +} + +/// Selects the opcode table for each Morph hardfork. +#[derive(Clone, Copy, Debug)] +#[non_exhaustive] +pub struct MorphConfigSelector; + +/// Morph's opcode overrides do not vary between its hardforks, so the only table parameter is +/// the inherited base spec. +const MORPH_CUSTOM_SPEC_ID: u32 = 0; + +impl EvmConfigSelector for MorphConfigSelector { + type Config = + MorphConfig; + + fn execution_config(spec_id: MorphHardfork) -> ExecutionConfig { + let base = SpecId::from(spec_id); + if base.enables(SpecId::OSAKA) { + ExecutionConfig::for_config::>( + ) + } else if base.enables(SpecId::PRAGUE) { + ExecutionConfig::for_config::< + MorphConfig<{ SpecId::PRAGUE as u32 }, MORPH_CUSTOM_SPEC_ID>, + >() + } else { + ExecutionConfig::for_config::< + MorphConfig<{ SpecId::CANCUN as u32 }, MORPH_CUSTOM_SPEC_ID>, + >() + } } } #[inline] -fn morph_blockhash_value(chain_id: u64, number: u64) -> U256 { +fn morph_blockhash_value(chain_id: u64, number: u64) -> Word { let mut input = [0_u8; 16]; input[..8].copy_from_slice(&chain_id.to_be_bytes()); input[8..].copy_from_slice(&number.to_be_bytes()); - U256::from_be_bytes(keccak256(input).0) + Word::from_be_bytes(keccak256(input).0) } #[inline] -fn morph_blockhash_result(chain_id: u64, current_number: u64, requested_number: u64) -> U256 { +fn morph_blockhash_result(chain_id: u64, current_number: u64, requested_number: u64) -> Word { // Match Morph geth exactly: // valid range is [current-256, current), otherwise push zero. let lower = current_number.saturating_sub(BLOCK_HASH_HISTORY); if requested_number >= lower && requested_number < current_number { morph_blockhash_value(chain_id, requested_number) } else { - U256::ZERO + Word::ZERO } } @@ -62,278 +147,175 @@ fn morph_blockhash_result(chain_id: u64, current_number: u64, requested_number: /// Morph geth does not read historical header hashes for BLOCKHASH. Instead it returns: /// `keccak256(chain_id(8-byte big-endian) || block_number(8-byte big-endian))` /// for numbers within the 256-block lookup window. -fn blockhash_morph( - context: InstructionContext<'_, MorphContext, EthInterpreter>, -) -> InstructionExecResult { - let Some(([], number)) = StackTr::popn_top::<0>(&mut context.interpreter.stack) else { - return Err(InstructionResult::StackUnderflow); - }; - - let requested_number_u64 = as_u64_saturated(*number); - let current_number_u64 = as_u64_saturated(context.host.block_number()); - let chain_id_u64 = as_u64_saturated(context.host.chain_id()); - - *number = morph_blockhash_result(chain_id_u64, current_number_u64, requested_number_u64); - Ok(()) +#[instruction(EvmTypes = MorphEvmTypes)] +pub fn morph_blockhash(cx: _, [number]: [Word]) -> out { + let requested_number = number.saturating_to::(); + let current_number = cx.state.host().block().number.saturating_to::(); + let chain_id = cx.state.tx().chain_id.saturating_to::(); + *out = morph_blockhash_result(chain_id, current_number, requested_number); } -/// MorphEvm extends the Evm with Morph specific types and logic. -#[derive(Debug, derive_more::Deref, derive_more::DerefMut)] -#[expect(clippy::type_complexity)] -pub struct MorphEvm { - /// Inner EVM type. - #[deref] - #[deref_mut] - pub inner: Evm< - MorphContext, - I, - EthInstructions>, - MorphPrecompiles, - EthFrame, - >, - /// Cached token fee info from the validation/deduction phase. - /// Ensures consistent price_ratio/scale between deduct and reimburse, - /// matching go-ethereum's `st.feeRate`/`st.tokenScale` caching pattern. - pub(crate) cached_token_fee_info: Option, - /// Token-unit numerator the fee deduction overcharged by rounding up. - /// - /// From Celadon on, the unused-gas refund adds this back before rounding - /// down, so the caller pays `ceil` of the net fee instead of - /// `ceil(prepaid) - ceil(refund)`, which under-collects. Mirrors - /// go-ethereum's `st.altFeeRoundingCredit`. - pub(crate) cached_alt_fee_rounding_credit: U256, - /// Cached L1 data fee calculated during handler validation. - /// Avoids re-encoding the full transaction RLP in the block executor's - /// receipt-building path (the handler already has the encoded bytes via - /// `MorphTxEnv.rlp_bytes`). - pub(crate) cached_l1_data_fee: U256, - /// Signed refund counter from a successful fee deduction call. - /// Applied before the final refund cap; refund-transfer refunds are excluded. - pub(crate) pre_fee_refund: i64, - /// Transfer event logs from token fee deduction (pre-execution phase). - /// - /// In go-ethereum, `buyAltTokenGas()` emits Transfer events into `StateDB.logs` - /// which is independent of the state snapshot/revert mechanism — logs survive - /// regardless of main tx result. revm's `ExecutionResult::Revert` has no `logs` - /// field, so we cache fee-related logs separately from the journal and merge - /// them into the receipt in the block executor. - pub(crate) pre_fee_logs: Vec, - /// Transfer event logs from token fee reimbursement (post-execution phase). - pub(crate) post_fee_logs: Vec, +/// Returns the runtime version of a Morph block with the given chain id and gas limit. +/// +/// Two standard rules do not apply to Morph: +/// - EIP-7623 is off, matching Morph geth's calldata pricing. +/// - The EIP-7825 transaction gas cap is the block gas limit. Historical mainnet transactions +/// (e.g. block 20459477, `gas_limit=21,165,068`) exceed the EIP-7825 cap of 2^24 even though +/// that rule arrives with the OSAKA spec Morph maps later hardforks to. +pub fn morph_version(spec: MorphHardfork, chain_id: u64, block_gas_limit: u64) -> Version { + let mut version = Version::new(spec.into()); + version.chain_id = chain_id; + version.features.remove(EvmFeatures::EIP7623); + version.tx_gas_limit_cap = block_gas_limit; + version } -impl MorphEvm { - /// Constructs an EVM from the full environment used by both execution and pool queries. - pub fn from_env(db: DB, env: crate::MorphEvmEnv, inspector: I) -> Self { - let ctx = MorphContext::new(db, *env.cfg_env.spec()) - .with_cfg(env.cfg_env) - .with_block(env.block_env); - Self::new(ctx, inspector) - } +/// Returns the environment of a Morph block. +pub fn morph_evm_env( + spec: MorphHardfork, + chain_id: u64, + block_gas_limit: u64, + block: MorphBlockEnv, +) -> MorphEvmEnv { + MorphEvmEnv::new_with_version(spec, block, morph_version(spec, chain_id, block_gas_limit)) +} - /// Create a new Morph EVM. - /// - /// The precompiles are automatically selected based on the hardfork spec - /// configured in the context's cfg. - pub fn new(ctx: MorphContext, inspector: I) -> Self { - // Get the current hardfork spec from context and create matching precompiles - let spec = ctx.cfg.spec; - let precompiles = MorphPrecompiles::new_with_spec(spec); - let mut instructions = EthInstructions::new_mainnet_with_spec(spec.into()); - - // SLOAD (0x54) and SSTORE (0x55) are deliberately NOT overridden. - // - // Token fee deduction leaves the caller's fee-token slot with the DB-committed - // `original_value`, the deducted `present_value` and `is_cold = true` — the same - // triple morph-geth has, where EIP-2200 `GetCommittedState` and the EIP-2929 - // access list are independent. revm <= 41 conflated the two and re-baselined - // `original_value` whenever a slot was cold, which forced Morph to hand-write both - // opcodes just to restore it. bluealloy/revm#3746 (revm-state 42) keys that - // re-baseline on the transaction boundary instead, so the native instructions now - // produce geth-equivalent gas on their own. - // - // `morph_tx_v0_token_fee_transfer_to_fee_token_contract_gas_regression` is the - // tripwire: it fails by exactly 2800 gas if that stops holding. - - // Morph custom BLOCKHASH implementation (matches Morph geth). - instructions.insert_instruction( - 0x40, - Instruction::new(blockhash_morph::), - BLOCKHASH as u16, - ); - // SELFDESTRUCT is disabled in Morph - instructions.insert_instruction(0xff, Instruction::unknown(), 0); - // BLOBHASH is disabled in Morph - instructions.insert_instruction(0x49, Instruction::unknown(), 0); - // BLOBBASEFEE is disabled in Morph - instructions.insert_instruction(0x4a, Instruction::unknown(), 0); - Self::new_inner(Evm { - ctx, - inspector, - instruction: instructions, - precompiles, - frame_stack: FrameStack::new(), - }) - } +/// Builds a Morph EVM over `database`. +pub fn morph_evm<'a>(database: impl DynDatabase + 'a, env: MorphEvmEnv) -> MorphEvm<'a> { + let MorphEvmEnv { + spec, + version, + block, + } = env; + MorphEvm::new_with_execution_config( + ExecutionConfig::for_spec_and_version(spec, version), + spec, + block, + morph_tx_registry(spec), + database, + morph_precompiles(spec), + ) +} + +/// Hides the protocol's fee-token frames from an inspector. +/// +/// go-ethereum wraps those calls in `OnSystemCallStart`/`OnSystemCallEnd`, so tracers do not see +/// them as part of the transaction. evm2 inspects every message it runs, and exposes no way for +/// a handler to pause the inspector, so every inspector installed on a Morph EVM goes through +/// this filter, which ignores everything between the start and end of a +/// [`MorphMessageExt::fee_frame`] frame. +#[derive(Debug)] +pub struct FeeFrameFilter { + inner: I, + in_fee_frame: bool, +} - #[inline] - #[expect(clippy::type_complexity)] - fn new_inner( - inner: Evm< - MorphContext, - I, - EthInstructions>, - MorphPrecompiles, - EthFrame, - >, - ) -> Self { +impl FeeFrameFilter { + /// Wraps `inner`. + pub const fn new(inner: I) -> Self { Self { inner, - cached_token_fee_info: None, - cached_alt_fee_rounding_credit: U256::ZERO, - cached_l1_data_fee: U256::ZERO, - pre_fee_refund: 0, - pre_fee_logs: Vec::new(), - post_fee_logs: Vec::new(), + in_fee_frame: false, } } -} - -impl MorphEvm { - /// Consumes self and returns a new Evm type with given Inspector. - pub fn with_inspector(self, inspector: OINSP) -> MorphEvm { - MorphEvm::new_inner(self.inner.with_inspector(inspector)) - } - /// Consumes self and returns a new Evm type with given Precompiles. - pub fn with_precompiles(self, precompiles: MorphPrecompiles) -> Self { - Self::new_inner(self.inner.with_precompiles(precompiles)) + /// Returns the wrapped inspector. + pub fn into_inner(self) -> I { + self.inner } - /// Consumes self and returns the inner Inspector. - pub fn into_inspector(self) -> I { - self.inner.into_inspector() + /// Returns the wrapped inspector. + pub const fn inner(&self) -> &I { + &self.inner } +} - /// Returns the cached token fee info set during handler validation. - /// - /// The cache is populated by `validate_and_deduct_token_fee` and persists - /// through the handler lifecycle so that post-execution code (e.g., the - /// block executor's receipt builder) can reuse it without re-reading the DB. - #[inline] - pub fn cached_token_fee_info(&self) -> Option { - self.cached_token_fee_info +impl> Inspector for FeeFrameFilter { + fn initialize_interp(&mut self, interp: &mut Interpreter<'_, '_, MorphEvmTypes>) { + if !self.in_fee_frame { + self.inner.initialize_interp(interp); + } } - /// Returns the L1 data fee cached during handler validation. - /// - /// Set in `validate_and_deduct_eth_fee` / `validate_and_deduct_token_fee` and - /// reused by `reward_beneficiary` and the block executor's receipt builder, - /// avoiding redundant `calculate_tx_l1_cost` calls and RLP re-encoding. - #[inline] - pub fn cached_l1_data_fee(&self) -> U256 { - self.cached_l1_data_fee + fn step(&mut self, interp: &mut Interpreter<'_, '_, MorphEvmTypes>) { + if !self.in_fee_frame { + self.inner.step(interp); + } } - /// Takes the cached pre-execution fee logs (token fee deduction Transfer events). - #[inline] - pub fn take_pre_fee_logs(&mut self) -> Vec { - std::mem::take(&mut self.pre_fee_logs) + fn step_end(&mut self, interp: &mut Interpreter<'_, '_, MorphEvmTypes>) { + if !self.in_fee_frame { + self.inner.step_end(interp); + } } - /// Takes the cached post-execution fee logs (token fee reimbursement Transfer events). - #[inline] - pub fn take_post_fee_logs(&mut self) -> Vec { - std::mem::take(&mut self.post_fee_logs) + fn log(&mut self, log: &Log, host: &mut MorphEvm<'_>) { + if !self.in_fee_frame { + self.inner.log(log, host); + } } -} -impl EvmTr for MorphEvm -where - DB: Database, -{ - type Context = MorphContext; - type Instructions = EthInstructions>; - type Precompiles = MorphPrecompiles; - type Frame = EthFrame; - - fn all( - &self, - ) -> ( - &Self::Context, - &Self::Instructions, - &Self::Precompiles, - &FrameStack, - ) { - self.inner.all() + fn call( + &mut self, + interp: &mut Interpreter<'_, '_, MorphEvmTypes>, + message: &mut Message, + ) -> Option> { + if message.ext.fee_frame { + self.in_fee_frame = true; + } + if self.in_fee_frame { + return None; + } + self.inner.call(interp, message) } - fn all_mut( + fn call_end( &mut self, - ) -> ( - &mut Self::Context, - &mut Self::Instructions, - &mut Self::Precompiles, - &mut FrameStack, + interp: &mut Interpreter<'_, '_, MorphEvmTypes>, + message: &Message, + result: &mut MessageResult, ) { - self.inner.all_mut() - } - - fn frame_stack(&mut self) -> &mut FrameStack { - &mut self.inner.frame_stack + if message.ext.fee_frame { + self.in_fee_frame = false; + return; + } + if !self.in_fee_frame { + self.inner.call_end(interp, message, result); + } } - fn frame_init( + fn create( &mut self, - frame_input: ::FrameInit, - ) -> Result< - ItemOrResult<&mut Self::Frame, ::FrameResult>, - ContextError, - > { - self.inner.frame_init(frame_input) - } - - fn frame_run(&mut self) -> Result, ContextError> { - self.inner.frame_run() + interp: &mut Interpreter<'_, '_, MorphEvmTypes>, + message: &mut Message, + ) -> Option> { + if self.in_fee_frame { + return None; + } + self.inner.create(interp, message) } - fn frame_return_result( + fn create_end( &mut self, - result: ::FrameResult, - ) -> Result::FrameResult>, ContextError> { - self.inner.frame_return_result(result) - } -} - -impl InspectorEvmTr for MorphEvm -where - DB: Database, - I: Inspector>, -{ - type Inspector = I; - - fn all_inspector( - &self, - ) -> ( - &Self::Context, - &Self::Instructions, - &Self::Precompiles, - &FrameStack, - &Self::Inspector, + interp: &mut Interpreter<'_, '_, MorphEvmTypes>, + message: &Message, + result: &mut MessageResult, ) { - self.inner.all_inspector() + if !self.in_fee_frame { + self.inner.create_end(interp, message, result); + } } - fn all_mut_inspector( + fn selfdestruct( &mut self, - ) -> ( - &mut Self::Context, - &mut Self::Instructions, - &mut Self::Precompiles, - &mut FrameStack, - &mut Self::Inspector, + contract: &Address, + target: &Address, + value: &U256, + host: &mut MorphEvm<'_>, ) { - self.inner.all_mut_inspector() + if !self.in_fee_frame { + self.inner.selfdestruct(contract, target, value, host); + } } } @@ -346,7 +328,7 @@ mod tests { fn morph_blockhash_matches_geth_vector() { // Golden vector captured from geth debug_traceTransaction for block 2662438: // BLOCKHASH(2662437) => 0x6d24... using chain_id=2818. - let expected = U256::from_be_bytes( + let expected = Word::from_be_bytes( b256!("6d2426d9b8d6f63ec1a38d3a4e7b88f318ebe9f0d837c4781852168c5bd2678e").0, ); assert_eq!(morph_blockhash_value(2818, 2_662_437), expected); @@ -356,13 +338,13 @@ mod tests { fn morph_blockhash_block_zero() { // Block 0 requested from block 1 — block 0 is within [1-256, 1) = [0, 1), so valid let result = morph_blockhash_result(2818, 1, 0); - assert_ne!(result, U256::ZERO, "block 0 from block 1 should be valid"); + assert_ne!(result, Word::ZERO, "block 0 from block 1 should be valid"); // Block 0 requested from block 0 — current block returns zero let result = morph_blockhash_result(2818, 0, 0); assert_eq!( result, - U256::ZERO, + Word::ZERO, "block 0 from block 0 should be zero (current block)" ); } @@ -371,7 +353,7 @@ mod tests { fn morph_blockhash_chain_id_zero() { // chain_id=0 should still produce a deterministic hash let result = morph_blockhash_value(0, 100); - assert_ne!(result, U256::ZERO, "chain_id=0 should still produce a hash"); + assert_ne!(result, Word::ZERO, "chain_id=0 should still produce a hash"); // Different chain_ids produce different hashes let result_0 = morph_blockhash_value(0, 100); @@ -390,12 +372,12 @@ mod tests { for n in 0..5 { assert_ne!( morph_blockhash_result(chain_id, 5, n), - U256::ZERO, + Word::ZERO, "block {n} from block 5 should be valid" ); } // Block 5 (current) should be zero - assert_eq!(morph_blockhash_result(chain_id, 5, 5), U256::ZERO); + assert_eq!(morph_blockhash_result(chain_id, 5, 5), Word::ZERO); } #[test] @@ -406,21 +388,21 @@ mod tests { // current - 256 = 44 (inclusive lower bound) assert_ne!( morph_blockhash_result(chain_id, current, 44), - U256::ZERO, + Word::ZERO, "block current-256 should be valid" ); // current - 257 = 43 (out of range) assert_eq!( morph_blockhash_result(chain_id, current, 43), - U256::ZERO, + Word::ZERO, "block current-257 should be zero" ); // current - 1 = 299 (valid, most recent) assert_ne!( morph_blockhash_result(chain_id, current, 299), - U256::ZERO, + Word::ZERO, "block current-1 should be valid" ); } @@ -441,23 +423,49 @@ mod tests { // current block and future blocks must return zero assert_eq!( morph_blockhash_result(chain_id, current, current), - U256::ZERO + Word::ZERO ); assert_eq!( morph_blockhash_result(chain_id, current, current + 1), - U256::ZERO + Word::ZERO ); // more than 256 blocks in the past returns zero assert_eq!( morph_blockhash_result(chain_id, current, current - 257), - U256::ZERO + Word::ZERO ); // lower bound is inclusive (current - 256 is valid) assert_ne!( morph_blockhash_result(chain_id, current, current - 256), - U256::ZERO + Word::ZERO ); } + + #[test] + fn morph_version_turns_off_eip7623_and_the_eip7825_cap() { + let version = morph_version(MorphHardfork::Celadon, 2818, 30_000_000); + assert_eq!(version.chain_id, 2818); + assert!(!version.feature(EvmFeatures::EIP7623)); + assert_eq!(version.tx_gas_limit_cap, 30_000_000); + } + + #[test] + fn execution_config_maps_each_hardfork_to_its_base_spec() { + for (fork, spec) in [ + (MorphHardfork::Bernoulli, SpecId::CANCUN), + (MorphHardfork::Curie, SpecId::CANCUN), + (MorphHardfork::Morph203, SpecId::CANCUN), + (MorphHardfork::Viridian, SpecId::PRAGUE), + (MorphHardfork::Emerald, SpecId::OSAKA), + (MorphHardfork::Jade, SpecId::OSAKA), + (MorphHardfork::Celadon, SpecId::OSAKA), + ] { + assert_eq!( + MorphConfigSelector::execution_config(fork).base_spec_id(), + spec + ); + } + } } diff --git a/crates/revm/src/exec.rs b/crates/revm/src/exec.rs deleted file mode 100644 index 9fa3e681..00000000 --- a/crates/revm/src/exec.rs +++ /dev/null @@ -1,193 +0,0 @@ -use crate::{ - MorphBlockEnv, MorphInvalidTransaction, MorphTxEnv, - error::MorphHaltReason, - evm::{MorphContext, MorphEvm}, - handler::MorphEvmHandler, -}; -use alloy_evm::{Database, TransactionEnvMut as _}; -use revm::{ - DatabaseCommit, ExecuteCommitEvm, ExecuteEvm, - context::{ContextSetters, TxEnv, result::ExecResultAndState}, - context_interface::{ - ContextTr, JournalTr, - result::{EVMError, ExecutionResult}, - }, - handler::{Handler, SystemCallTx, system_call::SystemCallEvm}, - inspector::{InspectCommitEvm, InspectEvm, InspectSystemCallEvm, Inspector, InspectorHandler}, - primitives::{Address, Bytes}, - state::EvmState, -}; - -/// Total gas system transactions are allowed to use. -const SYSTEM_CALL_GAS_LIMIT: u64 = 200_000; - -impl ExecuteEvm for MorphEvm -where - DB: Database, -{ - type Tx = MorphTxEnv; - type Block = MorphBlockEnv; - type State = EvmState; - type Error = EVMError; - type ExecutionResult = ExecutionResult; - - fn set_block(&mut self, block: Self::Block) { - self.inner.ctx.set_block(block); - } - - fn transact_one(&mut self, tx: Self::Tx) -> Result { - self.inner.ctx.set_tx(tx); - let mut h = MorphEvmHandler::new(); - h.run(self) - } - - fn finalize(&mut self) -> Self::State { - self.inner.ctx.journal_mut().finalize() - } - - fn replay( - &mut self, - ) -> Result, Self::Error> { - let mut h = MorphEvmHandler::new(); - h.run(self) - // An execution error can leave loaded accounts and warm-state data in - // the journal. Clear it before this EVM is reused, matching revm's - // mainnet replay implementation. - .inspect_err(|_| { - let _ = self.finalize(); - }) - .map(|result| { - let state = self.finalize(); - ExecResultAndState::new(result, state) - }) - } -} - -impl ExecuteCommitEvm for MorphEvm -where - DB: Database + DatabaseCommit, -{ - fn commit(&mut self, state: Self::State) { - self.inner.ctx.db_mut().commit(state); - } -} - -impl InspectEvm for MorphEvm -where - DB: Database, - I: Inspector>, -{ - type Inspector = I; - - fn set_inspector(&mut self, inspector: Self::Inspector) { - self.inner.inspector = inspector; - } - - fn inspect_one_tx(&mut self, tx: Self::Tx) -> Result { - self.inner.ctx.set_tx(tx); - let mut h = MorphEvmHandler::new(); - h.inspect_run(self) - } -} - -impl InspectCommitEvm for MorphEvm -where - DB: Database + DatabaseCommit, - I: Inspector>, -{ -} - -impl SystemCallEvm for MorphEvm -where - DB: Database, -{ - fn system_call_one_with_caller( - &mut self, - caller: Address, - system_contract_address: Address, - data: Bytes, - ) -> Result { - let mut tx = TxEnv::new_system_tx_with_caller(caller, system_contract_address, data); - tx.set_gas_limit(SYSTEM_CALL_GAS_LIMIT); - self.inner.ctx.set_tx(tx.into()); - let mut h = MorphEvmHandler::new(); - h.run_system_call(self) - } -} - -impl InspectSystemCallEvm for MorphEvm -where - DB: Database, - I: Inspector>, -{ - fn inspect_one_system_call_with_caller( - &mut self, - caller: Address, - system_contract_address: Address, - data: Bytes, - ) -> Result { - let mut tx = TxEnv::new_system_tx_with_caller(caller, system_contract_address, data); - tx.set_gas_limit(SYSTEM_CALL_GAS_LIMIT); - self.inner.ctx.set_tx(tx.into()); - let mut h = MorphEvmHandler::new(); - h.inspect_run_system_call(self) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use alloy_primitives::TxKind; - use morph_chainspec::MorphHardfork; - use revm::{ - context::{BlockEnv, TxEnv}, - context_interface::result::InvalidTransaction, - database::{CacheDB, EmptyDB}, - handler::EvmTr, - inspector::NoOpInspector, - }; - - #[test] - fn replay_clears_journal_after_execution_error() { - let caller = Address::repeat_byte(0x11); - let mut evm = MorphEvm::new( - MorphContext::new(CacheDB::new(EmptyDB::default()), MorphHardfork::default()), - NoOpInspector, - ); - evm.block = MorphBlockEnv { - inner: BlockEnv { - gas_limit: 30_000_000, - ..Default::default() - }, - }; - evm.tx = MorphTxEnv { - inner: TxEnv { - caller, - gas_limit: 21_000, - gas_price: 1, - kind: TxKind::Call(Address::ZERO), - ..Default::default() - }, - ..Default::default() - }; - - let result = evm.replay(); - - assert!(matches!( - result, - Err(EVMError::Transaction( - MorphInvalidTransaction::EthInvalidTransaction( - InvalidTransaction::LackOfFundForMaxFee { .. } - ) - )) - )); - assert!( - evm.ctx_ref().journal().state.is_empty(), - "failed replay must not leak loaded account state" - ); - assert!( - evm.ctx_ref().journal().journal.is_empty(), - "failed replay must not leak journal entries" - ); - } -} diff --git a/crates/revm/src/handler.rs b/crates/revm/src/handler.rs index 27fc6118..535196df 100644 --- a/crates/revm/src/handler.rs +++ b/crates/revm/src/handler.rs @@ -1,28 +1,46 @@ -//! Morph EVM Handler implementation. - -use alloy_primitives::{Address, Bytes, U256}; -use morph_primitives::transaction::morph_transaction::MORPH_TX_VERSION_2; -use revm::{ - ExecuteEvm, - context::{ - Cfg, ContextTr, JournalTr, Transaction, - result::{EVMError, ExecutionResult, InvalidTransaction}, +//! Morph transaction handler. +//! +//! Every Morph transaction type runs through [`prepare`] and [`execute`], in the order +//! go-ethereum's `TransitionDb` runs them: charge the fee, reset the per-transaction access +//! state, apply EIP-7702 authorizations, run the message, then refund and pay the fee recipient. +//! That one flow keeps the rules below in a single place instead of split between the standard +//! evm2 handlers and hooks: +//! +//! - L1 data fee calculation and deduction +//! - ERC20 token fee deduction and reimbursement for MorphTx (0x7F) +//! - L2 execution fee handling, paid in full to the fee recipient +//! - L1 message transactions (0x7E), which pay no fees on L2 + +use std::sync::OnceLock; + +use alloy_primitives::{Address, B256, Bytes, U256}; +use evm2::{ + EvmFeatures, SpecId, TxResult, + bytecode::Bytecode, + env::{TxEnv, TxEnvExt}, + ethereum::{ + access_list_counts, + eip7702::{AuthRefunds, apply_auth_list, eip7702_authorization_gas}, + execute_initial_frame, finalize_gas, initial_gas_and_reservoir, intrinsic_and_floor_gas, + prepare_initial_frame, validate_block_gas_limit, validate_chain_id, + validate_create_initcode, validate_floor_gas, validate_gas_price, validate_intrinsic_gas, + validate_nonce_not_overflow, validate_priority_fee, validate_tx_gas_limit_cap, + warm_access_list, warm_base_accounts, }, - context_interface::{ - Block, cfg::gas_params::Eip2780TxInfo, journaled_state::account::JournaledAccountTr, - result::ResultGas, - }, - handler::{EvmTr, FrameTr, Handler, MainnetHandler, post_execution, pre_execution, validation}, - inspector::{Inspector, InspectorHandler}, - interpreter::{Gas, GasTracker, InitialAndFloorGas, interpreter::EthInterpreter}, - primitives::hardfork::SpecId, + evm::State, + handler::GasSettlement, + interpreter::{GasTracker, Host, Message, MessageExt, MessageKind, MessageResult, Word}, + registry::{HandlerError, HandlerResult, TxRegistry, TxRequest, handler}, +}; +use morph_chainspec::hardfork::MorphHardfork; +use morph_primitives::{ + L1_TX_TYPE_ID, MORPH_TX_TYPE_ID, transaction::morph_transaction::MORPH_TX_VERSION_2, }; use crate::{ - MorphEvm, MorphInvalidTransaction, - error::MorphHaltReason, - evm::MorphContext, - l1block::L1BlockInfo, + MorphInvalidTransaction, MorphTxEnv, + evm::{MorphEvm, MorphEvmTypes, MorphMessageExt, MorphTxResultExt}, + l1block::{L1_GAS_PRICE_ORACLE_ADDRESS, L1BlockInfo}, token_fee::{ TokenFeeInfo, TokenRegistryEntry, compute_mapping_slot_for_address, encode_balance_of_calldata, read_balance_from_storage, @@ -30,1059 +48,884 @@ use crate::{ tx::MorphTxExt, }; -/// Morph EVM [`Handler`] implementation. -/// -/// This handler implements Morph-specific transaction fee logic: -/// - L1 data fee calculation and deduction -/// - L2 execution fee handling -/// - Gas reimbursement for unused gas -/// - L1 message transaction handling (no gas fees) -#[derive(Debug)] -pub struct MorphEvmHandler { - /// Phantom data to avoid type inference issues. - _phantom: core::marker::PhantomData<(DB, I)>, -} +const LEGACY_TX_TYPE: u8 = 0x00; +const EIP2930_TX_TYPE: u8 = 0x01; +const EIP1559_TX_TYPE: u8 = 0x02; +const EIP7702_TX_TYPE: u8 = 0x04; -impl MorphEvmHandler { - /// Create a new [`MorphEvmHandler`] handler instance - pub fn new() -> Self { - Self { - _phantom: core::marker::PhantomData, - } - } -} +/// Gas limit for internal EVM calls (ERC20 transfer, balanceOf). +const EVM_CALL_GAS_LIMIT: u64 = 200_000; -impl Default for MorphEvmHandler { - fn default() -> Self { - Self::new() - } -} +/// A transaction request as seen by the Morph handler. +type MorphTxRequest<'a, 'host> = TxRequest<'a, 'host, MorphEvmTypes, MorphTxEnv>; -impl Handler for MorphEvmHandler -where - DB: alloy_evm::Database, -{ - type Evm = MorphEvm; - type Error = EVMError; - type HaltReason = MorphHaltReason; - - #[inline] - fn run( - &mut self, - evm: &mut Self::Evm, - ) -> Result, Self::Error> { - match self.run_without_catch_error(evm) { - Ok(output) => Ok(output), - Err(err) => self.catch_error(evm, err), - } +/// Returns the transaction registry of a Morph hardfork. +/// +/// EIP-7702 transactions exist from Prague on. Every other type is accepted by every Morph +/// hardfork, all of which are at least Cancun. +pub fn morph_tx_registry( + spec: MorphHardfork, +) -> TxRegistry> { + static WITH_EIP7702: OnceLock>> = + OnceLock::new(); + static WITHOUT_EIP7702: OnceLock>> = + OnceLock::new(); + + if SpecId::from(spec).enables(SpecId::PRAGUE) { + WITH_EIP7702.get_or_init(|| build_registry(true)).clone() + } else { + WITHOUT_EIP7702 + .get_or_init(|| build_registry(false)) + .clone() } +} - #[inline] - fn execution_result( - &mut self, - evm: &mut Self::Evm, - result: <::Frame as FrameTr>::FrameResult, - result_gas: ResultGas, - ) -> Result, Self::Error> { - MainnetHandler::default() - .execution_result(evm, result, result_gas) - .map(|result| result.map_haltreason(Into::into)) - } +fn build_registry(eip7702: bool) -> TxRegistry> { + let mut registry = TxRegistry::new(); + let tx_types = [ + LEGACY_TX_TYPE, + EIP2930_TX_TYPE, + EIP1559_TX_TYPE, + L1_TX_TYPE_ID, + MORPH_TX_TYPE_ID, + ]; + for tx_type in tx_types { + registry.register( + tx_type, + |tx: &MorphTxEnv| Some(tx), + handler(prepare, execute), + ); + } + if eip7702 { + registry.register( + EIP7702_TX_TYPE, + |tx: &MorphTxEnv| Some(tx), + handler(prepare, execute), + ); + } + registry +} - /// Applies the EIP-7702 authorization list. - /// - /// revm's default implementation only applies the list when - /// `tx_type == 0x04`; MorphTx (`0x7F`) maps to `TransactionType::Custom` - /// and would be skipped silently, charging the sender for authorizations - /// that never take effect. MorphTx V2 lists are applied here with the same - /// `pre_execution::apply_auth_list` routine and refund accounting as `0x04`. +/// The token fee charged by [`prepare`], needed again to refund unused gas. +#[derive(Clone, Copy, Debug)] +struct AppliedTokenFee { + /// Registry data of the fee token, so that the deduction and the refund use the same + /// `price_ratio`/`scale`, matching go-ethereum's `st.feeRate`/`st.tokenScale`. + info: TokenFeeInfo, + /// Token-unit numerator the deduction overcharged by rounding up. /// - /// The EIP-2780 (Amsterdam) runtime-charge variant is not handled for - /// MorphTx: no Morph hardfork enables it (see - /// `test_morph_hardforks_do_not_enable_amsterdam_state_gas`). - #[inline] - fn apply_eip7702_auth_list( - &self, - evm: &mut Self::Evm, - init_and_floor_gas: &mut GasTracker, - ) -> Result, Self::Error> { - if !evm.ctx_ref().tx().is_morph_tx() { - return pre_execution::apply_eip7702_auth_list(evm.ctx(), init_and_floor_gas); - } - - // `validate_env` already enforced that only V2 carries a list, so V0/V1 - // (and a V2 with an empty list, which behaves like V1) fall through here - // with nothing to apply. - if evm.ctx_ref().tx().authorization_list_len() == 0 { - return Ok(Some(0)); - } - - let chain_id = evm.ctx_ref().cfg().chain_id(); - let (tx, journal) = evm.ctx().tx_journal_mut(); - let refunded_accounts = pre_execution::apply_auth_list::<_, Self::Error>( - chain_id, - tx.authorization_list(), - journal, - )?; + /// From Celadon on, the unused-gas refund adds this back before rounding down, so the + /// caller pays `ceil` of the net fee instead of `ceil(prepaid) - ceil(refund)`, which + /// under-collects. Mirrors go-ethereum's `st.altFeeRoundingCredit`. + rounding_credit: U256, + /// Signed refund counter of the fee deduction call. Applied before the final refund cap; + /// the refund transfer's own counter is excluded. + refund_counter: i64, +} - let regular_gas_refund = evm - .ctx_ref() - .cfg() - .gas_params() - .tx_eip7702_auth_refund_regular() - .saturating_mul(refunded_accounts); - - Ok(Some(regular_gas_refund)) - } - - #[inline] - fn validate_against_state_and_deduct_caller( - &self, - evm: &mut Self::Evm, - _init_and_floor_gas: &mut InitialAndFloorGas, - ) -> Result<(), Self::Error> { - // Reset per-transaction caches from the previous iteration. - evm.cached_l1_data_fee = U256::ZERO; - evm.pre_fee_refund = 0; - evm.cached_token_fee_info = None; - evm.cached_alt_fee_rounding_credit = U256::ZERO; - evm.pre_fee_logs.clear(); - evm.post_fee_logs.clear(); - - let (_, tx, _, journal, _, _) = evm.ctx().all_mut(); - - if tx.is_l1_msg() { - let mut caller = journal.load_account_with_code_mut(tx.caller())?.data; - - // CREATE nonce is bumped later in make_create_frame - if tx.kind().is_call() { - caller.bump_nonce(); - } - return Ok(()); - } +/// What [`prepare`] established for [`execute`]. +#[derive(Debug)] +pub struct PreparedMorphTx { + caller: Address, + /// Effective gas price of the transaction. + gas_price: U256, + intrinsic: u64, + floor_gas: u64, + /// The sender's nonce before this transaction bumped it, which names a created contract. + sender_nonce: u64, + tx_env: TxEnv, + l1_data_fee: U256, + token_fee: Option, +} - // MorphTx (0x7F) can use token fee (fee_token_id > 0) or ETH fee (fee_token_id == 0). - if evm.ctx_ref().tx().is_morph_tx() { - let token_id = evm.ctx_ref().tx().fee_token_id.unwrap_or_default(); - if token_id > 0 { - return self.validate_and_deduct_token_fee(evm, token_id); - } - return self.validate_and_deduct_eth_fee(evm); - } +/// Validates a transaction and applies its pre-execution state changes. +fn prepare(req: &mut MorphTxRequest<'_, '_>) -> HandlerResult { + let caller = req.tx.signer(); + let tx: &MorphTxEnv = req.tx.inner(); + let host: &mut MorphEvm<'_> = req.host; + + let basefee = host.block().basefee.saturating_to::(); + let gas_price = U256::from(tx.effective_gas_price_at(basefee)); + let tx_env = TxEnvExt { + origin: caller, + gas_price, + chain_id: U256::from(host.version().chain_id), + ..TxEnvExt::default() + }; - // Standard ETH-based fee handling - self.validate_and_deduct_eth_fee(evm) + if tx.is_l1_msg() { + // If intrinsic gas exceeds the gas limit, fall back to the gas limit: L1 messages + // prepay gas on L1 and must always execute, matching go-ethereum. + let (intrinsic, _) = intrinsic_gas(host, tx, caller); + let sender_nonce = bump_sender_nonce(host, caller)?; + warm_transaction_accounts(host, tx, caller)?; + return Ok(PreparedMorphTx { + caller, + gas_price, + intrinsic: intrinsic.min(tx.gas_limit), + floor_gas: 0, + sender_nonce, + tx_env, + l1_data_fee: U256::ZERO, + token_fee: None, + }); } - fn reimburse_caller( - &self, - evm: &mut Self::Evm, - exec_result: &mut <::Frame as FrameTr>::FrameResult, - ) -> Result<(), Self::Error> { - let (_, tx, _, _, _, _) = evm.ctx().all_mut(); + validate_env(host, tx)?; + let (intrinsic, floor_gas) = intrinsic_gas(host, tx, caller); + validate_intrinsic_gas(tx.gas_limit, intrinsic, 0)?; + validate_floor_gas(tx.gas_limit, floor_gas)?; - // L1 message gas is prepaid on L1, no reimbursement needed. - if tx.is_l1_msg() { - return Ok(()); - } + let token_id = tx.fee_token_id.unwrap_or_default(); + let charged = if tx.is_morph_tx() && token_id > 0 { + deduct_token_fee(host, tx, caller, &tx_env, token_id)? + } else { + deduct_eth_fee(host, tx, caller)? + }; + warm_transaction_accounts(host, tx, caller)?; + + Ok(PreparedMorphTx { + caller, + gas_price, + intrinsic, + floor_gas, + sender_nonce: charged.sender_nonce, + tx_env, + l1_data_fee: charged.l1_data_fee, + token_fee: charged.token_fee, + }) +} - // MorphTx (0x7F) can use token fee (fee_token_id > 0) or ETH fee (fee_token_id == 0). - if tx.is_morph_tx() { - let token_id = tx.fee_token_id.unwrap_or_default(); - if token_id > 0 { - // When fee charge was disabled (eth_call), no token was deducted and - // cached_token_fee_info was not set — skip reimbursement entirely. - if evm.cached_token_fee_info.is_none() { - return Ok(()); - } - return self.reimburse_caller_token_fee(evm, exec_result.gas()); - } - // fee_token_id == 0 follows standard ETH reimbursement flow - post_execution::reimburse_caller(evm.ctx(), exec_result.gas(), U256::ZERO)?; - return Ok(()); - } +/// Executes a prepared transaction and settles its gas. +fn execute( + req: MorphTxRequest<'_, '_>, + prepared: PreparedMorphTx, +) -> HandlerResult> { + let PreparedMorphTx { + caller, + gas_price, + intrinsic, + floor_gas, + sender_nonce, + tx_env, + l1_data_fee, + token_fee, + } = prepared; + let tx: &MorphTxEnv = req.tx.inner(); + let host: &mut MorphEvm<'_> = req.host; + + let execution_refund = apply_authorizations(host, tx)?; + + let (execution_gas_limit, reservoir) = + initial_gas_and_reservoir(host.version(), tx.gas_limit, intrinsic, 0); + let mut tx_gas = + GasTracker::new_with_execution_gas_and_reservoir(execution_gas_limit, reservoir); + let frame = prepare_initial_frame( + host, + caller, + sender_nonce, + tx.kind, + &tx.data, + tx.value, + &mut tx_gas, + )?; + let mut result = execute_initial_frame( + host, + &tx_env, + frame, + &mut tx_gas, + execution_gas_limit, + reservoir, + )?; - // Standard ETH-based fee handling - post_execution::reimburse_caller(evm.ctx(), exec_result.gas(), U256::ZERO)?; - Ok(()) - } - - #[inline] - fn refund( - &self, - evm: &mut Self::Evm, - exec_result: &mut <::Frame as FrameTr>::FrameResult, - eip7702_refund: i64, - ) -> Result<(), Self::Error> { - // L1 message tx follows go-ethereum semantics: no gas refunds. - // Keep gas_used as actual consumed gas without applying post-exec refund. - if evm.ctx_ref().tx().is_l1_msg() { - // revm::Gas::used() subtracts `refunded` by default. - // For L1 messages we must zero it out, otherwise gas_used is undercounted. - exec_result.gas_mut().set_refund(0); - return Ok(()); + if tx.is_l1_msg() { + // L1 messages follow go-ethereum: no gas refund, so gas used is the gas consumed. + result.gas.set_refunded(0); + return settle(host, tx, caller, gas_price, floor_gas, result); + } + + let fee_refund = token_fee.map_or(0, |fee| fee.refund_counter); + result.gas.record_refund(fee_refund); + result + .gas + .record_refund(i64::try_from(execution_refund).unwrap_or(i64::MAX)); + let mut output = settle(host, tx, caller, gas_price, floor_gas, result)?; + + let unused_gas = tx.gas_limit.saturating_sub(output.tx_gas_used()); + match token_fee { + Some(fee) => reimburse_token_fee(host, &tx_env, caller, gas_price, unused_gas, fee)?, + // A token-fee transaction that charged nothing (fee charging is disabled) has + // nothing to reimburse or pay out, in either asset. + None if tx.uses_token_fee() => {} + None if host.feature(EvmFeatures::FEE_CHARGE) => { + let refund = gas_price.saturating_mul(U256::from(unused_gas)); + host.state_mut().account(&caller)?.add_balance(refund); + // Morph pays the whole fee to the fee recipient: there is no base fee burn. + let beneficiary = host.block().beneficiary; + let reward = gas_price + .saturating_mul(U256::from(output.tx_gas_used())) + .saturating_add(l1_data_fee); + host.state_mut().account(&beneficiary)?.add_balance(reward); } - exec_result.gas_mut().record_refund(evm.pre_fee_refund); - post_execution::refund( - evm.ctx().cfg().gas_params(), - exec_result.gas_mut(), - eip7702_refund, - ); - Ok(()) - } - - #[inline] - fn reward_beneficiary( - &self, - evm: &mut Self::Evm, - exec_result: &mut <::Frame as FrameTr>::FrameResult, - ) -> Result<(), Self::Error> { - // Reuse the L1 data fee cached during validate_and_deduct_eth_fee / - // validate_and_deduct_token_fee, avoiding a redundant calculate_tx_l1_cost call. - // Read before ctx().all_mut() borrows evm. - let l1_data_fee = evm.cached_l1_data_fee; - - let (block, tx, _, journal, _, _) = evm.ctx().all_mut(); - - // L1 messages skip all reward. - // Token-fee MorphTx rewards are already applied when token fee is deducted. - if tx.is_l1_msg() || (tx.is_morph_tx() && tx.fee_token_id.unwrap_or_default() > 0) { - return Ok(()); - } - - let beneficiary = block.beneficiary(); - - let basefee = block.basefee() as u128; - let effective_gas_price = tx.effective_gas_price(basefee); - - let gas_used = exec_result.gas().used(); - - let execution_fee = U256::from(effective_gas_price).saturating_mul(U256::from(gas_used)); + None => {} + } - // reward beneficiary - journal - .load_account_mut(beneficiary)? - .incr_balance(execution_fee.saturating_add(l1_data_fee)); + output.ext = MorphTxResultExt { + l1_data_fee, + token_fee_info: token_fee.map(|fee| fee.info), + }; + Ok(output) +} - Ok(()) - } +/// Finalizes gas accounting for the transaction. +fn settle( + host: &mut MorphEvm<'_>, + tx: &MorphTxEnv, + caller: Address, + gas_price: U256, + floor_gas: u64, + result: MessageResult, +) -> HandlerResult> { + finalize_gas( + host, + GasSettlement { + caller, + gas_price, + gas_limit: tx.gas_limit, + floor_gas, + initial_state_gas: 0, + state_refund: 0, + result, + }, + ) +} - #[inline] - fn validate_env(&self, evm: &mut Self::Evm) -> Result<(), Self::Error> { - // For L1 message transactions - if evm.ctx_ref().tx().is_l1_msg() { - // L1 messages have zero gas price, so skip gas price validation - return Ok(()); - } +/// Validates the fields of a non-L1-message transaction that need no state. +fn validate_env(host: &MorphEvm<'_>, tx: &MorphTxEnv) -> HandlerResult<()> { + let version = host.version(); + let basefee = host.block().basefee; + let max_fee = U256::from(tx.gas_price); + let priority_fee = U256::from(tx.gas_priority_fee.unwrap_or_default()); + let effective_gas_price = max_fee.min(basefee.saturating_add(priority_fee)); + + // Legacy transactions are the only standard type that can omit the chain id. + validate_chain_id( + version, + tx.chain_id, + tx.tx_type == LEGACY_TX_TYPE || tx.is_morph_tx(), + )?; + validate_tx_gas_limit_cap(version, tx.gas_limit)?; - // Standard validation. - // Note: revm maps MorphTx (type 0x7F) to `TransactionType::Custom`, - // which skips gas-price checks entirely. - validation::validate_env::<_, Self::Error>(evm.ctx())?; - - // MorphTx maps to `TransactionType::Custom`, so revm's standard path - // does not enforce EIP-1559 fee-cap rules. Those rules are independent - // of which asset ultimately pays the fee, matching Morph geth's preCheck. - if evm.ctx_ref().tx().is_morph_tx() && !evm.ctx_ref().cfg().is_fee_charge_disabled() { - let base_fee = Some(evm.ctx_ref().block().basefee() as u128); - validation::validate_priority_fee_tx( - evm.ctx_ref().tx().max_fee_per_gas(), - evm.ctx_ref() - .tx() - .max_priority_fee_per_gas() - .unwrap_or_default(), - base_fee, - evm.ctx_ref().cfg().is_priority_fee_check_disabled(), - )?; + match tx.tx_type { + LEGACY_TX_TYPE | EIP2930_TX_TYPE => validate_gas_price(version, max_fee, basefee)?, + EIP1559_TX_TYPE => { + validate_priority_fee(version, max_fee, priority_fee)?; + validate_gas_price(version, effective_gas_price, basefee)?; } - - // The `Custom` branch also skips the EIP-7702 static rules (Prague gate, - // no CREATE) that revm applies to `0x04`. A MorphTx V2 carrying - // authorizations must obey the same rules; an empty V2 list is allowed - // and needs no extra checks. - if evm.ctx_ref().tx().is_morph_tx() { - self.validate_morph_tx_authorization_list(evm)?; + EIP7702_TX_TYPE => { + validate_priority_fee(version, max_fee, priority_fee)?; + validate_gas_price(version, effective_gas_price, basefee)?; + if tx.authorization_list.is_empty() { + return Err(HandlerError::EmptyAuthorizationList); + } } - - Ok(()) - } - - #[inline] - fn validate_initial_tx_gas( - &self, - evm: &mut Self::Evm, - ) -> Result { - let tx = evm.ctx_ref().tx(); - let cfg = evm.ctx_ref().cfg(); - let spec = (*cfg.spec()).into(); - let disable_eip7623 = cfg.is_eip7623_disabled(); - let is_amsterdam_eip8037 = cfg.is_amsterdam_eip8037_enabled(); - let tx_gas_limit_cap = cfg.tx_gas_limit_cap(); - // Derive the EIP-2780 intrinsic-gas info the same way revm's own handler does - // rather than hardcoding `None`. Every Morph hardfork maps below AMSTERDAM today - // (asserted by `test_morph_hardforks_do_not_enable_amsterdam_state_gas`), so this - // is `None` in practice — but a hardcoded `None` would silently diverge from - // upstream intrinsic gas the moment that mapping changes. - let eip2780 = cfg.is_amsterdam_eip2780_enabled().then(|| Eip2780TxInfo { - value: tx.value(), - // Self-transfer: a `Call` whose recipient is the sender itself. - is_self_transfer: tx.kind().to() == Some(&tx.caller()), - }); - - // For L1 message transactions, handle intrinsic gas specially - if tx.is_l1_msg() { - // Calculate intrinsic gas (same as normal transactions). If intrinsic gas - // > gas_limit, fall back to gas_limit (matching go-ethereum's behavior for - // L1 messages, which prepay gas on L1 and must always execute). - let initial_and_floor = validation::validate_initial_tx_gas_with_gas_params( - tx, - spec, - cfg.gas_params(), - disable_eip7623, - is_amsterdam_eip8037, - tx_gas_limit_cap, - eip2780, - ) - .unwrap_or_else(|_| InitialAndFloorGas::new(tx.gas_limit(), 0)); - - return Ok(initial_and_floor); + _ => {} + } + + validate_block_gas_limit(version, tx.gas_limit, host.block().gas_limit)?; + validate_create_initcode(version, tx.kind, &tx.data)?; + validate_nonce_not_overflow(tx.nonce)?; + + if tx.is_morph_tx() { + // The EIP-1559 fee-cap rules hold whichever asset ends up paying the fee, matching + // Morph geth's preCheck. Unlike the standard types, a disabled base fee check does + // not relax them while fees are being charged. + if host.feature(EvmFeatures::FEE_CHARGE) { + validate_priority_fee(version, max_fee, priority_fee)?; + if effective_gas_price < basefee { + return Err(HandlerError::FeeCapLessThanBaseFee { + max_fee_per_gas: effective_gas_price, + base_fee: basefee, + }); + } } - - // Normal transaction validation - let initial_and_floor = validation::validate_initial_tx_gas_with_gas_params( - tx, - spec, - cfg.gas_params(), - disable_eip7623, - is_amsterdam_eip8037, - tx_gas_limit_cap, - eip2780, - ) - .map_err(MorphInvalidTransaction::EthInvalidTransaction)?; - - Ok(initial_and_floor) + validate_morph_tx_authorization_list(host, tx)?; } - fn catch_error( - &self, - evm: &mut Self::Evm, - error: Self::Error, - ) -> Result, Self::Error> { - MainnetHandler::default() - .catch_error(evm, error) - .map(|result| result.map_haltreason(Into::into)) - } + Ok(()) } -impl InspectorHandler for MorphEvmHandler -where - DB: alloy_evm::Database, - I: Inspector>, -{ - type IT = EthInterpreter; - - fn inspect_run( - &mut self, - evm: &mut Self::Evm, - ) -> Result, Self::Error> { - match self.inspect_run_without_catch_error(evm) { - Ok(output) => Ok(output), - Err(e) => self.catch_error(evm, e), +/// Static EIP-7702 rules for MorphTx: +/// +/// - V0/V1 must not carry an authorization list +/// - V2 with an empty list needs no extra checks (it behaves like V1) +/// - V2 with authorizations requires Prague (always true past Viridian, +/// asserted anyway) and a call target (no CREATE) +fn validate_morph_tx_authorization_list(host: &MorphEvm<'_>, tx: &MorphTxEnv) -> HandlerResult<()> { + let version = tx.version.unwrap_or_default(); + + if version < MORPH_TX_VERSION_2 { + if !tx.authorization_list.is_empty() { + return Err(MorphInvalidTransaction::AuthorizationListNotSupported { version }.into()); } + return Ok(()); } -} - -// Helper methods for MorphEvmHandler -impl MorphEvmHandler -where - DB: alloy_evm::Database, -{ - /// Static EIP-7702 rules for MorphTx, mirroring the `Eip7702` branch of - /// revm's `validate_env` that `TransactionType::Custom` skips: - /// - /// - V0/V1 must not carry an authorization list - /// - V2 with an empty list needs no extra checks (it behaves like V1) - /// - V2 with authorizations requires Prague (always true past Viridian, - /// asserted anyway) and a call target (no CREATE) - #[inline] - fn validate_morph_tx_authorization_list( - &self, - evm: &mut MorphEvm, - ) -> Result<(), EVMError> { - let tx = evm.ctx_ref().tx(); - let version = tx.version.unwrap_or_default(); - let auth_list_len = tx.authorization_list_len(); - - if version < MORPH_TX_VERSION_2 { - if auth_list_len != 0 { - return Err( - MorphInvalidTransaction::AuthorizationListNotSupported { version }.into(), - ); - } - return Ok(()); - } - - if auth_list_len == 0 { - return Ok(()); - } - - let spec: SpecId = (*evm.ctx_ref().cfg().spec()).into(); - if !spec.is_enabled_in(SpecId::PRAGUE) { - return Err(MorphInvalidTransaction::EthInvalidTransaction( - InvalidTransaction::Eip7702NotSupported, - ) - .into()); - } - if tx.kind().is_create() { - return Err(MorphInvalidTransaction::AuthorizationListCreate.into()); - } - Ok(()) + if tx.authorization_list.is_empty() { + return Ok(()); } - /// Validate and deduct ETH-based gas fees. - #[inline] - fn validate_and_deduct_eth_fee( - &self, - evm: &mut MorphEvm, - ) -> Result<(), EVMError> { - let hardfork = *evm.ctx_ref().cfg().spec(); - - // Fetch L1 block info from the L1 Gas Price Oracle contract per-tx. - // Must NOT use a per-block cache because the oracle can be updated by a - // regular transaction (from the external gas-oracle service) within the - // same block. Subsequent user txs must see the updated fee parameters, - // matching go-ethereum's per-tx L1BlockInfo read. - let l1_block_info = L1BlockInfo::try_fetch(evm.ctx_mut().db_mut(), hardfork)?; - - let rlp_bytes = evm - .ctx_ref() - .tx() - .rlp_bytes - .as_ref() - .map(|b| b.as_ref()) - .unwrap_or_default(); - - let l1_data_fee = l1_block_info.calculate_tx_l1_cost(rlp_bytes, hardfork); - evm.cached_l1_data_fee = l1_data_fee; - - let (block, tx, cfg, journal, _, _) = evm.ctx().all_mut(); - - let mut caller = journal.load_account_with_code_mut(tx.caller())?.data; + if !host.spec_id().enables(SpecId::PRAGUE) { + return Err(MorphInvalidTransaction::Eip7702NotSupported.into()); + } + if tx.kind.is_create() { + return Err(MorphInvalidTransaction::AuthorizationListCreate.into()); + } - pre_execution::validate_account_nonce_and_code( - &caller.account().info, - tx.nonce(), - cfg.is_eip3607_disabled(), - cfg.is_nonce_check_disabled(), - )?; + Ok(()) +} - let new_balance_after_l2_fee = - calculate_caller_fee_with_l1_cost(*caller.balance(), tx, block, cfg, l1_data_fee)?; +/// Returns the intrinsic gas and calldata floor gas of `tx`. +fn intrinsic_gas(host: &MorphEvm<'_>, tx: &MorphTxEnv, caller: Address) -> (u64, u64) { + let version = host.version(); + let (access_list_accounts, access_list_storage_keys) = access_list_counts(&tx.access_list); + let (intrinsic, floor_gas) = intrinsic_and_floor_gas( + version, + caller, + tx.kind, + &tx.data, + access_list_accounts, + access_list_storage_keys, + tx.value, + ); + ( + intrinsic + eip7702_authorization_gas(version, tx.authorization_list.len()), + floor_gas, + ) +} - caller.set_balance(new_balance_after_l2_fee); +/// Rejects a sender that cannot send `tx`: a contract (EIP-3607) or the wrong nonce. +fn validate_sender(host: &mut MorphEvm<'_>, caller: Address, tx_nonce: u64) -> HandlerResult<()> { + let eip3607 = host.feature(EvmFeatures::EIP3607); + let nonce_check = host.feature(EvmFeatures::NONCE_CHECK); + let mut sender = host.state_mut().account(&caller)?; - // CREATE nonce is bumped later in make_create_frame - if tx.kind().is_call() { - caller.bump_nonce(); + if eip3607 && !sender.is_empty_code_hash() { + let code = sender.load_code()?; + if !code.is_empty() && !code.is_eip7702() { + return Err(HandlerError::RejectCallerWithCode); } - - Ok(()) } + if nonce_check && sender.nonce() != tx_nonce { + return Err(HandlerError::InvalidNonce { + expected: sender.nonce(), + got: tx_nonce, + }); + } + Ok(()) +} - /// Reimburse unused gas fees in ERC20 tokens. - /// - /// Uses the cached `TokenFeeInfo` from the deduction phase to ensure - /// consistent price_ratio/scale, matching go-ethereum's `st.feeRate`/`st.tokenScale`. - #[inline] - fn reimburse_caller_token_fee( - &self, - evm: &mut MorphEvm, - gas: &Gas, - ) -> Result<(), EVMError> { - let caller = evm.ctx_ref().tx().caller(); - let beneficiary = evm.ctx_ref().block().beneficiary(); - let basefee = evm.ctx.block().basefee() as u128; - let effective_gas_price = evm.ctx.tx().effective_gas_price(basefee); - let hardfork = *evm.ctx_ref().cfg().spec(); - - let refunded = gas.refunded().max(0) as u64; - let reimburse_eth = U256::from( - effective_gas_price.saturating_mul(gas.remaining().saturating_add(refunded) as u128), - ); +/// Bumps the sender's nonce, returning its previous value. +fn bump_sender_nonce(host: &mut MorphEvm<'_>, caller: Address) -> HandlerResult { + let mut sender = host.state_mut().account(&caller)?; + let nonce = sender.nonce(); + sender.bump_nonce(); + Ok(nonce) +} - if reimburse_eth.is_zero() { - return Ok(()); - } +/// Warms what EIP-2929/2930/3651 start a transaction with, as `StateDB.Prepare` does. +/// +/// This must run after the fee deduction: the deduction's own warmth has been dropped by then +/// (see [`cool_loaded_state`]) and these accounts are warm regardless of it. +fn warm_transaction_accounts( + host: &mut MorphEvm<'_>, + tx: &MorphTxEnv, + caller: Address, +) -> HandlerResult<()> { + host.state_mut().account(&caller)?.warm(); + warm_base_accounts(host, tx.kind); + warm_access_list(host, &tx.access_list); + Ok(()) +} - // Use cached token fee info from the deduction phase (set in validate_and_deduct_token_fee). - // This ensures the same price_ratio/scale is used for both deduction and reimbursement. - // The cache is kept populated (not taken) so the block executor's receipt builder - // can also read it without re-querying the DB. - let token_fee_info = evm.cached_token_fee_info.ok_or_else(|| { - MorphInvalidTransaction::TokenTransferFailed { - reason: "cached_token_fee_info not set by validate_and_deduct_token_fee".into(), - } - })?; +/// Applies the transaction's EIP-7702 authorization list and returns the gas to refund. +/// +/// A `0x04` transaction and a MorphTx V2 go through the same routine, with the same refund +/// accounting. The list is empty for every other transaction. +fn apply_authorizations(host: &mut MorphEvm<'_>, tx: &MorphTxEnv) -> HandlerResult { + if tx.authorization_list.is_empty() { + return Ok(0); + } + let chain_id = host.version().chain_id; + let mut refunds = AuthRefunds::new(host.version()); + apply_auth_list(host, chain_id, &tx.authorization_list, &mut refunds)?; + Ok(refunds.execution_refund) +} - // From Celadon on, add back the numerator the deduction's rounding-up - // overcharged and round down, so the caller ends up paying `ceil` of the - // net fee. Before Celadon both halves round up independently, which - // under-collects; that is mainnet's history and must stay bit-identical. - // Matches go-ethereum's `refundGas` gate on `IsCeladon`. - let token_amount_required = if hardfork.is_celadon() { - token_fee_info - .eth_to_token_amount_floor(reimburse_eth, evm.cached_alt_fee_rounding_credit) - } else { - token_fee_info.eth_to_token_amount(reimburse_eth) - }; +/// The fee a transaction was charged during [`prepare`]. +struct ChargedFee { + l1_data_fee: U256, + token_fee: Option, + sender_nonce: u64, +} - // Rounding down can land on zero, which the ceiling never did for a - // non-zero `reimburse_eth`. go-ethereum's `TransferAltTokenHybrid` - // returns early on a zero amount: no `Transfer(.., 0)` log on the - // call path, and no slot writes on the direct-slot path. - if token_amount_required.is_zero() { - return Ok(()); - } +/// Fetches the L1 data fee parameters for this transaction and prices it. +/// +/// Must NOT use a per-block cache because the oracle can be updated by a regular transaction +/// (from the external gas-oracle service) within the same block. Subsequent user txs must see +/// the updated fee parameters, matching go-ethereum's per-tx `L1BlockInfo` read. +fn l1_data_fee(host: &mut MorphEvm<'_>, tx: &MorphTxEnv) -> HandlerResult { + let hardfork = host.config_spec_id(); + let state = host.state_mut(); + let l1_block_info = L1BlockInfo::try_fetch_with( + |slot| state.storage_slot_untracked(&L1_GAS_PRICE_ORACLE_ADDRESS, &slot), + hardfork, + )?; + let rlp_bytes = tx.rlp_bytes.as_ref().map(Bytes::as_ref).unwrap_or_default(); + Ok(l1_block_info.calculate_tx_l1_cost(rlp_bytes, hardfork)) +} - // Attempt token refund. Matches go-ethereum's refundGas() which silently logs - // and continues on failure: "Continue execution even if refund fails - refund - // should not cause transaction to fail" (state_transition.go:698). - let refund_result = if let Some(balance_slot) = token_fee_info.balance_slot { - let journal = evm.ctx().journal_mut(); - transfer_erc20_with_slot( - journal, - beneficiary, - caller, - token_fee_info.token_address, - token_amount_required, - balance_slot, - ) - .map(|_| ()) - } else { - // Cache refund Transfer logs separately, matching the pre_fee_logs - // pattern from validate_and_deduct_token_fee. - let log_count_before = evm.ctx_mut().journal_mut().logs.len(); - let result = transfer_erc20_with_evm( - evm, - beneficiary, - caller, - token_fee_info.token_address, - token_amount_required, - None, - ); - let refund_logs: Vec<_> = evm - .ctx_mut() - .journal_mut() - .logs - .drain(log_count_before..) - .collect(); - evm.post_fee_logs = refund_logs; - result.map(|_| ()) - }; +/// Validates the caller and deducts ETH-based gas fees, including the L1 data fee. +fn deduct_eth_fee( + host: &mut MorphEvm<'_>, + tx: &MorphTxEnv, + caller: Address, +) -> HandlerResult { + let l1_data_fee = l1_data_fee(host, tx)?; + validate_sender(host, caller, tx.nonce)?; + + let basefee = host.block().basefee.saturating_to::(); + let fee_charge = host.feature(EvmFeatures::FEE_CHARGE); + let balance_check = host.feature(EvmFeatures::BALANCE_CHECK); + + let mut sender = host.state_mut().account(&caller)?; + let new_balance = calculate_caller_fee_with_l1_cost( + sender.balance(), + tx, + basefee, + l1_data_fee, + fee_charge, + balance_check, + )?; + sender.set_balance(new_balance); + let sender_nonce = sender.nonce(); + sender.bump_nonce(); + + Ok(ChargedFee { + l1_data_fee, + token_fee: None, + sender_nonce, + }) +} - if let Err(err) = refund_result { - // A contract may reject a refund, but unavailable state is not a verdict - // about the contract. Internal calls have already taken the context error, - // so it must reach the executor here rather than disappearing at finalization. - if matches!(err, EVMError::Database(_)) { - return Err(err); - } - tracing::error!( - target: "morph::evm", - token_id = ?evm.ctx_ref().tx().fee_token_id, - %err, - "failed to refund alt token gas, continuing execution" - ); +/// Validates the caller and deducts token-based gas fees. +/// +/// This handles gas payment using ERC20 tokens instead of ETH. +fn deduct_token_fee( + host: &mut MorphEvm<'_>, + tx: &MorphTxEnv, + caller: Address, + tx_env: &TxEnv, + token_id: u16, +) -> HandlerResult { + // Token ID 0 means ETH — routed through deduct_eth_fee instead. + if token_id == 0 { + return Err(MorphInvalidTransaction::TokenIdZeroNotSupported.into()); + } + + // Validate account nonce and code (EIP-3607) BEFORE any state mutations. + validate_sender(host, caller, tx.nonce)?; + + let fee_charge = host.feature(EvmFeatures::FEE_CHARGE); + + // Real transactions must cover the transferred ETH value before token metadata is loaded. + // Simulations retain the existing value-check behavior and only add token eligibility. + if fee_charge && !tx.value.is_zero() { + let balance = host.state_mut().account(&caller)?.balance(); + if balance < tx.value { + return Err(HandlerError::InsufficientFunds { + fee: tx.value, + balance, + }); } + } - Ok(()) + let state = host.state_mut(); + let token_registry_entry = TokenRegistryEntry::load_with( + |address, slot| state.storage_slot_untracked(&address, &slot), + token_id, + )? + .ok_or(MorphInvalidTransaction::TokenNotRegistered(token_id))? + .ensure_usable(token_id)?; + + // Simulations validate token eligibility but skip balance lookup and fee deduction. + if !fee_charge { + let sender_nonce = bump_sender_nonce(host, caller)?; + return Ok(ChargedFee { + l1_data_fee: U256::ZERO, + token_fee: None, + sender_nonce, + }); } - /// Validate and deduct token-based gas fees. - /// - /// This handles gas payment using ERC20 tokens instead of ETH. - fn validate_and_deduct_token_fee( - &self, - evm: &mut MorphEvm, - token_id: u16, - ) -> Result<(), EVMError> { - // Token ID 0 means ETH — routed through validate_and_deduct_eth_fee instead. - if token_id == 0 { - return Err(MorphInvalidTransaction::TokenIdZeroNotSupported.into()); - } + let token_fee_info = load_token_fee_info(host, tx_env, token_registry_entry, caller)?; - { - let (_, tx, cfg, journal, _, _) = evm.ctx_mut().all_mut(); - let caller_addr = tx.caller(); - let nonce = tx.nonce(); - - // Validate account nonce and code (EIP-3607) BEFORE any state mutations, - // matching the order used in validate_and_deduct_eth_fee. - let caller = journal.load_account_with_code_mut(caller_addr)?.data; - pre_execution::validate_account_nonce_and_code( - &caller.account().info, - nonce, - cfg.is_eip3607_disabled(), - cfg.is_nonce_check_disabled(), - )?; - } + let beneficiary = host.block().beneficiary; + let fee_limit_from_tx = tx.fee_limit.unwrap_or_default(); - let caller_addr = evm.ctx_ref().tx().caller(); - let is_call = evm.ctx_ref().tx().kind().is_call(); - let is_fee_charge_disabled = evm.ctx_ref().cfg().is_fee_charge_disabled(); - - // Real transactions must cover the transferred ETH value before token metadata is loaded. - // Simulations retain reth's existing value-check behavior and only add token eligibility. - if !is_fee_charge_disabled { - let tx_value = evm.ctx_ref().tx().value(); - if !tx_value.is_zero() { - let caller_eth_balance = *evm - .ctx_mut() - .journal_mut() - .load_account_mut(caller_addr)? - .data - .balance(); - if caller_eth_balance < tx_value { - return Err(MorphInvalidTransaction::EthInvalidTransaction( - InvalidTransaction::LackOfFundForMaxFee { - fee: Box::new(tx_value), - balance: Box::new(caller_eth_balance), - }, - ) - .into()); - } - } - } + // Get RLP-encoded transaction bytes for L1 fee calculation + let l1_data_fee = l1_data_fee(host, tx)?; - let token_registry_entry = - TokenRegistryEntry::load(evm.ctx_mut().journal_mut().db_mut(), token_id)? - .ok_or(MorphInvalidTransaction::TokenNotRegistered(token_id))? - .ensure_usable(token_id)?; - - // Simulations validate token eligibility but skip balance lookup and fee deduction. - if is_fee_charge_disabled { - if is_call { - let mut caller = evm - .ctx_mut() - .journal_mut() - .load_account_with_code_mut(caller_addr)? - .data; - caller.bump_nonce(); - } - return Ok(()); - } + // Calculate L2 gas fee using effective_gas_price (= min(gasTipCap + baseFee, gasFeeCap)), + // matching go-ethereum's buyAltTokenGas() which uses st.gasPrice (effective gas price). + // Using the max fee would overcharge when tip + basefee < feeCap. + let l2_gas_fee = U256::from(tx.gas_limit).saturating_mul(tx_env.gas_price); - let hardfork = *evm.ctx_ref().cfg().spec(); + // Total fee in ETH + let total_eth_fee = l2_gas_fee.saturating_add(l1_data_fee); - let token_fee_info = load_token_fee_info(evm, token_registry_entry, caller_addr)?; + // Calculate token amount required for total fee. The credit is the part of + // one token unit the rounding-up overcharged; from Celadon on the refund + // hands it back (see `reimburse_token_fee`). + let (token_amount_required, rounding_credit) = + token_fee_info.eth_to_token_amount_with_credit(total_eth_fee); - let beneficiary = evm.ctx_ref().block().beneficiary(); - let rlp_bytes = evm.ctx_ref().tx().rlp_bytes.clone().unwrap_or_default(); - let gas_limit = evm.ctx_ref().tx().gas_limit(); - let fee_limit_from_tx = evm.ctx_ref().tx().fee_limit.unwrap_or_default(); - let basefee = evm.ctx_ref().block().basefee() as u128; - let effective_gas_price = evm.ctx_ref().tx().effective_gas_price(basefee); + let fee_limit = token_fee_info.effective_fee_limit(fee_limit_from_tx); - // Get RLP-encoded transaction bytes for L1 fee calculation - // Fetch L1 block info per-tx (same rationale as validate_and_deduct_eth_fee). - let l1_block_info = L1BlockInfo::try_fetch(evm.ctx_mut().journal_mut().db_mut(), hardfork)?; - let l1_data_fee = l1_block_info.calculate_tx_l1_cost(rlp_bytes.as_ref(), hardfork); + // Check if caller has sufficient token balance + if fee_limit < token_amount_required { + return Err(MorphInvalidTransaction::InsufficientTokenBalance { + required: token_amount_required, + available: fee_limit, + } + .into()); + } - // Calculate L2 gas fee using effective_gas_price (= min(gasTipCap + baseFee, gasFeeCap)), - // matching go-ethereum's buyAltTokenGas() which uses st.gasPrice (effective gas price). - // tx.gas_price() returns max_fee_per_gas and would overcharge when tip + basefee < feeCap. - let l2_gas_fee = U256::from(gas_limit).saturating_mul(U256::from(effective_gas_price)); + let mut refund_counter = 0; + if token_amount_required.is_zero() { + // Geth skips both transfer modes for a zero fee. Nonce and fee bookkeeping below + // still need their normal per-transaction updates. + } else if let Some(balance_slot) = token_fee_info.balance_slot { + // Transfer with token slot. + transfer_erc20_with_slot( + host, + caller, + beneficiary, + token_fee_info.token_address, + token_amount_required, + balance_slot, + )?; + } else { + // Transfer with evm call (from=caller, balance known from token registry). + refund_counter = transfer_erc20_with_evm( + host, + tx_env, + caller, + beneficiary, + token_fee_info.token_address, + token_amount_required, + Some(token_fee_info.balance), + )?; + } - // Total fee in ETH - let total_eth_fee = l2_gas_fee.saturating_add(l1_data_fee); + // Everything the deduction touched stays, but none of its access metadata may reach + // the main transaction. A zero fee still ran `balanceOf`, which warmed the token. + cool_loaded_state(host.state_mut()); - // Calculate token amount required for total fee. The credit is the part of - // one token unit the rounding-up overcharged; from Celadon on the refund - // hands it back (see `reimburse_caller_token_fee`). - let (token_amount_required, alt_fee_rounding_credit) = - token_fee_info.eth_to_token_amount_with_credit(total_eth_fee); + let sender_nonce = bump_sender_nonce(host, caller)?; - let fee_limit = token_fee_info.effective_fee_limit(fee_limit_from_tx); + Ok(ChargedFee { + l1_data_fee, + token_fee: Some(AppliedTokenFee { + info: token_fee_info, + rounding_credit, + refund_counter, + }), + sender_nonce, + }) +} - // Check if caller has sufficient token balance - if fee_limit < token_amount_required { - return Err(MorphInvalidTransaction::InsufficientTokenBalance { - required: token_amount_required, - available: fee_limit, - } - .into()); +/// Drops the access metadata a fee deduction left behind, keeping its state writes. +/// +/// go-ethereum's `StateDB.Prepare` rebuilds the access list and resets transient storage after +/// the deduction, before the main transaction (core/state/statedb.go:1066). The equivalent +/// here is to mark everything cold and clear transient storage: the slots' `original` values +/// are untouched, so the EIP-2200 metering of a main-frame SSTORE still sees the slot's +/// pre-transaction value and its gas stays equal to go-ethereum's. +/// +/// Transient storage can only belong to accounts a frame ran in, and those are all loaded. +fn cool_loaded_state(state: &mut State<'_>) { + let loaded: Vec<(Address, Vec)> = state + .loaded_accounts() + .map(|(address, slots)| (*address, slots.copied().collect())) + .collect(); + + for (address, slots) in loaded { + state.set_account_warm(&address, false); + for slot in slots { + state.set_storage_warm(&address, slot, false); } + state.take_transient_storage(&address); + } +} - if token_amount_required.is_zero() { - // Geth skips both transfer modes for a zero fee. Nonce and caches below - // still need their normal per-transaction updates. - } else if let Some(balance_slot) = token_fee_info.balance_slot { - // Transfer with token slot. - let journal = evm.ctx_mut().journal_mut(); - let (from_storage_slot, to_storage_slot) = transfer_erc20_with_slot( - journal, - caller_addr, - beneficiary, - token_fee_info.token_address, - token_amount_required, - balance_slot, - )?; - // We don't want the fee-token account/slots we touched during validation to become - // warm for the rest of the transaction execution. - if let Some(token_acc) = journal.state.get_mut(&token_fee_info.token_address) { - token_acc.mark_cold(); - if let Some(slot) = token_acc.storage.get_mut(&from_storage_slot) { - slot.mark_cold(); - } - if let Some(slot) = token_acc.storage.get_mut(&to_storage_slot) { - slot.mark_cold(); - } - } - } else { - // Transfer with evm call (from=caller, balance known from token registry). - evm.pre_fee_refund = transfer_erc20_with_evm( - evm, - caller_addr, - beneficiary, - token_fee_info.token_address, - token_amount_required, - Some(token_fee_info.balance), - )?; - } +/// Reimburse unused gas fees in ERC20 tokens. +/// +/// Uses the token data cached from the deduction phase to ensure a consistent +/// price_ratio/scale, matching go-ethereum's `st.feeRate`/`st.tokenScale`. +fn reimburse_token_fee( + host: &mut MorphEvm<'_>, + tx_env: &TxEnv, + caller: Address, + gas_price: U256, + unused_gas: u64, + fee: AppliedTokenFee, +) -> HandlerResult<()> { + let beneficiary = host.block().beneficiary; + let hardfork = host.config_spec_id(); + let AppliedTokenFee { + info, + rounding_credit, + .. + } = fee; + + let reimburse_eth = gas_price.saturating_mul(U256::from(unused_gas)); + if reimburse_eth.is_zero() { + return Ok(()); + } + + // From Celadon on, add back the numerator the deduction's rounding-up + // overcharged and round down, so the caller ends up paying `ceil` of the + // net fee. Before Celadon both halves round up independently, which + // under-collects; that is mainnet's history and must stay bit-identical. + // Matches go-ethereum's `refundGas` gate on `IsCeladon`. + let token_amount_required = if hardfork.is_celadon() { + info.eth_to_token_amount_floor(reimburse_eth, rounding_credit) + } else { + info.eth_to_token_amount(reimburse_eth) + }; - if token_fee_info.balance_slot.is_none() { - // balanceOf runs even for a zero fee. Geth Prepare clears its access - // list/transient storage before the main transaction in that case too. - // Cache fee Transfer logs separately from the journal. - // - // go-ethereum's StateDB.logs is independent of the state snapshot/revert - // mechanism — fee logs survive regardless of main tx result. In revm they - // would not: the `finalize()` below clears the journal's logs, and whatever - // survived would still be dropped when `execution_result` commits the - // transaction. So the fee logs are kept out of the handler pipeline entirely - // and merged back in the receipt builder. - evm.pre_fee_logs = std::mem::take(&mut evm.ctx_mut().journal_mut().logs); - - // State changes should be marked cold to avoid warm access in the main tx execution. - // Fee deduction ran a real EVM frame, so its state writes must survive while the - // frame's metadata must not: go-ethereum's `StateDB.Prepare` rebuilds the access - // list and resets transient storage before the main transaction - // (core/state/statedb.go:1066). `finalize()` is the nearest revm equivalent — it - // commits the deduction's state and drops the journal, undo history, logs and - // transient storage. - // - // `mark_cold` below only has to *drop* the warmth this frame's own CALL created; it - // does not restore what `Prepare` would have left warm, and must not try to. That - // warmth arrives later from upstream, which is why the two cannot be swapped: - // `run_without_catch_error` runs this deduction inside `validate()`, then - // `pre_execution()` → `pre_execution::load_accounts` re-warms the coinbase - // (EIP-3651) and the transaction's access list, and the nonce bump just below - // re-loads the caller. If a future change reorders those phases, a main frame that - // reads `COINBASE` would be charged 2600 instead of go-ethereum's 100; nothing here - // would catch it, because no fixture's main frame touches the coinbase. - // - // The `transaction_id` handling inside `finalize()` is load-bearing, not incidental. - // Warming a slot goes through `EvmStorageSlot::mark_warm_with_transaction_id`, which - // re-baselines the EIP-2200 `original_value` to the present value whenever the slot's - // transaction id differs from the journal's (revm-state/src/lib.rs). That must not - // happen to the slot the deduction just cleared: re-baselining it to zero would make - // the main frame's SSTORE a *create* (SSTORE_SET, 20000) rather than a *recreate* - // (100), and would drop the `SubRefund` that cancels the deduction frame's `+4800`. - // Measured on `main_restores_cleared_slot`: 23_291 gas becomes 38_391 (+19_900 - // -4_800), and the state root moves with the fee it implies. - // - // It does not happen because ids stay equal throughout execution. revm advances the - // id only when a transaction finishes — `commit_tx()` from `execution_result`, or - // `discard_tx()` on the error path — both after the main frame is done; - // `ExecuteEvm::finalize` then resets it to ZERO before the next transaction. So - // across this deduction and the main frame the journal's id is 0 — and this - // `finalize()` keeps it at 0 rather than advancing it. Swapping in `commit_tx()` here - // would leave the deduction-warmed slots holding 0 while the journal held 1, and the - // main frame's first touch of them would re-baseline `original_value`; the call-path - // fixtures under `bin/morph-statetest` catch exactly that. An explicit `mark_cold` - // carries no such risk: it drives only the warm/cold gas decision, never the - // re-baseline. - let mut state = evm.finalize(); - state.iter_mut().for_each(|(_, acc)| { - acc.mark_cold(); - acc.storage.iter_mut().for_each(|(_, slot)| { - slot.mark_cold(); - }); - }); - evm.ctx_mut().journal_mut().state.extend(state); - } + // Rounding down can land on zero, which the ceiling never did for a + // non-zero `reimburse_eth`. go-ethereum's `TransferAltTokenHybrid` + // returns early on a zero amount: no `Transfer(.., 0)` log on the + // call path, and no slot writes on the direct-slot path. + if token_amount_required.is_zero() { + return Ok(()); + } + + // Attempt token refund. Matches go-ethereum's refundGas() which silently logs + // and continues on failure: "Continue execution even if refund fails - refund + // should not cause transaction to fail" (state_transition.go:698). + let refund_result = if let Some(balance_slot) = info.balance_slot { + transfer_erc20_with_slot( + host, + beneficiary, + caller, + info.token_address, + token_amount_required, + balance_slot, + ) + } else { + transfer_erc20_with_evm( + host, + tx_env, + beneficiary, + caller, + info.token_address, + token_amount_required, + None, + ) + .map(|_| ()) + }; - // CREATE nonce is bumped later in make_create_frame - if is_call { - let mut caller = evm - .ctx_mut() - .journal_mut() - .load_account_with_code_mut(caller_addr)? - .data; - caller.bump_nonce(); + if let Err(err) = refund_result { + // A contract may reject a refund, but unavailable state is not a verdict + // about the contract, so it must reach the executor. + if matches!(err, HandlerError::Database(_) | HandlerError::Fatal(_)) { + return Err(err); } - - // Cache token fee info for the reimburse phase, ensuring consistent - // price_ratio/scale between deduction and reimbursement. - evm.cached_token_fee_info = Some(token_fee_info); - evm.cached_alt_fee_rounding_credit = alt_fee_rounding_credit; - evm.cached_l1_data_fee = l1_data_fee; - - Ok(()) + tracing::error!( + target: "morph::evm", + token = %info.token_address, + %err, + "failed to refund alt token gas, continuing execution" + ); } -} -/// Execute `f` within a journal checkpoint. Commits on `Ok`, reverts on `Err`. -#[inline] -fn with_journal_checkpoint( - journal: &mut revm::Journal, - f: impl FnOnce(&mut revm::Journal) -> Result, -) -> Result -where - DB: alloy_evm::Database, -{ - let checkpoint = journal.checkpoint(); - match f(journal) { - Ok(val) => { - journal.checkpoint_commit(); - Ok(val) - } - Err(err) => { - journal.checkpoint_revert(checkpoint); - Err(err) - } - } + Ok(()) } -/// Performs an ERC20 balance transfer by directly `sload`/`sstore`-ing the token contract storage -/// using the known `balance` mapping base slot, returning the computed storage slots for `from`/`to`. +/// Performs an ERC20 balance transfer by directly reading and writing the token contract storage +/// using the known `balance` mapping base slot. /// -/// The token account is loaded and touched here, ahead of the checkpoint, rather than by the -/// callers. The journal's `sload`/`sstore` panic instead of erroring when the account is absent -/// from `journal.state`, and touching keeps the token among the transaction's state changes even -/// for a self-transfer that writes no slot, as go-ethereum's `SetState` still marks it dirty. -#[inline] -fn transfer_erc20_with_slot( - journal: &mut revm::Journal, +/// The token is touched ahead of the checkpoint, so that it stays among the transaction's state +/// changes even for a self-transfer that writes no slot, as go-ethereum's `SetState` still marks +/// it dirty. A failure undoes the balance writes; the token stays touched. +fn transfer_erc20_with_slot( + host: &mut MorphEvm<'_>, from: Address, to: Address, token: Address, token_amount: U256, token_balance_slot: U256, -) -> Result<(U256, U256), EVMError<::Error, MorphInvalidTransaction>> -where - DB: alloy_evm::Database, -{ - let _ = journal.load_account_mut(token)?; - journal.touch(token); - with_journal_checkpoint(journal, |journal| { - // Sub amount (checked: reject if insufficient, matching go-ethereum's - // changeAltTokenBalanceByState which returns an error on underflow) - let from_storage_slot = compute_mapping_slot_for_address(token_balance_slot, from); - let from_balance = *journal.sload(token, from_storage_slot)?; - let new_from_balance = from_balance.checked_sub(token_amount).ok_or( - MorphInvalidTransaction::InsufficientTokenBalance { - required: token_amount, - available: from_balance, - }, - )?; +) -> HandlerResult<()> { + host.state_mut().account(&token)?.touch(); + + let features = host.version().features; + let checkpoint = host.state().checkpoint(); + let result = write_erc20_balances( + host.state_mut(), + from, + to, + token, + token_amount, + token_balance_slot, + ); + if result.is_err() { + host.state_mut().rollback(checkpoint, features); + } + result +} - // Self-transfers are a no-op after the balance check above. - let to_storage_slot = compute_mapping_slot_for_address(token_balance_slot, to); - if from_storage_slot == to_storage_slot { - return Ok((from_storage_slot, to_storage_slot)); - } +fn write_erc20_balances( + state: &mut State<'_>, + from: Address, + to: Address, + token: Address, + token_amount: U256, + token_balance_slot: U256, +) -> HandlerResult<()> { + // Sub amount (checked: reject if insufficient, matching go-ethereum's + // changeAltTokenBalanceByState which returns an error on underflow) + let from_storage_slot = compute_mapping_slot_for_address(token_balance_slot, from); + let from_balance = state.storage_slot(&token, from_storage_slot)?.current(); + let new_from_balance = from_balance.checked_sub(token_amount).ok_or( + MorphInvalidTransaction::InsufficientTokenBalance { + required: token_amount, + available: from_balance, + }, + )?; - // Add amount (checked: unlike go-ethereum's unbounded big.Int Add, - // we reject on overflow to maintain token conservation) - let to_balance = *journal.sload(token, to_storage_slot)?; - let new_to_balance = to_balance.checked_add(token_amount).ok_or( - MorphInvalidTransaction::TokenTransferFailed { - reason: "recipient token balance overflow".into(), - }, - )?; + // Self-transfers are a no-op after the balance check above. + let to_storage_slot = compute_mapping_slot_for_address(token_balance_slot, to); + if from_storage_slot == to_storage_slot { + return Ok(()); + } - journal.sstore(token, from_storage_slot, new_from_balance)?; - journal.sstore(token, to_storage_slot, new_to_balance)?; - Ok((from_storage_slot, to_storage_slot)) - }) + // Add amount (checked: unlike go-ethereum's unbounded big.Int Add, + // we reject on overflow to maintain token conservation) + let to_balance = state.storage_slot(&token, to_storage_slot)?.current(); + let new_to_balance = to_balance.checked_add(token_amount).ok_or_else(|| { + MorphInvalidTransaction::TokenTransferFailed { + reason: "recipient token balance overflow".into(), + } + })?; + + state + .storage_slot(&token, from_storage_slot)? + .set(new_from_balance); + state + .storage_slot(&token, to_storage_slot)? + .set(new_to_balance); + Ok(()) } -/// Gas limit for internal EVM calls (ERC20 transfer, balanceOf). -const EVM_CALL_GAS_LIMIT: u64 = 200_000; - /// Loads internal-call code without changing the account's access-list temperature. /// Geth's direct Call/StaticCall resolve code without executing a CALL opcode. -/// -/// This is also what puts `address` into `journal.state`, which [`evm_call`] depends on: -/// a `CallValue::Transfer` frame runs `Journal::transfer_loaded`, and its zero-value path -/// is `self.state.get_mut(&to).unwrap()` — a panic, not an error. In an ordinary CALL the -/// account is there because the opcode's `load_acc_and_calc_gas` put it there; an internal -/// call has no opcode, so this is the only load. Resolving the bytecode some other way -/// (caching it, hoisting it, short-circuiting on a known code hash) must keep the load. -fn internal_call_code( - journal: &mut revm::Journal, - address: Address, -) -> Result<(alloy_primitives::B256, revm::state::Bytecode), DB::Error> { - let account = journal.load_account_with_code(address)?; - let was_cold = account.is_cold; - let code = ( - account.info.code_hash(), - account.info.code.clone().unwrap_or_default(), - ); - if was_cold { - journal - .state - .get_mut(&address) - .expect("account was loaded") - .mark_cold(); - } - Ok(code) +fn internal_call_code(host: &mut MorphEvm<'_>, address: Address) -> HandlerResult { + Ok(host.state_mut().account(&address)?.load_code()?) } /// Executes a fee-token frame while retaining the outer transaction's ORIGIN/GASPRICE. /// The frame owns its VM checkpoint; a successful call is not rolled back merely /// because the token's return value or balance delta fails a later business check. -fn evm_call( - evm: &mut MorphEvm, +fn evm_call( + host: &mut MorphEvm<'_>, + tx_env: &TxEnv, caller: Address, target: Address, calldata: Bytes, is_static: bool, -) -> Result> -where - DB: alloy_evm::Database, -{ - use revm::context_interface::LocalContextTr; - use revm::interpreter::interpreter_action::FrameInit; - use revm::interpreter::{ - CallInput, CallInputs, CallScheme, CallValue, FrameInput, SharedMemory, - }; +) -> HandlerResult> { + let mut code = internal_call_code(host, target)?; + let mut code_address = target; + if let Some(delegate) = code.eip7702_address() { + code = internal_call_code(host, delegate)?; + code_address = delegate; + } - // Frame execution reports database failures through ctx.error. Check both before - // and after so a refund cannot overwrite an error from the main transaction. - take_context_error(evm)?; - let mut known_bytecode = internal_call_code(evm.ctx_mut().journal_mut(), target)?; - if let Some(delegate) = known_bytecode.1.eip7702_address() { - known_bytecode = internal_call_code(evm.ctx_mut().journal_mut(), delegate)?; - } - // Fee frames are top-level frames that run in the middle of a transaction, so - // neither of revm's truncation points covers them: `free_child_context` only - // releases a *child* frame's region, and `LocalContext::clear` only runs once the - // whole transaction is done. Carve this frame's memory out above whatever the - // shared buffer already holds and release it on the way out, so the main - // transaction frame still starts on zeroed memory the way go-ethereum's - // per-run `NewMemory()` guarantees. The frame keeps using the context's buffer - // rather than one of its own because a nested call hands its callee a - // `CallInput::SharedBuffer` range, and a precompile callee resolves that range - // against the context's buffer (`CallInput::as_bytes`) rather than against the - // calling frame's memory. - let mut fee_frame_memory = - SharedMemory::new_with_buffer(evm.ctx_ref().local().shared_memory_buffer().clone()); - let mut memory = fee_frame_memory.new_child_context(); - memory.set_memory_limit(evm.ctx_ref().cfg().memory_limit()); - let frame = FrameInit { - depth: 0, - memory, - frame_input: FrameInput::Call(Box::new(CallInputs { - input: CallInput::Bytes(calldata), - return_memory_offset: 0..0, - gas_limit: EVM_CALL_GAS_LIMIT, - reservoir: 0, - bytecode_address: target, - known_bytecode, - target_address: target, - caller, - // A zero transfer also performs geth StaticCall's legacy account touch. - value: CallValue::Transfer(U256::ZERO), - scheme: if is_static { - CallScheme::StaticCall - } else { - CallScheme::Call - }, - is_static, - charged_new_account_state_gas: false, - })), + let mut message: Message = MessageExt { + kind: if is_static { + MessageKind::StaticCall + } else { + MessageKind::Call + }, + depth: host.version().initial_call_depth, + gas_limit: EVM_CALL_GAS_LIMIT, + reservoir: 0, + destination: target, + call_target: target, + caller, + input: calldata.into(), + // A zero transfer also performs geth StaticCall's legacy account touch. + value: U256::ZERO, + code, + code_address, + caller_is_static: false, + salt: B256::ZERO, + ext: MorphMessageExt { fee_frame: true }, + _non_exhaustive: (), }; - let result = MorphEvmHandler::::new().run_exec_loop(evm, frame); - fee_frame_memory.free_child_context(); - let result = result?; - take_context_error(evm)?; - Ok(result) -} - -/// Moves a database failure recorded on the context into the return path. -#[inline] -fn take_context_error( - evm: &mut MorphEvm, -) -> Result<(), EVMError> -where - DB: alloy_evm::Database, -{ - revm::context_interface::context::take_error::< - EVMError, - DB::Error, - >(&mut evm.ctx_mut().error) + Ok(host.execute_message(tx_env, &mut message)?) } /// Queries the token using a genuine static frame, as geth's StaticCall does. /// Successful reads retain access-list warming; writes and malformed results fail. -pub(crate) fn evm_call_balance_of( - evm: &mut MorphEvm, +pub(crate) fn evm_call_balance_of( + host: &mut MorphEvm<'_>, + tx_env: &TxEnv, token: Address, account: Address, -) -> Result> -where - DB: alloy_evm::Database, -{ +) -> HandlerResult { let result = evm_call( - evm, + host, + tx_env, account, token, encode_balance_of_calldata(account), true, )?; - let output = &result.interpreter_result().output; - if !result.instruction_result().is_ok() || output.len() < 32 { + if !result.stop.is_success() || result.output.len() < 32 { return Err(MorphInvalidTransaction::TokenBalanceQueryFailed.into()); } - Ok(U256::from_be_slice(&output[..32])) + Ok(U256::from_be_slice(&result.output[..32])) } /// Resolves the caller's fee-token balance against the **executing** EVM. /// /// go-ethereum reads it through `st.evm` (`GetAltTokenBalanceHybrid`, core/token_gas.go:43), /// so the `balanceOf` call sees the real block context, the real chain config and the user as -/// `msg.sender`. Building a throwaway EVM here instead — as this path used to, through -/// `system_call_one` — answers under `BlockEnv::default()` and `CfgEnv::default()`: block 0, -/// timestamp 1, chain id 1, zero coinbase and base fee, with `SYSTEM_ADDRESS` as the sender. -/// For any token whose `balanceOf` reads that context the two clients would charge different -/// fees for the same transaction. The gas budget was never the problem: this crate's -/// `system_call_one` set the limit to its own `SYSTEM_CALL_GAS_LIMIT` — `exec.rs`, 200_000, -/// which deliberately shadows revm's `SYSTEM_CALL_GAS_LIMIT` of 30_000_000 at the -/// `SystemCallEvm` impl — and that 200k is go-ethereum's `maxGas`. [`EVM_CALL_GAS_LIMIT`] -/// carries the same number forward. -fn load_token_fee_info( - evm: &mut MorphEvm, +/// `msg.sender`. +fn load_token_fee_info( + host: &mut MorphEvm<'_>, + tx_env: &TxEnv, entry: TokenRegistryEntry, caller: Address, -) -> Result> -where - DB: alloy_evm::Database, -{ +) -> HandlerResult { let balance = match entry.balance_slot() { - // Slot mode is a plain storage read with no environment to get wrong. It goes - // through the database rather than the journal deliberately: the journal is empty - // at this point in the transaction, and an `sload` here would warm a slot that the - // fee deduction below is careful to leave cold. - Some(slot) => read_balance_from_storage( - evm.ctx_mut().journal_mut().db_mut(), - entry.token_address(), - caller, - slot, - )?, - None => evm_call_balance_of(evm, entry.token_address(), caller)?, + // Slot mode is a plain storage read with no environment to get wrong. It must not + // go through the journaled accessors: a tracked load would warm a slot that the fee + // deduction below is careful to leave cold. + Some(slot) => { + let state = host.state_mut(); + read_balance_from_storage( + |address, slot| state.storage_slot_untracked(&address, &slot), + entry.token_address(), + caller, + slot, + )? + } + None => evm_call_balance_of(host, tx_env, entry.token_address(), caller)?, }; Ok(entry.into_fee_info(caller, balance)) } @@ -1092,32 +935,26 @@ where /// 2. Validates ABI-decoded bool return value (supports old tokens with no return data) /// 3. Verifies sender balance changed by the expected amount /// -/// Uses [`evm_call`] instead of `system_call_one_with_caller` so that event logs -/// (e.g., ERC20 Transfer) naturally remain in the journal and appear in the -/// transaction receipt, matching go-ethereum's `evm.Call()` behavior. -/// /// `from_balance_before` is the sender's balance before the transfer. If `None`, /// the balance is queried via EVM call (matching go-eth's nil `userBalanceBefore`). /// Returns the signed refund counter for successful transfers; the deduction phase /// carries it into transaction gas accounting, while reimbursement ignores it. -fn transfer_erc20_with_evm( - evm: &mut MorphEvm, +fn transfer_erc20_with_evm( + host: &mut MorphEvm<'_>, + tx_env: &TxEnv, from: Address, to: Address, token_address: Address, token_amount: U256, from_balance_before: Option, -) -> Result> -where - DB: alloy_evm::Database, -{ +) -> HandlerResult { if token_amount.is_zero() { return Ok(0); } // Read sender balance before transfer if not provided. let from_balance_before = match from_balance_before { - Some(b) => b, - None => evm_call_balance_of(evm, token_address, from)?, + Some(balance) => balance, + None => evm_call_balance_of(host, tx_env, token_address, from)?, }; // Geth checks affordability before executing the token contract. @@ -1130,17 +967,11 @@ where })?; let calldata = build_transfer_calldata(to, token_amount); - let frame_result = - evm_call(evm, from, token_address, calldata, false).map_err(|e| match e { - EVMError::Database(_) => e, - _ => EVMError::Transaction(MorphInvalidTransaction::TokenTransferFailed { - reason: format!("Error: {e:?}"), - }), - })?; + let result = evm_call(host, tx_env, from, token_address, calldata, false)?; - if !frame_result.instruction_result().is_ok() { + if !result.stop.is_success() { return Err(MorphInvalidTransaction::TokenTransferFailed { - reason: format!("{:?}", frame_result.interpreter_result()), + reason: format!("{:?}", result.stop), } .into()); } @@ -1149,7 +980,7 @@ where // - No return data: accepted (old tokens that don't return bool) // - 32+ bytes with last byte == 1: accepted (standard ERC20) // - Otherwise: rejected - let output = &frame_result.interpreter_result().output; + let output = &result.output; if !output.is_empty() && (output.len() < 32 || output[31] != 1) { return Err(MorphInvalidTransaction::TokenTransferFailed { reason: "alt token transfer returned failure".to_string(), @@ -1158,7 +989,7 @@ where } // Verify sender balance changed by the expected amount, matching go-ethereum. - let from_balance_after = evm_call_balance_of(evm, token_address, from)?; + let from_balance_after = evm_call_balance_of(host, tx_env, token_address, from)?; // Verify sender balance decreased by exactly the transfer amount. // Matches go-ethereum's transferAltTokenByEVM which always checks this, @@ -1173,14 +1004,14 @@ where .into()); } - Ok(frame_result.gas().refunded()) + Ok(result.gas.refunded()) } /// Build the calldata for ERC20 `transfer(address,uint256)` call. /// /// Method selector: `0xa9059cbb` #[inline] -fn build_transfer_calldata(to: Address, token_amount: alloy_primitives::Uint<256, 4>) -> Bytes { +fn build_transfer_calldata(to: Address, token_amount: U256) -> Bytes { let method_id = [0xa9u8, 0x05, 0x9c, 0xbb]; // Encode calldata: method_id + padded to address + amount let mut calldata = Vec::with_capacity(68); @@ -1194,67 +1025,54 @@ fn build_transfer_calldata(to: Address, token_amount: alloy_primitives::Uint<256 /// Calculate the new balance after deducting L2 fees and L1 data fee. /// -/// This is a Morph-specific version of `pre_execution::calculate_caller_fee` that -/// also includes the L1 data fee in the balance calculation. -/// -/// # Arguments -/// * `balance` - Current caller balance -/// * `tx` - Transaction -/// * `block` - Block environment -/// * `cfg` - Configuration -/// * `l1_data_fee` - L1 data fee calculated from L1BlockInfo -/// /// # Returns /// The new balance after deducting all fees, or an error if balance is insufficient. -#[inline] fn calculate_caller_fee_with_l1_cost( balance: U256, - tx: impl Transaction, - block: impl Block, - cfg: impl Cfg, + tx: &MorphTxEnv, + basefee: u128, l1_data_fee: U256, -) -> Result { + fee_charge: bool, + balance_check: bool, +) -> HandlerResult { // Simulation paths must not consume the caller balance. - if cfg.is_fee_charge_disabled() { + if !fee_charge { return Ok(balance); } - let basefee = block.basefee() as u128; - let blob_price = block.blob_gasprice().unwrap_or_default(); - let is_balance_check_disabled = cfg.is_balance_check_disabled(); - // Validate balance against max possible spending using max_fee_per_gas (not effective_gas_price). // go-eth's buyGas() checks: balance >= gasFeeCap * gas + value + l1DataFee. // This ensures the sender can afford the worst-case gas cost before deducting the actual cost. - if !is_balance_check_disabled { - let max_gas_spending = U256::from( - (tx.gas_limit() as u128) - .checked_mul(tx.max_fee_per_gas()) - .ok_or(InvalidTransaction::OverflowPaymentInTransaction)?, - ); + if balance_check { + let max_gas_spending = (tx.gas_limit as u128) + .checked_mul(tx.gas_price) + .map(U256::from) + .ok_or(MorphInvalidTransaction::OverflowPaymentInTransaction)?; let max_spending = max_gas_spending - .checked_add(tx.value()) + .checked_add(tx.value) .and_then(|v| v.checked_add(l1_data_fee)) - .ok_or(InvalidTransaction::OverflowPaymentInTransaction)?; + .ok_or(MorphInvalidTransaction::OverflowPaymentInTransaction)?; if balance < max_spending { - return Err(InvalidTransaction::LackOfFundForMaxFee { - fee: Box::new(max_spending), - balance: Box::new(balance), + return Err(HandlerError::InsufficientFunds { + fee: max_spending, + balance, }); } } // Deduct using effective_gas_price (not max_fee_per_gas). // go-eth's buyGas(): SubBalance(from, gasPrice * gas + l1DataFee) - let effective_balance_spending = tx.effective_balance_spending(basefee, blob_price)?; - let gas_balance_spending = effective_balance_spending - tx.value(); + let gas_balance_spending = (tx.gas_limit as u128) + .checked_mul(tx.effective_gas_price_at(basefee)) + .map(U256::from) + .ok_or(MorphInvalidTransaction::OverflowPaymentInTransaction)?; let total_fee_deduction = gas_balance_spending.saturating_add(l1_data_fee); let mut new_balance = balance.saturating_sub(total_fee_deduction); - if is_balance_check_disabled { + if !balance_check { // Make sure the caller's balance is at least the value of the transaction. - new_balance = new_balance.max(tx.value()); + new_balance = new_balance.max(tx.value); } Ok(new_balance) @@ -1263,187 +1081,150 @@ fn calculate_caller_fee_with_l1_cost( #[cfg(test)] mod tests { use super::*; - use crate::MorphTxEnv; - use crate::token_fee::tests::{TokenReadFailure, UnreadableTokenDb}; - use crate::{ - MorphBlockEnv, - token_fee::{L2_TOKEN_REGISTRY_ADDRESS, compute_mapping_slot}, + use crate::token_fee::{ + L2_TOKEN_REGISTRY_ADDRESS, compute_mapping_slot, + tests::{UnreadableTokenDb, is_token_read_failure}, }; - use alloy_primitives::{B256, Bytes, TxKind, address, keccak256}; - use morph_chainspec::hardfork::MorphHardfork; - use morph_primitives::MORPH_TX_TYPE_ID; - use revm::{ - context::{BlockEnv, TxEnv}, - context_interface::{cfg::gas_params::GasId, result::InvalidTransaction}, - database::{CacheDB, EmptyDB}, - inspector::NoOpInspector, - state::{AccountInfo, Bytecode}, + use crate::{MorphBlockEnv, MorphEvmEnv, evm::morph_evm, evm::morph_evm_env}; + use alloy_consensus::transaction::Recovered; + use alloy_eips::eip7702::{ + Authorization, RecoveredAuthority, RecoveredAuthorization, SignedAuthorization, }; + use alloy_primitives::{Log, TxKind, address, b256}; + use evm2::{ + Inspector, + ethereum::LazyAuthorization, + evm::{AccountInfo, Database, Db, DynDatabase, InMemoryDB}, + interpreter::Interpreter, + version::GasId, + }; + use morph_chainspec::hardfork::MorphHardfork; + use morph_primitives::transaction::morph_transaction::MORPH_TX_VERSION_1; use std::sync::{ Arc, atomic::{AtomicBool, Ordering}, }; - fn finish_transaction_with_refund( - code: Bytes, - ) -> Result, EVMError> - { - let caller = address!("1000000000000000000000000000000000000001"); - let beneficiary = address!("2000000000000000000000000000000000000002"); - let token = address!("3000000000000000000000000000000000000003"); - let target = address!("4000000000000000000000000000000000000004"); - let mut inner = CacheDB::new(EmptyDB::default()); - inner.insert_account_info( - token, - AccountInfo { - code_hash: keccak256(code.as_ref()), - code: Some(Bytecode::new_raw(code)), - ..Default::default() - }, - ); - let mut evm = MorphEvm::new( - MorphContext::new(UnreadableTokenDb { inner, token }, MorphHardfork::Emerald), - NoOpInspector, - ); - evm.block.inner.beneficiary = beneficiary; - // Produce a real successful main frame. The remainder of this probe enters the - // normal reimbursement and result-finalization phases with an unused gas budget. - let frame = evm_call(&mut evm, caller, target, Bytes::new(), false).unwrap(); - evm.tx = MorphTxEnv { - inner: TxEnv { - tx_type: MORPH_TX_TYPE_ID, - caller, - gas_price: 1, - gas_limit: 30_000, - kind: TxKind::Call(target), - ..Default::default() - }, - fee_token_id: Some(1), - ..Default::default() - }; - evm.cached_token_fee_info = Some(TokenFeeInfo { - token_address: token, - is_active: true, - price_ratio: U256::from(1), - scale: U256::from(1), - caller, - balance: U256::from(100_000), - balance_slot: None, - ..Default::default() - }); - let mut handler = MorphEvmHandler::<_, NoOpInspector>::default(); - handler - .reimburse_caller_token_fee(&mut evm, &Gas::new(1_000)) - .and_then(|_| handler.execution_result(&mut evm, frame, ResultGas::default())) + /// The environment most tests run under: a block with room for any test transaction. + fn test_env(spec: MorphHardfork, block: MorphBlockEnv) -> MorphEvmEnv { + morph_evm_env(spec, 1, 30_000_000, block) } - /// A readable token under [`UnreadableTokenDb`], so any failure reported below comes - /// from the context, not from a read. - fn readable_token_evm() -> MorphEvm { - let token = address!("3000000000000000000000000000000000000003"); - let mut inner = CacheDB::new(EmptyDB::default()); - insert_contract( - &mut inner, - token, - alloy_primitives::bytes!("6000545f5260205ff3"), - ); - inner - .insert_account_storage(token, U256::ZERO, U256::from(42)) - .unwrap(); - MorphEvm::new( - MorphContext::new( - UnreadableTokenDb { - inner, - // Nothing reads this address, so every storage read succeeds. - token: address!("9000000000000000000000000000000000000009"), - }, - MorphHardfork::Emerald, - ), - NoOpInspector, - ) + fn evm_on<'a>( + database: impl DynDatabase + 'a, + spec: MorphHardfork, + block: MorphBlockEnv, + ) -> MorphEvm<'a> { + morph_evm(database, test_env(spec, block)) } - #[test] - fn a_nested_call_does_not_run_in_a_context_the_main_frame_already_poisoned() { - let token = address!("3000000000000000000000000000000000000003"); - let account = address!("1000000000000000000000000000000000000001"); - let mut evm = readable_token_evm(); - assert_eq!( - evm_call_balance_of(&mut evm, token, account).unwrap(), - U256::from(42), - "sanity: the token is readable" - ); + fn evm_with_spec(spec: MorphHardfork) -> MorphEvm<'static> { + evm_on(InMemoryDB::default(), spec, MorphBlockEnv::default()) + } - // The main frame halted on a failed read; post-execution then reaches this call. - evm.ctx_mut().error = Err(revm::context_interface::context::ContextError::Db( - TokenReadFailure, - )); - let result = evm_call_balance_of(&mut evm, token, account); - assert!( - matches!(result, Err(EVMError::Database(TokenReadFailure))), - "the main frame's failure must be reported, not overwritten by a nested call: {result:?}" + /// A transaction environment with `origin` and no gas price. + fn tx_env_of(origin: Address) -> TxEnv { + TxEnvExt { + origin, + ..TxEnvExt::default() + } + } + + fn insert_contract(db: &mut InMemoryDB, address: Address, code: Bytes) { + db.insert_account_info( + &address, + AccountInfo::default().with_code(Bytecode::new_legacy(code)), ); - assert!( - evm.ctx_ref().error.is_ok(), - "the failure has been moved into the return path" + } + + fn fund(db: &mut InMemoryDB, address: Address, balance: u64) { + db.insert_account_info( + &address, + AccountInfo::default().with_balance(U256::from(balance)), ); } - #[test] - fn a_refund_after_a_poisoned_main_frame_reports_the_main_frame_failure() { + fn transact( + evm: &mut MorphEvm<'_>, + tx: MorphTxEnv, + caller: Address, + ) -> HandlerResult> { + let tx = Recovered::new_unchecked(tx, caller); + evm.transact(&tx).map(|executed| executed.commit()) + } + + fn storage_of(evm: &mut MorphEvm<'_>, address: Address, key: U256) -> U256 { + evm.state_mut() + .storage_slot_untracked(&address, &key) + .unwrap() + } + + fn morph_error(error: &HandlerError) -> &MorphInvalidTransaction { + error + .external_ref::() + .unwrap_or_else(|| panic!("expected a Morph error, got {error:?}")) + } + + fn no_state_loaded(evm: &MorphEvm<'_>) -> bool { + evm.state().loaded_accounts().next().is_none() + } + + const REFUND_PROBE_TOKEN: Address = address!("3000000000000000000000000000000000000003"); + + /// Runs the token refund against a token implementing `code`. + fn refund_against_token(database: impl DynDatabase) -> HandlerResult<()> { let caller = address!("1000000000000000000000000000000000000001"); - let token = address!("3000000000000000000000000000000000000003"); - let mut evm = readable_token_evm(); - evm.block.inner.beneficiary = address!("2000000000000000000000000000000000000002"); - evm.tx = MorphTxEnv { - inner: TxEnv { - tx_type: MORPH_TX_TYPE_ID, - caller, - gas_price: 1, - gas_limit: 30_000, - ..Default::default() - }, - fee_token_id: Some(1), + let block = MorphBlockEnv { + beneficiary: address!("2000000000000000000000000000000000000002"), ..Default::default() }; - evm.cached_token_fee_info = Some(TokenFeeInfo { - token_address: token, - is_active: true, - price_ratio: U256::from(1), - scale: U256::from(1), + let mut evm = evm_on(database, MorphHardfork::Emerald, block); + reimburse_token_fee( + &mut evm, + &tx_env_of(caller), caller, - balance: U256::from(100_000), - balance_slot: None, - ..Default::default() - }); - evm.ctx_mut().error = Err(revm::context_interface::context::ContextError::Db( - TokenReadFailure, - )); + U256::from(1), + 1_000, + AppliedTokenFee { + info: TokenFeeInfo { + token_address: REFUND_PROBE_TOKEN, + is_active: true, + price_ratio: U256::from(1), + scale: U256::from(1), + caller, + balance: U256::from(100_000), + balance_slot: None, + ..Default::default() + }, + rounding_credit: U256::ZERO, + refund_counter: 0, + }, + ) + } - let result = MorphEvmHandler::<_, NoOpInspector>::default() - .reimburse_caller_token_fee(&mut evm, &Gas::new(1_000)); - assert!( - matches!(result, Err(EVMError::Database(TokenReadFailure))), - "{result:?}" - ); + fn token_db_with_code(code: Bytes) -> InMemoryDB { + let mut inner = InMemoryDB::default(); + insert_contract(&mut inner, REFUND_PROBE_TOKEN, code); + inner } #[test] fn refund_database_failure_aborts_final_execution_result() { - let result = finish_transaction_with_refund(alloy_primitives::bytes!("6000545f5260205ff3")); + let result = refund_against_token(Db::new(UnreadableTokenDb { + inner: token_db_with_code(alloy_primitives::bytes!("6000545f5260205ff3")), + token: REFUND_PROBE_TOKEN, + })); + let error = result.unwrap_err(); assert!( - matches!(result, Err(EVMError::Database(TokenReadFailure))), - "refund I/O must abort execution, not finalize success without a refund: {result:?}" + is_token_read_failure(&error), + "refund I/O must abort execution, not finalize success without a refund: {error:?}" ); } #[test] fn refund_contract_revert_still_allows_transaction_to_finish() { - let result = finish_transaction_with_refund(alloy_primitives::bytes!("5f5ffd")); - assert!( - matches!(result, Ok(ExecutionResult::Success { .. })), - "{result:?}" - ); + let result = refund_against_token(token_db_with_code(alloy_primitives::bytes!("5f5ffd"))); + assert!(result.is_ok(), "{result:?}"); } #[test] @@ -1451,28 +1232,28 @@ mod tests { let token = address!("3000000000000000000000000000000000000003"); let from = address!("1000000000000000000000000000000000000001"); let to = address!("2000000000000000000000000000000000000002"); - let mut inner = CacheDB::new(EmptyDB::default()); + let mut inner = InMemoryDB::default(); insert_contract( &mut inner, token, alloy_primitives::bytes!("6000545f5260205ff3"), ); - let mut evm = MorphEvm::new( - MorphContext::new(UnreadableTokenDb { inner, token }, MorphHardfork::Emerald), - NoOpInspector, + let mut evm = evm_on( + Db::new(UnreadableTokenDb { inner, token }), + MorphHardfork::Emerald, + MorphBlockEnv::default(), ); - let result = transfer_erc20_with_evm( + let error = transfer_erc20_with_evm( &mut evm, + &tx_env_of(from), from, to, token, U256::from(1), Some(U256::from(10)), - ); - assert!( - matches!(result, Err(EVMError::Database(TokenReadFailure))), - "{result:?}" - ); + ) + .unwrap_err(); + assert!(is_token_read_failure(&error), "{error:?}"); } fn mutating_return_code(write_value: u8, return_value: u8) -> Bytes { @@ -1497,34 +1278,34 @@ mod tests { #[derive(Debug)] struct TokenAccessTrackingDb { - inner: CacheDB, + inner: InMemoryDB, token: Address, token_accessed: Arc, } - impl revm::Database for TokenAccessTrackingDb { - type Error = std::convert::Infallible; + impl Database for TokenAccessTrackingDb { + type Error = evm2::DatabaseError; - fn basic(&mut self, address: Address) -> Result, Self::Error> { - if address == self.token { + fn get_account(&mut self, address: &Address) -> Result, Self::Error> { + if *address == self.token { self.token_accessed.store(true, Ordering::Relaxed); } - revm::Database::basic(&mut self.inner, address) + DynDatabase::get_account(&mut self.inner, address) } - fn code_by_hash(&mut self, code_hash: B256) -> Result { - revm::Database::code_by_hash(&mut self.inner, code_hash) + fn get_code_by_hash(&mut self, code_hash: &B256) -> Result { + DynDatabase::get_code_by_hash(&mut self.inner, code_hash) } - fn storage(&mut self, address: Address, index: U256) -> Result { - if address == self.token { + fn get_storage(&mut self, address: &Address, key: &Word) -> Result { + if *address == self.token { self.token_accessed.store(true, Ordering::Relaxed); } - revm::Database::storage(&mut self.inner, address, index) + DynDatabase::get_storage(&mut self.inner, address, key) } - fn block_hash(&mut self, number: u64) -> Result { - revm::Database::block_hash(&mut self.inner, number) + fn get_block_hash(&mut self, number: &Word) -> Result { + DynDatabase::get_block_hash(&mut self.inner, number) } } @@ -1535,26 +1316,17 @@ mod tests { Bytes::from(vec![opcode, 0x5f, 0x52, 0x60, 0x20, 0x5f, 0xf3]) } - fn insert_contract(db: &mut CacheDB, address: Address, code: Bytes) { - db.insert_account_info( - address, - AccountInfo { - code_hash: keccak256(code.as_ref()), - code: Some(Bytecode::new_raw(code)), - ..Default::default() - }, - ); - } - /// Loads token 1's registry entry and resolves `caller`'s balance against `evm`. - fn probe_fee_token_balance(db: CacheDB, block: BlockEnv, caller: Address) -> U256 { - let mut evm = MorphEvm::new(MorphContext::new(db, MorphHardfork::Emerald), NoOpInspector); - evm.block = MorphBlockEnv { inner: block }; - - let entry = TokenRegistryEntry::load(evm.ctx_mut().journal_mut().db_mut(), 1) - .unwrap() - .unwrap(); - load_token_fee_info(&mut evm, entry, caller) + fn probe_fee_token_balance(db: InMemoryDB, block: MorphBlockEnv, caller: Address) -> U256 { + let mut evm = evm_on(db, MorphHardfork::Emerald, block); + let state = evm.state_mut(); + let entry = TokenRegistryEntry::load_with( + |address, slot| state.storage_slot_untracked(&address, &slot), + 1, + ) + .unwrap() + .unwrap(); + load_token_fee_info(&mut evm, &tx_env_of(caller), entry, caller) .unwrap() .balance } @@ -1565,13 +1337,13 @@ mod tests { let token = address!("5300000000000000000000000000000000000042"); let caller = address!("1000000000000000000000000000000000000001"); - let mut db = CacheDB::new(EmptyDB::default()); + let mut db = InMemoryDB::default(); insert_test_fee_token(&mut db, 1, token, true); insert_contract(&mut db, token, code_returning(0x42)); // TIMESTAMP let balance = probe_fee_token_balance( db, - BlockEnv { + MorphBlockEnv { timestamp: U256::from(TIMESTAMP), ..Default::default() }, @@ -1588,28 +1360,23 @@ mod tests { let token = address!("5300000000000000000000000000000000000042"); let caller = address!("1000000000000000000000000000000000000001"); - let mut db = CacheDB::new(EmptyDB::default()); + let mut db = InMemoryDB::default(); insert_test_fee_token(&mut db, 1, token, true); insert_contract(&mut db, token, code_returning(0x33)); // CALLER - let balance = probe_fee_token_balance(db, BlockEnv::default(), caller); + let balance = probe_fee_token_balance(db, MorphBlockEnv::default(), caller); // go-ethereum queries as the account being asked about, not as the zero address and // not as `SYSTEM_ADDRESS`. assert_eq!(balance, U256::from_be_bytes(caller.into_word().0)); } - fn insert_test_fee_token( - db: &mut CacheDB, - token_id: u16, - token: Address, - is_active: bool, - ) { + fn insert_test_fee_token(db: &mut InMemoryDB, token_id: u16, token: Address, is_active: bool) { insert_test_fee_token_config(db, token_id, token, is_active, U256::from(1), U256::from(1)); } fn insert_test_fee_token_config( - db: &mut CacheDB, + db: &mut InMemoryDB, token_id: u16, token: Address, is_active: bool, @@ -1621,92 +1388,83 @@ mod tests { let base = compute_mapping_slot(U256::from(151), &token_id_bytes); db.insert_account_storage( - L2_TOKEN_REGISTRY_ADDRESS, - base, - U256::from_be_bytes(token.into_word().0), - ) - .unwrap(); + &L2_TOKEN_REGISTRY_ADDRESS, + &base, + &U256::from_be_bytes(token.into_word().0), + ); let mut status = [0u8; 32]; status[30] = 18; status[31] = u8::from(is_active); db.insert_account_storage( - L2_TOKEN_REGISTRY_ADDRESS, - base + U256::from(2), - U256::from_be_bytes(status), - ) - .unwrap(); - db.insert_account_storage(L2_TOKEN_REGISTRY_ADDRESS, base + U256::from(3), scale) - .unwrap(); + &L2_TOKEN_REGISTRY_ADDRESS, + &(base + U256::from(2)), + &U256::from_be_bytes(status), + ); + db.insert_account_storage(&L2_TOKEN_REGISTRY_ADDRESS, &(base + U256::from(3)), &scale); db.insert_account_storage( - L2_TOKEN_REGISTRY_ADDRESS, - compute_mapping_slot(U256::from(153), &token_id_bytes), - price_ratio, - ) - .unwrap(); + &L2_TOKEN_REGISTRY_ADDRESS, + &compute_mapping_slot(U256::from(153), &token_id_bytes), + &price_ratio, + ); } - fn token_fee_simulation_evm( - db: DB, - caller: Address, - token_id: u16, - ) -> MorphEvm - where - DB: alloy_evm::Database, - { - let mut evm = MorphEvm::new( - MorphContext::new(db, MorphHardfork::default()), - NoOpInspector, - ); - evm.cfg.disable_fee_charge = true; - evm.tx = MorphTxEnv { - inner: TxEnv { - tx_type: MORPH_TX_TYPE_ID, - gas_limit: 21_000, - caller, - kind: TxKind::Call(Address::ZERO), - ..Default::default() - }, + /// An environment with fee charging disabled, as simulations run. + fn simulation_env() -> MorphEvmEnv { + let mut env = test_env(MorphHardfork::default(), MorphBlockEnv::default()); + env.version.features.remove(EvmFeatures::FEE_CHARGE); + env + } + + fn token_fee_simulation_tx(token_id: u16) -> MorphTxEnv { + MorphTxEnv { + tx_type: MORPH_TX_TYPE_ID, + gas_limit: 21_000, + kind: TxKind::Call(Address::ZERO), fee_token_id: Some(token_id), ..Default::default() - }; - evm + } + } + + /// Runs the deduction of a simulated token-fee transaction. + fn simulate_token_fee<'a>( + database: impl DynDatabase + 'a, + caller: Address, + token_id: u16, + ) -> HandlerResult { + let mut evm = morph_evm(database, simulation_env()); + deduct_token_fee( + &mut evm, + &token_fee_simulation_tx(token_id), + caller, + &tx_env_of(caller), + token_id, + ) } #[test] fn validate_env_rejects_token_fee_morph_tx_below_base_fee() { - let mut evm = MorphEvm::new( - MorphContext::new(CacheDB::new(EmptyDB::default()), MorphHardfork::default()), - NoOpInspector, - ); - evm.block = MorphBlockEnv { - inner: BlockEnv { - basefee: 100, - ..Default::default() - }, - }; - evm.tx = MorphTxEnv { - inner: TxEnv { - tx_type: MORPH_TX_TYPE_ID, - gas_limit: 21_000, - gas_price: 99, - gas_priority_fee: Some(1), - kind: TxKind::Call(Address::ZERO), + let evm = evm_on( + InMemoryDB::default(), + MorphHardfork::default(), + MorphBlockEnv { + basefee: U256::from(100), ..Default::default() }, + ); + let tx = MorphTxEnv { + tx_type: MORPH_TX_TYPE_ID, + gas_limit: 21_000, + gas_price: 99, + gas_priority_fee: Some(1), + kind: TxKind::Call(Address::ZERO), fee_token_id: Some(1), ..Default::default() }; - let err = - as Handler>::validate_env(&MorphEvmHandler::default(), &mut evm) - .unwrap_err(); - assert!(matches!( - err, - EVMError::Transaction(MorphInvalidTransaction::EthInvalidTransaction( - InvalidTransaction::GasPriceLessThanBasefee - )) + validate_env(&evm, &tx).unwrap_err(), + HandlerError::FeeCapLessThanBaseFee { .. } )); } @@ -1714,13 +1472,8 @@ mod tests { // MorphTx V2 (EIP-7702 authorization list) handler rules // ========================================================================= - use alloy_consensus::transaction::Either; - use alloy_eips::eip7702::{Authorization, RecoveredAuthority}; - use morph_primitives::transaction::morph_transaction::MORPH_TX_VERSION_1; - use revm::context_interface::transaction::{RecoveredAuthorization, SignedAuthorization}; - - fn sample_signed_authorization() -> SignedAuthorization { - Authorization { + fn sample_signed_authorization() -> LazyAuthorization { + let signed: SignedAuthorization = Authorization { chain_id: U256::from(1), address: Address::with_last_byte(0x42), nonce: 0, @@ -1729,7 +1482,8 @@ mod tests { U256::from(1), U256::from(2), true, - )) + )); + LazyAuthorization::Signed(signed) } fn recovered_authorization( @@ -1737,8 +1491,8 @@ mod tests { delegate: Address, chain_id: u64, auth_nonce: u64, - ) -> Either { - Either::Right(RecoveredAuthorization::new_unchecked( + ) -> LazyAuthorization { + LazyAuthorization::Recovered(RecoveredAuthorization::new_unchecked( Authorization { chain_id: U256::from(chain_id), address: delegate, @@ -1751,557 +1505,411 @@ mod tests { fn morph_tx_env_with_authorizations( version: Option, kind: TxKind, - authorization_list: Vec>, + authorization_list: Vec, ) -> MorphTxEnv { MorphTxEnv { - inner: TxEnv { - tx_type: MORPH_TX_TYPE_ID, - gas_limit: 100_000, - kind, - authorization_list, - ..Default::default() - }, + tx_type: MORPH_TX_TYPE_ID, + gas_limit: 100_000, + kind, + authorization_list, version, fee_token_id: Some(0), ..Default::default() } } - fn evm_with_spec(spec: MorphHardfork) -> MorphEvm, NoOpInspector> { - MorphEvm::new( - MorphContext::new(CacheDB::new(EmptyDB::default()), spec), - NoOpInspector, + fn v2_env_with(authorization_list: Vec) -> MorphTxEnv { + morph_tx_env_with_authorizations( + Some(MORPH_TX_VERSION_2), + TxKind::Call(Address::ZERO), + authorization_list, ) } - fn validate_env_of( - evm: &mut MorphEvm, NoOpInspector>, - ) -> Result<(), EVMError> { - as Handler>::validate_env(&MorphEvmHandler::default(), evm) + fn validate_env_of(spec: MorphHardfork, tx: &MorphTxEnv) -> HandlerResult<()> { + validate_env(&evm_with_spec(spec), tx) } #[test] fn validate_env_accepts_v2_morph_tx_with_authorization_list() { - let mut evm = evm_with_spec(MorphHardfork::Celadon); - evm.tx = morph_tx_env_with_authorizations( - Some(MORPH_TX_VERSION_2), - TxKind::Call(Address::ZERO), - vec![Either::Left(sample_signed_authorization())], - ); - - assert!(validate_env_of(&mut evm).is_ok()); + let tx = v2_env_with(vec![sample_signed_authorization()]); + assert!(validate_env_of(MorphHardfork::Celadon, &tx).is_ok()); } #[test] fn validate_env_rejects_v1_morph_tx_with_authorization_list() { - let mut evm = evm_with_spec(MorphHardfork::Celadon); - evm.tx = morph_tx_env_with_authorizations( + let tx = morph_tx_env_with_authorizations( Some(MORPH_TX_VERSION_1), TxKind::Call(Address::ZERO), - vec![Either::Left(sample_signed_authorization())], + vec![sample_signed_authorization()], ); - let err = validate_env_of(&mut evm).unwrap_err(); + let err = validate_env_of(MorphHardfork::Celadon, &tx).unwrap_err(); assert!(matches!( - err, - EVMError::Transaction(MorphInvalidTransaction::AuthorizationListNotSupported { + morph_error(&err), + MorphInvalidTransaction::AuthorizationListNotSupported { version: MORPH_TX_VERSION_1 - }) + } )); } /// A V2 with an empty list is a V1 in all but the version byte: no 7702 - /// static rule applies (revm's `EmptyAuthorizationList` is `0x04`-only). + /// static rule applies (`EmptyAuthorizationList` is `0x04`-only). #[test] fn validate_env_accepts_v2_morph_tx_with_empty_authorization_list() { - let mut evm = evm_with_spec(MorphHardfork::Celadon); - evm.tx = morph_tx_env_with_authorizations( - Some(MORPH_TX_VERSION_2), - TxKind::Call(Address::ZERO), - vec![], - ); - - assert!(validate_env_of(&mut evm).is_ok()); + let tx = v2_env_with(vec![]); + assert!(validate_env_of(MorphHardfork::Celadon, &tx).is_ok()); } /// Without authorizations a V2 may create a contract, exactly like V1. #[test] fn validate_env_accepts_v2_morph_tx_create_without_authorizations() { - let mut evm = evm_with_spec(MorphHardfork::Celadon); - evm.tx = morph_tx_env_with_authorizations(Some(MORPH_TX_VERSION_2), TxKind::Create, vec![]); - - assert!(validate_env_of(&mut evm).is_ok()); + let tx = morph_tx_env_with_authorizations(Some(MORPH_TX_VERSION_2), TxKind::Create, vec![]); + assert!(validate_env_of(MorphHardfork::Celadon, &tx).is_ok()); } #[test] fn validate_env_rejects_v2_morph_tx_create() { - let mut evm = evm_with_spec(MorphHardfork::Celadon); - evm.tx = morph_tx_env_with_authorizations( + let tx = morph_tx_env_with_authorizations( Some(MORPH_TX_VERSION_2), TxKind::Create, - vec![Either::Left(sample_signed_authorization())], + vec![sample_signed_authorization()], ); - let err = validate_env_of(&mut evm).unwrap_err(); + let err = validate_env_of(MorphHardfork::Celadon, &tx).unwrap_err(); assert!(matches!( - err, - EVMError::Transaction(MorphInvalidTransaction::AuthorizationListCreate) + morph_error(&err), + MorphInvalidTransaction::AuthorizationListCreate )); } #[test] fn validate_env_rejects_v2_morph_tx_before_prague() { // Structurally unreachable on Morph (Celadon > Viridian = Prague), but the - // guard mirrors revm's `Eip7702NotSupported` for `0x04`. - let mut evm = evm_with_spec(MorphHardfork::Morph203); - evm.tx = morph_tx_env_with_authorizations( - Some(MORPH_TX_VERSION_2), - TxKind::Call(Address::ZERO), - vec![Either::Left(sample_signed_authorization())], - ); + // guard mirrors the `Eip7702NotSupported` rule of `0x04`. + let tx = v2_env_with(vec![sample_signed_authorization()]); - let err = validate_env_of(&mut evm).unwrap_err(); + let err = validate_env_of(MorphHardfork::Morph203, &tx).unwrap_err(); assert!(matches!( - err, - EVMError::Transaction(MorphInvalidTransaction::EthInvalidTransaction( - InvalidTransaction::Eip7702NotSupported - )) + morph_error(&err), + MorphInvalidTransaction::Eip7702NotSupported )); } #[test] fn validate_env_keeps_accepting_v1_morph_tx_without_authorizations() { - let mut evm = evm_with_spec(MorphHardfork::Celadon); - evm.tx = morph_tx_env_with_authorizations( + let tx = morph_tx_env_with_authorizations( Some(MORPH_TX_VERSION_1), TxKind::Call(Address::ZERO), vec![], ); - - assert!(validate_env_of(&mut evm).is_ok()); - } - - fn apply_auth_list_of(evm: &mut MorphEvm, NoOpInspector>) -> Option { - let mut gas = GasTracker::new(100_000, 100_000, 0); - as Handler>::apply_eip7702_auth_list( - &MorphEvmHandler::default(), - evm, - &mut gas, - ) - .expect("authorization application must not fail") + assert!(validate_env_of(MorphHardfork::Celadon, &tx).is_ok()); } - fn account_nonce_and_code( - evm: &mut MorphEvm, NoOpInspector>, - address: Address, - ) -> (u64, Option) { - let account = evm - .ctx() - .journal_mut() - .load_account_with_code_mut(address) - .unwrap() - .data; - let info = &account.account().info; - (info.nonce, info.code.clone()) + fn account_nonce_and_code(evm: &mut MorphEvm<'_>, address: Address) -> (u64, Bytecode) { + let mut account = evm.state_mut().account(&address).unwrap(); + (account.nonce(), account.load_code().unwrap()) } - /// revm's default hook is a no-op for `TransactionType::Custom`; the Morph - /// override must apply a V2 list exactly like a `0x04` transaction, and - /// report the EIP-7702 refund for authorities that already exist. + /// A V2 list must apply exactly like a `0x04` transaction, and report the EIP-7702 refund + /// for authorities that already exist. #[test] - fn apply_eip7702_auth_list_delegates_v2_morph_tx_authorities() { + fn apply_authorizations_delegates_v2_morph_tx_authorities() { let authority = Address::with_last_byte(0xaa); let delegate = Address::with_last_byte(0x42); - let mut db = CacheDB::new(EmptyDB::default()); - db.insert_account_info( - authority, - AccountInfo { - balance: U256::from(1), - nonce: 0, - ..Default::default() - }, - ); - let mut evm = MorphEvm::new(MorphContext::new(db, MorphHardfork::Celadon), NoOpInspector); - evm.cfg.chain_id = 1; - evm.tx = morph_tx_env_with_authorizations( - Some(MORPH_TX_VERSION_2), - TxKind::Call(Address::ZERO), - vec![recovered_authorization(authority, delegate, 1, 0)], - ); + let mut db = InMemoryDB::default(); + fund(&mut db, authority, 1); + let mut evm = evm_on(db, MorphHardfork::Celadon, MorphBlockEnv::default()); + let tx = v2_env_with(vec![recovered_authorization(authority, delegate, 1, 0)]); - let refund = apply_auth_list_of(&mut evm); + let refund = apply_authorizations(&mut evm, &tx).unwrap(); assert_eq!( refund, - Some( - evm.ctx_ref() - .cfg() - .gas_params() - .tx_eip7702_auth_refund_regular() - ), + evm.version().gas_params.get(GasId::TxEip7702AuthRefund), "an existing authority earns the regular EIP-7702 refund" ); - assert_eq!(refund, Some(12_500)); + assert_eq!(refund, 12_500); let (nonce, code) = account_nonce_and_code(&mut evm, authority); assert_eq!(nonce, 1, "authority nonce is consumed by the delegation"); - let code = code.expect("delegation designator written"); assert!(code.is_eip7702()); assert_eq!(code, Bytecode::new_eip7702(delegate)); } #[test] - fn apply_eip7702_auth_list_skips_invalid_v2_tuples() { + fn apply_authorizations_skips_invalid_v2_tuples() { let authority = Address::with_last_byte(0xaa); let delegate = Address::with_last_byte(0x42); let mut evm = evm_with_spec(MorphHardfork::Celadon); - evm.cfg.chain_id = 1; - evm.tx = morph_tx_env_with_authorizations( - Some(MORPH_TX_VERSION_2), - TxKind::Call(Address::ZERO), - vec![ - // wrong chain id - recovered_authorization(authority, delegate, 999, 0), - // wrong nonce (authority is at 0) - recovered_authorization(authority, delegate, 1, 5), - ], - ); + let tx = v2_env_with(vec![ + // wrong chain id + recovered_authorization(authority, delegate, 999, 0), + // wrong nonce (authority is at 0) + recovered_authorization(authority, delegate, 1, 5), + ]); - assert_eq!(apply_auth_list_of(&mut evm), Some(0)); + assert_eq!(apply_authorizations(&mut evm, &tx).unwrap(), 0); let (nonce, code) = account_nonce_and_code(&mut evm, authority); assert_eq!(nonce, 0); - assert!(code.is_none_or(|code| code.is_empty())); + assert!(code.is_empty()); } #[test] - fn apply_eip7702_auth_list_is_noop_for_morph_tx_without_authorizations() { + fn apply_authorizations_is_noop_for_morph_tx_without_authorizations() { let mut evm = evm_with_spec(MorphHardfork::Celadon); - evm.tx = morph_tx_env_with_authorizations( + let tx = morph_tx_env_with_authorizations( Some(MORPH_TX_VERSION_1), TxKind::Call(Address::ZERO), vec![], ); - assert_eq!(apply_auth_list_of(&mut evm), Some(0)); - } - - fn evm_with_authority( - authority: Address, - info: AccountInfo, - ) -> MorphEvm, NoOpInspector> { - let mut db = CacheDB::new(EmptyDB::default()); - db.insert_account_info(authority, info); - let mut evm = MorphEvm::new(MorphContext::new(db, MorphHardfork::Celadon), NoOpInspector); - evm.cfg.chain_id = 1; - evm + assert_eq!(apply_authorizations(&mut evm, &tx).unwrap(), 0); } - fn v2_env_with( - authorization_list: Vec>, - ) -> MorphTxEnv { - morph_tx_env_with_authorizations( - Some(MORPH_TX_VERSION_2), - TxKind::Call(Address::ZERO), - authorization_list, - ) + fn evm_with_authority(authority: Address, info: AccountInfo) -> MorphEvm<'static> { + let mut db = InMemoryDB::default(); + db.insert_account_info(&authority, info); + evm_on(db, MorphHardfork::Celadon, MorphBlockEnv::default()) } /// A never-seen authority is created by the delegation and earns no refund /// (the 25 000 intrinsic gas pays for the new account). #[test] - fn apply_eip7702_auth_list_creates_fresh_authority_without_refund() { + fn apply_authorizations_creates_fresh_authority_without_refund() { let authority = Address::with_last_byte(0xaa); let delegate = Address::with_last_byte(0x42); let mut evm = evm_with_spec(MorphHardfork::Celadon); - evm.cfg.chain_id = 1; - evm.tx = v2_env_with(vec![recovered_authorization(authority, delegate, 1, 0)]); + let tx = v2_env_with(vec![recovered_authorization(authority, delegate, 1, 0)]); - assert_eq!(apply_auth_list_of(&mut evm), Some(0)); + assert_eq!(apply_authorizations(&mut evm, &tx).unwrap(), 0); let (nonce, code) = account_nonce_and_code(&mut evm, authority); assert_eq!(nonce, 1); - assert_eq!(code, Some(Bytecode::new_eip7702(delegate))); + assert_eq!(code, Bytecode::new_eip7702(delegate)); } /// An authority that is a real contract can never be delegated (EIP-7702 rule 5). #[test] - fn apply_eip7702_auth_list_skips_authority_with_contract_code() { + fn apply_authorizations_skips_authority_with_contract_code() { let authority = Address::with_last_byte(0xaa); let delegate = Address::with_last_byte(0x42); // PUSH1 0 PUSH1 0 REVERT - let contract_code = Bytecode::new_raw(Bytes::from_static(&[0x60, 0x00, 0x60, 0x00, 0xfd])); + let contract_code = + Bytecode::new_legacy(Bytes::from_static(&[0x60, 0x00, 0x60, 0x00, 0xfd])); let mut evm = evm_with_authority( authority, - AccountInfo { - balance: U256::from(1), - nonce: 3, - code_hash: contract_code.hash_slow(), - code: Some(contract_code.clone()), - ..Default::default() - }, + AccountInfo::default() + .with_balance(U256::from(1)) + .with_nonce(3) + .with_code(contract_code.clone()), ); - evm.tx = v2_env_with(vec![recovered_authorization(authority, delegate, 1, 3)]); + let tx = v2_env_with(vec![recovered_authorization(authority, delegate, 1, 3)]); - assert_eq!(apply_auth_list_of(&mut evm), Some(0)); + assert_eq!(apply_authorizations(&mut evm, &tx).unwrap(), 0); let (nonce, code) = account_nonce_and_code(&mut evm, authority); assert_eq!(nonce, 3, "contract authority is left untouched"); - assert_eq!(code, Some(contract_code)); + assert_eq!(code, contract_code); } /// An already-delegated authority can be re-pointed at a new delegate. #[test] - fn apply_eip7702_auth_list_redelegates_already_delegated_authority() { + fn apply_authorizations_redelegates_already_delegated_authority() { let authority = Address::with_last_byte(0xaa); let first = Address::with_last_byte(0x41); let second = Address::with_last_byte(0x42); - let existing = Bytecode::new_eip7702(first); let mut evm = evm_with_authority( authority, - AccountInfo { - balance: U256::from(1), - nonce: 5, - code_hash: existing.hash_slow(), - code: Some(existing), - ..Default::default() - }, + AccountInfo::default() + .with_balance(U256::from(1)) + .with_nonce(5) + .with_code(Bytecode::new_eip7702(first)), ); - evm.tx = v2_env_with(vec![recovered_authorization(authority, second, 1, 5)]); + let tx = v2_env_with(vec![recovered_authorization(authority, second, 1, 5)]); - assert_eq!(apply_auth_list_of(&mut evm), Some(12_500)); + assert_eq!(apply_authorizations(&mut evm, &tx).unwrap(), 12_500); let (nonce, code) = account_nonce_and_code(&mut evm, authority); assert_eq!(nonce, 6); - assert_eq!(code, Some(Bytecode::new_eip7702(second))); + assert_eq!(code, Bytecode::new_eip7702(second)); } /// Delegating to the zero address clears the designator (EIP-7702 rule 8). #[test] - fn apply_eip7702_auth_list_zero_address_clears_delegation() { + fn apply_authorizations_zero_address_clears_delegation() { let authority = Address::with_last_byte(0xaa); - let existing = Bytecode::new_eip7702(Address::with_last_byte(0x41)); let mut evm = evm_with_authority( authority, - AccountInfo { - balance: U256::from(1), - nonce: 5, - code_hash: existing.hash_slow(), - code: Some(existing), - ..Default::default() - }, + AccountInfo::default() + .with_balance(U256::from(1)) + .with_nonce(5) + .with_code(Bytecode::new_eip7702(Address::with_last_byte(0x41))), ); - evm.tx = v2_env_with(vec![recovered_authorization( + let tx = v2_env_with(vec![recovered_authorization( authority, Address::ZERO, 1, 5, )]); - assert_eq!(apply_auth_list_of(&mut evm), Some(12_500)); + assert_eq!(apply_authorizations(&mut evm, &tx).unwrap(), 12_500); let (nonce, code) = account_nonce_and_code(&mut evm, authority); assert_eq!(nonce, 6); assert!( - code.is_none_or(|code| code.is_empty()), + code.is_empty(), "zero-address delegation must clear the code" ); } - /// A tuple whose authority could not be recovered (the shape - /// `MorphTxEnv::from_recovered_tx` produces for a bad signature) is - /// skipped, not fatal. + /// A tuple whose authority could not be recovered (the shape `MorphTxEnv::from_envelope` + /// produces for a bad signature) is skipped, not fatal. #[test] - fn apply_eip7702_auth_list_skips_tuple_with_invalid_authority() { + fn apply_authorizations_skips_tuple_with_invalid_authority() { let delegate = Address::with_last_byte(0x42); let mut evm = evm_with_spec(MorphHardfork::Celadon); - evm.cfg.chain_id = 1; - evm.tx = v2_env_with(vec![Either::Right(RecoveredAuthorization::new_unchecked( - Authorization { - chain_id: U256::from(1), - address: delegate, - nonce: 0, - }, - RecoveredAuthority::Invalid, - ))]); + let tx = v2_env_with(vec![LazyAuthorization::Recovered( + RecoveredAuthorization::new_unchecked( + Authorization { + chain_id: U256::from(1), + address: delegate, + nonce: 0, + }, + RecoveredAuthority::Invalid, + ), + )]); - assert_eq!(apply_auth_list_of(&mut evm), Some(0)); + assert_eq!(apply_authorizations(&mut evm, &tx).unwrap(), 0); assert!( - evm.ctx() - .journal_mut() - .inner - .state - .values() - .all(|account| account - .info - .code - .as_ref() - .is_none_or(|code| code.is_empty())), - "no account may have been delegated" + no_state_loaded(&evm), + "no account may have been loaded for delegation" ); } /// `chainId = 0` tuples are valid on every chain (EIP-7702 rule 1). #[test] - fn apply_eip7702_auth_list_accepts_chain_id_zero_tuple() { + fn apply_authorizations_accepts_chain_id_zero_tuple() { let authority = Address::with_last_byte(0xaa); let delegate = Address::with_last_byte(0x42); let mut evm = evm_with_spec(MorphHardfork::Celadon); - evm.cfg.chain_id = 1; - evm.tx = v2_env_with(vec![recovered_authorization(authority, delegate, 0, 0)]); + let tx = v2_env_with(vec![recovered_authorization(authority, delegate, 0, 0)]); - assert_eq!(apply_auth_list_of(&mut evm), Some(0)); + assert_eq!(apply_authorizations(&mut evm, &tx).unwrap(), 0); let (nonce, code) = account_nonce_and_code(&mut evm, authority); assert_eq!(nonce, 1); - assert_eq!(code, Some(Bytecode::new_eip7702(delegate))); + assert_eq!(code, Bytecode::new_eip7702(delegate)); } /// `nonce = 2^64 - 1` tuples are skipped (EIP-7702 rule 2). #[test] - fn apply_eip7702_auth_list_skips_nonce_max_tuple() { + fn apply_authorizations_skips_nonce_max_tuple() { let authority = Address::with_last_byte(0xaa); let delegate = Address::with_last_byte(0x42); let mut evm = evm_with_spec(MorphHardfork::Celadon); - evm.cfg.chain_id = 1; - evm.tx = v2_env_with(vec![recovered_authorization( + let tx = v2_env_with(vec![recovered_authorization( authority, delegate, 1, u64::MAX, )]); - assert_eq!(apply_auth_list_of(&mut evm), Some(0)); + assert_eq!(apply_authorizations(&mut evm, &tx).unwrap(), 0); let (nonce, code) = account_nonce_and_code(&mut evm, authority); assert_eq!(nonce, 0); - assert!(code.is_none_or(|code| code.is_empty())); + assert!(code.is_empty()); } /// Two tuples for the same authority apply in order: the second one sees the /// nonce bumped by the first, and both earn the refund. #[test] - fn apply_eip7702_auth_list_applies_consecutive_tuples_for_same_authority() { + fn apply_authorizations_applies_consecutive_tuples_for_same_authority() { let authority = Address::with_last_byte(0xaa); let first = Address::with_last_byte(0x41); let second = Address::with_last_byte(0x42); let mut evm = evm_with_authority( authority, - AccountInfo { - balance: U256::from(1), - nonce: 0, - ..Default::default() - }, + AccountInfo::default().with_balance(U256::from(1)), ); - evm.tx = v2_env_with(vec![ + let tx = v2_env_with(vec![ recovered_authorization(authority, first, 1, 0), recovered_authorization(authority, second, 1, 1), ]); - assert_eq!(apply_auth_list_of(&mut evm), Some(25_000)); + assert_eq!(apply_authorizations(&mut evm, &tx).unwrap(), 25_000); let (nonce, code) = account_nonce_and_code(&mut evm, authority); assert_eq!(nonce, 2); - assert_eq!(code, Some(Bytecode::new_eip7702(second))); + assert_eq!(code, Bytecode::new_eip7702(second)); } /// Simulation (`eth_call`, fee charge disabled) still enforces the static /// V2 rules; only the fee-cap check is fee-dependent. #[test] fn validate_env_enforces_v2_rules_when_fee_charge_is_disabled() { - let mut evm = evm_with_spec(MorphHardfork::Celadon); - evm.cfg.disable_fee_charge = true; - evm.tx = morph_tx_env_with_authorizations( + let mut env = test_env(MorphHardfork::Celadon, MorphBlockEnv::default()); + env.version.features.remove(EvmFeatures::FEE_CHARGE); + let evm = morph_evm(InMemoryDB::default(), env); + let tx = morph_tx_env_with_authorizations( Some(MORPH_TX_VERSION_2), TxKind::Create, - vec![Either::Left(sample_signed_authorization())], + vec![sample_signed_authorization()], ); - let err = validate_env_of(&mut evm).unwrap_err(); + let err = validate_env(&evm, &tx).unwrap_err(); assert!(matches!( - err, - EVMError::Transaction(MorphInvalidTransaction::AuthorizationListCreate) + morph_error(&err), + MorphInvalidTransaction::AuthorizationListCreate )); } - /// revm's intrinsic gas charges 25 000 per authorization from - /// `authorization_list_len()` regardless of the transaction type, so a - /// MorphTx V2 needs no Morph-specific handling here (design doc 5.6). + /// Intrinsic gas charges 25 000 per authorization regardless of the transaction type, so + /// a MorphTx V2 needs no Morph-specific handling here (design doc 5.6). #[test] - fn validate_initial_tx_gas_charges_per_authorization_for_morph_tx_v2() { - let mut evm = evm_with_spec(MorphHardfork::Celadon); - evm.tx = v2_env_with(vec![ - Either::Left(sample_signed_authorization()), - Either::Left(sample_signed_authorization()), + fn intrinsic_gas_charges_per_authorization_for_morph_tx_v2() { + let evm = evm_with_spec(MorphHardfork::Celadon); + let tx = v2_env_with(vec![ + sample_signed_authorization(), + sample_signed_authorization(), ]); // 21_000 base + 2 × 25_000 per authorization. - evm.tx.inner.gas_limit = 70_999; - let err = as Handler>::validate_initial_tx_gas( - &MorphEvmHandler::default(), - &mut evm, - ) - .unwrap_err(); - assert!(matches!( - err, - EVMError::Transaction(MorphInvalidTransaction::EthInvalidTransaction( - InvalidTransaction::CallGasCostMoreThanGasLimit { - initial_gas: 71_000, - gas_limit: 70_999, - } - )) - )); - - evm.tx.inner.gas_limit = 71_000; - let initial = as Handler>::validate_initial_tx_gas( - &MorphEvmHandler::default(), - &mut evm, - ) - .expect("exact intrinsic gas is accepted"); - assert_eq!(initial.initial_regular_gas, 71_000); + let (intrinsic, floor) = intrinsic_gas(&evm, &tx, Address::ZERO); + assert_eq!(intrinsic, 71_000); + assert_eq!(floor, 0, "Morph runs without the EIP-7623 calldata floor"); + assert_eq!( + validate_intrinsic_gas(70_999, intrinsic, 0), + Err(HandlerError::IntrinsicGasTooLow { + required: 71_000, + got: 70_999, + }) + ); + assert_eq!(validate_intrinsic_gas(71_000, intrinsic, 0), Ok(())); } #[test] - fn validate_initial_tx_gas_uses_configured_gas_params() { - let mut evm = MorphEvm::new( - MorphContext::new(CacheDB::new(EmptyDB::default()), MorphHardfork::default()), - NoOpInspector, - ); - let mut gas_params = evm.cfg.gas_params.clone(); - gas_params.override_gas([(GasId::tx_base_stipend(), 30_000)]); - evm.cfg.set_gas_params(gas_params); - evm.tx = MorphTxEnv { - inner: TxEnv { - gas_limit: 25_000, - kind: TxKind::Call(Address::ZERO), - ..Default::default() - }, + fn intrinsic_gas_uses_configured_gas_params() { + let mut env = test_env(MorphHardfork::default(), MorphBlockEnv::default()); + env.version.gas_params.set(GasId::TxBaseStipend, 30_000); + let evm = morph_evm(InMemoryDB::default(), env); + let tx = MorphTxEnv { + gas_limit: 25_000, + kind: TxKind::Call(Address::ZERO), ..Default::default() }; - let err = as Handler>::validate_initial_tx_gas( - &MorphEvmHandler::default(), - &mut evm, - ) - .unwrap_err(); - - assert!(matches!( - err, - EVMError::Transaction(MorphInvalidTransaction::EthInvalidTransaction( - InvalidTransaction::CallGasCostMoreThanGasLimit { - initial_gas: 30_000, - gas_limit: 25_000, - } - )) - )); + assert_eq!(intrinsic_gas(&evm, &tx, Address::ZERO).0, 30_000); } #[test] @@ -2310,37 +1918,16 @@ mod tests { let to = address!("2000000000000000000000000000000000000002"); let token = address!("3000000000000000000000000000000000000003"); let original_balance = U256::from(50); - let contract_code = mutating_return_code(1, 0); - - let mut db = CacheDB::new(EmptyDB::default()); - db.insert_account_info( - from, - AccountInfo { - balance: U256::from(1_000_000), - ..Default::default() - }, - ); - db.insert_account_info( - token, - AccountInfo { - code_hash: keccak256(contract_code.as_ref()), - code: Some(Bytecode::new_raw(contract_code)), - ..Default::default() - }, - ); - db.insert_account_storage(token, U256::ZERO, original_balance) - .unwrap(); - let mut evm = MorphEvm::new( - MorphContext::new(db, MorphHardfork::default()), - NoOpInspector, - ); - evm.block = MorphBlockEnv { - inner: BlockEnv::default(), - }; + let mut db = InMemoryDB::default(); + fund(&mut db, from, 1_000_000); + insert_contract(&mut db, token, mutating_return_code(1, 0)); + db.insert_account_storage(&token, &U256::ZERO, &original_balance); + let mut evm = evm_on(db, MorphHardfork::default(), MorphBlockEnv::default()); let err = transfer_erc20_with_evm( &mut evm, + &tx_env_of(from), from, to, token, @@ -2350,17 +1937,13 @@ mod tests { .unwrap_err(); assert!(matches!( - err, - EVMError::Transaction(MorphInvalidTransaction::TokenTransferFailed { .. }) + morph_error(&err), + MorphInvalidTransaction::TokenTransferFailed { .. } )); - let slot_state = evm - .ctx_ref() - .journal() - .state - .get(&token) - .and_then(|account| account.storage.get(&U256::ZERO)) - .unwrap(); - assert_eq!(slot_state.present_value, U256::from(1)); + assert_eq!( + evm.state().get_storage(&token, &U256::ZERO), + Some(U256::from(1)) + ); } #[test] @@ -2368,45 +1951,29 @@ mod tests { let from = address!("1000000000000000000000000000000000000001"); let to = address!("2000000000000000000000000000000000000002"); let token = address!("3000000000000000000000000000000000000003"); - let original_balance = U256::from(50); - let contract_code = mutating_return_code(1, 1); - let mut db = CacheDB::new(EmptyDB::default()); - db.insert_account_info( + let mut db = InMemoryDB::default(); + fund(&mut db, from, 1_000_000); + insert_contract(&mut db, token, mutating_return_code(1, 1)); + db.insert_account_storage(&token, &U256::ZERO, &U256::from(50)); + let mut evm = evm_on(db, MorphHardfork::default(), MorphBlockEnv::default()); + + let err = transfer_erc20_with_evm( + &mut evm, + &tx_env_of(from), from, - AccountInfo { - balance: U256::from(1_000_000), - ..Default::default() - }, - ); - db.insert_account_info( + to, token, - AccountInfo { - code_hash: keccak256(contract_code.as_ref()), - code: Some(Bytecode::new_raw(contract_code)), - ..Default::default() - }, - ); - db.insert_account_storage(token, U256::ZERO, original_balance) - .unwrap(); - - let mut evm = MorphEvm::new( - MorphContext::new(db, MorphHardfork::default()), - NoOpInspector, - ); - evm.block = MorphBlockEnv { - inner: BlockEnv::default(), - }; - - let err = - transfer_erc20_with_evm(&mut evm, from, to, token, U256::from(1), Some(U256::ZERO)) - .unwrap_err(); + U256::from(1), + Some(U256::ZERO), + ) + .unwrap_err(); assert!(matches!( - err, - EVMError::Transaction(MorphInvalidTransaction::TokenTransferFailed { .. }) + morph_error(&err), + MorphInvalidTransaction::TokenTransferFailed { .. } )); - assert!(evm.ctx_ref().journal().state.is_empty()); + assert!(no_state_loaded(&evm)); } #[test] @@ -2418,36 +1985,23 @@ mod tests { let from_storage_slot = compute_mapping_slot_for_address(balance_slot, from); let to_storage_slot = compute_mapping_slot_for_address(balance_slot, to); - let mut db = CacheDB::new(EmptyDB::default()); - db.insert_account_info(token, AccountInfo::default()); - db.insert_account_storage(token, from_storage_slot, U256::from(10)) - .unwrap(); - db.insert_account_storage(token, to_storage_slot, U256::MAX) - .unwrap(); + let mut db = InMemoryDB::default(); + db.insert_account_info(&token, AccountInfo::default()); + db.insert_account_storage(&token, &from_storage_slot, &U256::from(10)); + db.insert_account_storage(&token, &to_storage_slot, &U256::MAX); + let mut evm = evm_on(db, MorphHardfork::default(), MorphBlockEnv::default()); - let mut evm = MorphEvm::new( - MorphContext::new(db, MorphHardfork::default()), - NoOpInspector, - ); - evm.block = MorphBlockEnv { - inner: BlockEnv::default(), - }; - - // Nothing loads the token first: the helper has to put it in `journal.state` itself. - let journal = evm.ctx_mut().journal_mut(); - let err = transfer_erc20_with_slot(journal, from, to, token, U256::from(1), balance_slot) + let err = transfer_erc20_with_slot(&mut evm, from, to, token, U256::from(1), balance_slot) .unwrap_err(); assert!(matches!( - err, - EVMError::Transaction(MorphInvalidTransaction::TokenTransferFailed { .. }) + morph_error(&err), + MorphInvalidTransaction::TokenTransferFailed { .. } )); - let from_balance_after = *evm - .ctx_mut() - .journal_mut() - .sload(token, from_storage_slot) - .unwrap(); - assert_eq!(from_balance_after, U256::from(10)); + assert_eq!( + storage_of(&mut evm, token, from_storage_slot), + U256::from(10) + ); } #[test] @@ -2455,111 +2009,67 @@ mod tests { let token = address!("3000000000000000000000000000000000000003"); let account = address!("1000000000000000000000000000000000000001"); let original_balance = U256::from(50); - let contract_code = mutating_return_code(1, 42); - - let mut db = CacheDB::new(EmptyDB::default()); - db.insert_account_info( - token, - AccountInfo { - code_hash: keccak256(contract_code.as_ref()), - code: Some(Bytecode::new_raw(contract_code)), - ..Default::default() - }, - ); - db.insert_account_storage(token, U256::ZERO, original_balance) - .unwrap(); - let mut evm = MorphEvm::new( - MorphContext::new(db, MorphHardfork::default()), - NoOpInspector, - ); - evm.block = MorphBlockEnv { - inner: BlockEnv::default(), - }; + let mut db = InMemoryDB::default(); + insert_contract(&mut db, token, mutating_return_code(1, 42)); + db.insert_account_storage(&token, &U256::ZERO, &original_balance); + let mut evm = evm_on(db, MorphHardfork::default(), MorphBlockEnv::default()); - assert!(evm_call_balance_of(&mut evm, token, account).is_err()); - assert_eq!( - revm::Database::storage(evm.ctx_mut().journal_mut().db_mut(), token, U256::ZERO) - .unwrap(), - original_balance - ); + assert!(evm_call_balance_of(&mut evm, &tx_env_of(account), token, account).is_err()); + assert_eq!(storage_of(&mut evm, token, U256::ZERO), original_balance); } - /// `disable_fee_charge` must leave the caller balance untouched. + /// Disabled fee charging must leave the caller balance untouched. #[test] - fn calculate_caller_fee_is_short_circuited_by_disable_fee_charge() { - use revm::context::{CfgEnv, TxEnv}; - + fn calculate_caller_fee_is_short_circuited_by_disabled_fee_charge() { let balance = U256::from(1_000_000_000_000u128); - let mut cfg = CfgEnv::::default(); - cfg.disable_fee_charge = true; - - let tx = TxEnv { + let tx = MorphTxEnv { gas_limit: 21_000, gas_price: 1_000_000_000, value: U256::from(42u64), ..Default::default() }; - let block = BlockEnv::default(); let l1_data_fee = U256::from(1_234u64); let new_balance = - calculate_caller_fee_with_l1_cost(balance, tx, block, cfg, l1_data_fee).unwrap(); + calculate_caller_fee_with_l1_cost(balance, &tx, 0, l1_data_fee, false, true).unwrap(); assert_eq!(new_balance, balance); } #[test] - fn validate_and_deduct_token_fee_rejects_unregistered_token_in_simulation() { + fn token_fee_simulation_rejects_unregistered_token() { let caller = address!("1000000000000000000000000000000000000001"); - let mut db = CacheDB::new(EmptyDB::default()); - db.insert_account_info( - caller, - AccountInfo { - balance: U256::from(1_000_000), - ..Default::default() - }, - ); - let mut evm = token_fee_simulation_evm(db, caller, 65535); + let mut db = InMemoryDB::default(); + fund(&mut db, caller, 1_000_000); - let err = MorphEvmHandler::default() - .validate_against_state_and_deduct_caller(&mut evm, &mut InitialAndFloorGas::default()) - .unwrap_err(); + let err = simulate_token_fee(db, caller, 65535).err().unwrap(); assert!(matches!( - err, - EVMError::Transaction(MorphInvalidTransaction::TokenNotRegistered(65535)) + morph_error(&err), + MorphInvalidTransaction::TokenNotRegistered(65535) )); } #[test] - fn validate_and_deduct_token_fee_rejects_inactive_token_in_simulation() { + fn token_fee_simulation_rejects_inactive_token() { let caller = address!("1000000000000000000000000000000000000001"); let token = address!("2000000000000000000000000000000000000002"); let token_id = 42u16; - let mut db = CacheDB::new(EmptyDB::default()); - db.insert_account_info( - caller, - AccountInfo { - balance: U256::from(1_000_000), - ..Default::default() - }, - ); + let mut db = InMemoryDB::default(); + fund(&mut db, caller, 1_000_000); insert_test_fee_token(&mut db, token_id, token, false); - let mut evm = token_fee_simulation_evm(db, caller, token_id); - let err = MorphEvmHandler::default() - .validate_against_state_and_deduct_caller(&mut evm, &mut InitialAndFloorGas::default()) - .unwrap_err(); + let err = simulate_token_fee(db, caller, token_id).err().unwrap(); assert!(matches!( - err, - EVMError::Transaction(MorphInvalidTransaction::TokenNotActive(42)) + morph_error(&err), + MorphInvalidTransaction::TokenNotActive(42) )); } #[test] - fn validate_and_deduct_token_fee_rejects_invalid_config_in_simulation() { + fn token_fee_simulation_rejects_invalid_config() { let caller = address!("1000000000000000000000000000000000000001"); let token = address!("2000000000000000000000000000000000000002"); let token_id = 42u16; @@ -2568,28 +2078,16 @@ mod tests { ("zero price ratio", U256::ZERO, U256::from(1)), ("zero scale", U256::from(1), U256::ZERO), ] { - let mut db = CacheDB::new(EmptyDB::default()); - db.insert_account_info( - caller, - AccountInfo { - balance: U256::from(1_000_000), - ..Default::default() - }, - ); + let mut db = InMemoryDB::default(); + fund(&mut db, caller, 1_000_000); insert_test_fee_token_config(&mut db, token_id, token, true, price_ratio, scale); - let mut evm = token_fee_simulation_evm(db, caller, token_id); - let err = MorphEvmHandler::default() - .validate_against_state_and_deduct_caller( - &mut evm, - &mut InitialAndFloorGas::default(), - ) - .unwrap_err(); + let err = simulate_token_fee(db, caller, token_id).err().unwrap(); assert!( matches!( - err, - EVMError::Transaction(MorphInvalidTransaction::InvalidTokenConfig(42)) + morph_error(&err), + MorphInvalidTransaction::InvalidTokenConfig(42) ), "{case} must be rejected" ); @@ -2602,14 +2100,8 @@ mod tests { let token = address!("2000000000000000000000000000000000000002"); let token_id = 42u16; let token_accessed = Arc::new(AtomicBool::new(false)); - let mut inner = CacheDB::new(EmptyDB::default()); - inner.insert_account_info( - caller, - AccountInfo { - balance: U256::from(1_000_000), - ..Default::default() - }, - ); + let mut inner = InMemoryDB::default(); + fund(&mut inner, caller, 1_000_000); insert_test_fee_token(&mut inner, token_id, token, true); let db = TokenAccessTrackingDb { @@ -2617,17 +2109,15 @@ mod tests { token, token_accessed: Arc::clone(&token_accessed), }; - let mut evm = token_fee_simulation_evm(db, caller, token_id); - MorphEvmHandler::default() - .validate_against_state_and_deduct_caller(&mut evm, &mut InitialAndFloorGas::default()) - .unwrap(); + assert!(simulate_token_fee(Db::new(db), caller, token_id).is_ok()); assert!( !token_accessed.load(Ordering::Relaxed), "simulation must not query the fee-token contract or its balance storage" ); } + const FEE_REFUND_TOKEN_ID: u16 = 1; const FEE_REFUND_GAS_LIMIT: u64 = 100_000; const FEE_REFUND_GAS_PRICE: u128 = 10; @@ -2694,86 +2184,58 @@ mod tests { U256::from_be_bytes(account.into_word().0) } - fn fee_refund_evm(payer_token_balance: U256) -> MorphEvm, NoOpInspector> { - let code = fee_refund_slotless_erc20_code(); - let mut db = CacheDB::new(EmptyDB::default()); - db.insert_account_info(FEE_REFUND_CALLER, AccountInfo::default()); - db.insert_account_info( - FEE_REFUND_TOKEN, - AccountInfo { - code_hash: keccak256(code.as_ref()), - code: Some(Bytecode::new_raw(code)), - ..Default::default() - }, - ); + fn fee_refund_db(payer_token_balance: U256) -> InMemoryDB { + let mut db = InMemoryDB::default(); + db.insert_account_info(&FEE_REFUND_CALLER, AccountInfo::default()); + insert_contract(&mut db, FEE_REFUND_TOKEN, fee_refund_slotless_erc20_code()); db.insert_account_storage( - FEE_REFUND_TOKEN, - fee_refund_balance_slot(FEE_REFUND_CALLER), - payer_token_balance, - ) - .unwrap(); + &FEE_REFUND_TOKEN, + &fee_refund_balance_slot(FEE_REFUND_CALLER), + &payer_token_balance, + ); // `balanceSlot` word left at zero => call mode (`balance_slot == None`). insert_test_fee_token(&mut db, FEE_REFUND_TOKEN_ID, FEE_REFUND_TOKEN, true); + db + } - let mut evm = MorphEvm::new( - MorphContext::new(db, MorphHardfork::default()), - NoOpInspector, - ); - evm.block = MorphBlockEnv { - inner: BlockEnv { - basefee: 1, - beneficiary: FEE_REFUND_BENEFICIARY, - gas_limit: 30_000_000, - ..Default::default() - }, - }; - // Production Morph configuration disables the Ethereum calldata gas floor. - evm.cfg.disable_eip7623 = true; - evm + fn fee_refund_block() -> MorphBlockEnv { + MorphBlockEnv { + basefee: U256::from(1), + beneficiary: FEE_REFUND_BENEFICIARY, + gas_limit: U256::from(30_000_000), + ..Default::default() + } + } + + fn fee_refund_evm(db: InMemoryDB) -> MorphEvm<'static> { + evm_on(db, MorphHardfork::default(), fee_refund_block()) } - fn fee_refund_present_value( - evm: &MorphEvm, NoOpInspector>, - account: Address, - ) -> U256 { - evm.ctx_ref() - .journal() - .state - .get(&FEE_REFUND_TOKEN) - .and_then(|acct| acct.storage.get(&fee_refund_balance_slot(account))) - .map(|slot| slot.present_value) - .expect("fee-token slot must be in the journal") + fn fee_refund_tx() -> MorphTxEnv { + MorphTxEnv { + tx_type: MORPH_TX_TYPE_ID, + gas_limit: FEE_REFUND_GAS_LIMIT, + gas_price: FEE_REFUND_GAS_PRICE, + kind: TxKind::Call(FEE_REFUND_TARGET), + fee_token_id: Some(FEE_REFUND_TOKEN_ID), + ..Default::default() + } } /// Runs one call-mode token-fee MorphTx (plain call to an EOA) and returns /// `(gas_used, final refund applied to the main frame, payer token balance after /// reimbursement)`. fn fee_refund_run_token_fee_tx(payer_token_balance: U256) -> (u64, u64, U256) { - let mut evm = fee_refund_evm(payer_token_balance); - let tx = MorphTxEnv { - inner: TxEnv { - tx_type: MORPH_TX_TYPE_ID, - caller: FEE_REFUND_CALLER, - gas_limit: FEE_REFUND_GAS_LIMIT, - gas_price: FEE_REFUND_GAS_PRICE, - kind: TxKind::Call(FEE_REFUND_TARGET), - ..Default::default() - }, - fee_token_id: Some(FEE_REFUND_TOKEN_ID), - ..Default::default() - }; - - let result = evm - .transact_one(tx) + let mut evm = fee_refund_evm(fee_refund_db(payer_token_balance)); + let result = transact(&mut evm, fee_refund_tx(), FEE_REFUND_CALLER) .expect("token-fee MorphTx must execute"); - assert!(result.is_success(), "expected success, got {result:?}"); - let gas_used = result.tx_gas_used(); - let gas_refunded = result.gas().final_refunded(); + assert!(result.status, "expected success, got {result:?}"); // Sanity: the fee was charged in call mode and equals exactly FEE_REFUND_TOKEN_FEE. - let info = evm - .cached_token_fee_info() - .expect("token fee info is cached"); + let info = result + .ext + .token_fee_info + .expect("token fee info is reported"); assert_eq!( info.balance_slot, None, "token must be registered in call mode" @@ -2789,273 +2251,840 @@ mod tests { U256::from(FEE_REFUND_TOKEN_FEE) ); - ( - gas_used, - gas_refunded, - fee_refund_present_value(&evm, FEE_REFUND_CALLER), - ) + ( + result.tx_gas_used(), + result.refunded, + storage_of( + &mut evm, + FEE_REFUND_TOKEN, + fee_refund_balance_slot(FEE_REFUND_CALLER), + ), + ) + } + + #[test] + fn deduction_sstore_refund_reaches_transaction_gas() { + let fee = U256::from(FEE_REFUND_TOKEN_FEE); + let (gas, refund, balance) = fee_refund_run_token_fee_tx(fee); + assert_eq!((gas, refund), (16_800, 4_200)); + assert_eq!(balance, fee - U256::from(168_000)); + let (gas, refund, balance) = fee_refund_run_token_fee_tx(fee + U256::from(1)); + assert_eq!((gas, refund), (21_000, 0)); + assert_eq!(balance, fee + U256::from(1) - U256::from(210_000)); + } + + #[test] + fn balance_queries_reject_state_writes() { + let mut db = fee_refund_db(U256::from(FEE_REFUND_TOKEN_FEE)); + insert_contract(&mut db, FEE_REFUND_TOKEN, mutating_return_code(1, 1)); + let mut evm = fee_refund_evm(db); + assert!( + evm_call_balance_of( + &mut evm, + &tx_env_of(FEE_REFUND_CALLER), + FEE_REFUND_TOKEN, + FEE_REFUND_CALLER + ) + .is_err() + ); + } + + /// Fee frames run under the environment the transaction's preparation built, so ORIGIN and + /// GASPRICE are the outer transaction's. + #[test] + fn internal_calls_preserve_origin_and_effective_gas_price() { + for (opcode, expected) in [ + (0x32, U256::from_be_slice(FEE_REFUND_CALLER.as_slice())), + (0x3a, U256::from(3)), + ] { + let mut db = fee_refund_db(U256::from(FEE_REFUND_TOKEN_FEE)); + fund(&mut db, FEE_REFUND_CALLER, 10_000_000); + insert_contract(&mut db, FEE_REFUND_TOKEN, code_returning(opcode)); + let mut evm = fee_refund_evm(db); + let tx = MorphTxEnv { + gas_price: 10, + gas_priority_fee: Some(2), + fee_token_id: Some(0), + ..fee_refund_tx() + }; + let mut request = TxRequest { + envelope: &tx, + tx: Recovered::new_unchecked(&tx, FEE_REFUND_CALLER), + host: &mut evm, + _non_exhaustive: (), + }; + let prepared = prepare(&mut request).unwrap(); + + assert_eq!( + evm_call_balance_of( + &mut evm, + &prepared.tx_env, + FEE_REFUND_TOKEN, + FEE_REFUND_BENEFICIARY + ) + .unwrap(), + expected + ); + } + } + + #[test] + fn zero_token_transfer_does_not_call_the_contract() { + let mut db = fee_refund_db(U256::ZERO); + insert_contract(&mut db, FEE_REFUND_TOKEN, mutating_return_code(1, 0)); + let mut evm = fee_refund_evm(db); + transfer_erc20_with_evm( + &mut evm, + &tx_env_of(FEE_REFUND_CALLER), + FEE_REFUND_CALLER, + FEE_REFUND_BENEFICIARY, + FEE_REFUND_TOKEN, + U256::ZERO, + Some(U256::ZERO), + ) + .unwrap(); + assert!(no_state_loaded(&evm)); + } + + /// Runs one transaction against `code` deployed at [`FEE_REFUND_TARGET`] and + /// returns what the main frame returned. `fee_token_id` selects the call-mode + /// token-fee path or the ordinary ETH-fee path. + fn fee_refund_run_probe(code: Bytes, fee_token_id: Option) -> Bytes { + let mut db = fee_refund_db(U256::from(FEE_REFUND_TOKEN_FEE)); + insert_contract(&mut db, FEE_REFUND_TARGET, code); + fund( + &mut db, + FEE_REFUND_CALLER, + (FEE_REFUND_GAS_LIMIT as u128 * FEE_REFUND_GAS_PRICE) as u64, + ); + let tx = MorphTxEnv { + tx_type: if fee_token_id.is_some() { + MORPH_TX_TYPE_ID + } else { + 0 + }, + fee_token_id, + ..fee_refund_tx() + }; + let result = + transact(&mut fee_refund_evm(db), tx, FEE_REFUND_CALLER).expect("probe must execute"); + assert!(result.status, "expected success, got {result:?}"); + result.output + } + + /// Minimal proxy: copies its calldata into memory and `DELEGATECALL`s + /// `implementation`, the way mainnet's call-mode fee tokens reach theirs. + fn delegating_proxy_code(implementation: Address) -> Bytes { + Bytes::from(delegate_body(implementation)) + } + + fn delegate_body(implementation: Address) -> Vec { + let mut code = vec![ + 0x36, // CALLDATASIZE (size) + 0x5f, // PUSH0 (offset) + 0x5f, // PUSH0 (destOffset) + 0x37, // CALLDATACOPY + 0x5f, // PUSH0 (retSize) + 0x5f, // PUSH0 (retOffset) + 0x36, // CALLDATASIZE (argsSize) + 0x5f, // PUSH0 (argsOffset) + 0x73, // PUSH20 implementation + ]; + code.extend_from_slice(implementation.as_slice()); + code.extend_from_slice(&[ + 0x5a, // GAS + 0xf4, // DELEGATECALL + 0x3d, // RETURNDATASIZE (size) + 0x5f, // PUSH0 (offset) + 0x5f, // PUSH0 (destOffset) + 0x3e, // RETURNDATACOPY + 0x50, // POP (DELEGATECALL success flag) + 0x3d, // RETURNDATASIZE (size) + 0x5f, // PUSH0 (offset) + 0xf3, // RETURN + ]); + code + } + + /// Same ERC20, except `balanceOf` returns its result through the identity + /// precompile, reading the precompile's arguments out of memory. + fn fee_refund_precompile_erc20_code() -> Bytes { + let mut code = vec![ + 0x36, // CALLDATASIZE + 0x60, 0x44, // PUSH1 68 + 0x14, // EQ + 0x60, 0x1e, // PUSH1 30 (transfer JUMPDEST) + 0x57, // JUMPI + // balanceOf(address), answered by identity(mem[0..32]) + 0x60, 0x04, // PUSH1 4 + 0x35, // CALLDATALOAD + 0x54, // SLOAD + 0x5f, // PUSH0 + 0x52, // MSTORE + 0x60, 0x20, // PUSH1 32 (retSize) + 0x60, 0x20, // PUSH1 32 (retOffset) + 0x60, 0x20, // PUSH1 32 (argsSize) + 0x5f, // PUSH0 (argsOffset) + 0x60, 0x04, // PUSH1 4 (identity precompile) + 0x5a, // GAS + 0xfa, // STATICCALL + 0x50, // POP + 0x60, 0x20, // PUSH1 32 (size) + 0x60, 0x20, // PUSH1 32 (offset) + 0xf3, // RETURN + ]; + assert_eq!(code.len(), 30, "the transfer JUMPDEST moved"); + code.extend_from_slice(&fee_refund_slotless_erc20_code()[19..]); + Bytes::from(code) + } + + /// A fee frame that calls a precompile must hand it its arguments out of the frame's memory. + #[test] + fn fee_token_frames_reach_a_precompile_through_memory() { + let fee = U256::from(FEE_REFUND_TOKEN_FEE); + let mut db = fee_refund_db(fee); + insert_contract( + &mut db, + FEE_REFUND_TOKEN, + fee_refund_precompile_erc20_code(), + ); + assert_eq!(fee_refund_run_fee_tx(db), fee_refund_run_token_fee_tx(fee)); + } + + /// Mainnet's call-mode fee tokens are proxies, so a fee frame's nested + /// `DELEGATECALL` reads its calldata back out of the frame's memory. + #[test] + fn fee_token_frames_reach_a_delegating_proxy_implementation() { + const IMPLEMENTATION: Address = address!("3000000000000000000000000000000000000004"); + let fee = U256::from(FEE_REFUND_TOKEN_FEE); + let mut db = fee_refund_db(fee); + insert_contract(&mut db, IMPLEMENTATION, fee_refund_slotless_erc20_code()); + insert_contract( + &mut db, + FEE_REFUND_TOKEN, + delegating_proxy_code(IMPLEMENTATION), + ); + + // Indistinguishable from the same transaction against an unproxied token: + // the implementation saw exactly the calldata the fee frame wrote. + assert_eq!(fee_refund_run_fee_tx(db), fee_refund_run_token_fee_tx(fee)); + } + + /// Runs the standard call-mode token-fee MorphTx over `db` and reports it the way + /// [`fee_refund_run_token_fee_tx`] does. + fn fee_refund_run_fee_tx(db: InMemoryDB) -> (u64, u64, U256) { + let mut evm = fee_refund_evm(db); + let result = transact(&mut evm, fee_refund_tx(), FEE_REFUND_CALLER) + .expect("token-fee MorphTx must execute"); + assert!(result.status, "expected success, got {result:?}"); + ( + result.tx_gas_used(), + result.refunded, + storage_of( + &mut evm, + FEE_REFUND_TOKEN, + fee_refund_balance_slot(FEE_REFUND_CALLER), + ), + ) + } + + /// go-ethereum allocates a fresh `Memory` for every interpreter run + /// (`core/vm/interpreter.go`), so a transaction's frame always starts on zeroed + /// memory, even after the fee-token frames ran. + #[test] + fn fee_token_frames_do_not_leak_memory_into_the_main_frame() { + // `MSIZE` and `MLOAD(0)`, each returned as the frame's 32-byte output. + for probe in [ + vec![0x59, 0x5f, 0x52, 0x60, 0x20, 0x5f, 0xf3], + vec![0x5f, 0x51, 0x5f, 0x52, 0x60, 0x20, 0x5f, 0xf3], + ] { + let code = Bytes::from(probe); + assert_eq!( + U256::from_be_slice(&fee_refund_run_probe(code.clone(), None)), + U256::ZERO, + "ETH-fee control" + ); + assert_eq!( + U256::from_be_slice(&fee_refund_run_probe(code, Some(FEE_REFUND_TOKEN_ID))), + U256::ZERO, + "a token-fee main frame must start on zeroed memory too" + ); + } + } + + /// `GAS; ; GAS; SWAP1; SUB; PUSH0; MSTORE; PUSH1 32; PUSH0; RETURN`: returns the gas + /// `measured` consumed, so a difference in its warm/cold pricing is visible in the output. + fn gas_meter(measured: &[u8]) -> Vec { + let mut code = vec![0x5a]; // GAS + code.extend_from_slice(measured); + code.extend_from_slice(&[ + 0x5a, // GAS + 0x90, // SWAP1 + 0x03, // SUB + 0x5f, // PUSH0 + 0x52, // MSTORE + 0x60, 0x20, // PUSH1 32 + 0x5f, // PUSH0 + 0xf3, // RETURN + ]); + code + } + + /// The deduction's `balanceOf`/`transfer` frames warm the token. go-ethereum's + /// `StateDB.Prepare` drops that before the main transaction, so the main frame must pay the + /// same cold-access price it pays when the fee is in ETH. + #[test] + fn main_frame_sees_the_fee_token_account_cold() { + let mut measured = vec![0x73]; // PUSH20 token + measured.extend_from_slice(FEE_REFUND_TOKEN.as_slice()); + measured.extend_from_slice(&[0x31, 0x50]); // BALANCE; POP + let code = Bytes::from(gas_meter(&measured)); + + let eth = U256::from_be_slice(&fee_refund_run_probe(code.clone(), None)); + let token = U256::from_be_slice(&fee_refund_run_probe(code, Some(FEE_REFUND_TOKEN_ID))); + + assert_eq!(token, eth); + assert_eq!(token, U256::from(2_600 + 3 + 2 + 2)); + } + + /// `to == token` runs [`token_slot_probe_code`] as the main frame: calling with empty + /// calldata measures an `SLOAD` of the payer's balance slot, which the deduction warmed. + fn token_slot_probe_code(payer: Address) -> Bytes { + let mut measure = vec![0x73]; // PUSH20 payer + measure.extend_from_slice(payer.as_slice()); + measure.extend_from_slice(&[0x54, 0x50]); // SLOAD; POP + let meter = gas_meter(&measure); + + // CALLDATASIZE; ISZERO; PUSH2 ; JUMPI; + let erc20 = relocated_erc20(7); + let probe_offset = 7 + erc20.len(); + + let mut code = vec![ + 0x36, // CALLDATASIZE + 0x15, // ISZERO + 0x61, + (probe_offset >> 8) as u8, + probe_offset as u8, // PUSH2 + 0x57, // JUMPI + 0x00, // padding, replaced below + ]; + code.pop(); + code.push(0x5b); // JUMPDEST so that the ERC20 body starts on a valid position + code.extend_from_slice(&erc20); + code.push(0x5b); // JUMPDEST at + code.extend_from_slice(&meter); + Bytes::from(code) + } + + /// [`fee_refund_slotless_erc20_code`], moved to start at `offset`. + fn relocated_erc20(offset: usize) -> Vec { + let mut code = fee_refund_slotless_erc20_code().to_vec(); + // The only absolute jump target in the body is the `PUSH1 19` at index 5. + code[5] = u8::try_from(19 + offset).unwrap(); + code + } + + /// Runs a token-fee or ETH-fee call to the token itself and returns the probe's output. + fn run_token_slot_probe(fee_token_id: Option) -> U256 { + let fee = U256::from(FEE_REFUND_TOKEN_FEE * 2); + let mut db = fee_refund_db(fee); + insert_contract( + &mut db, + FEE_REFUND_TOKEN, + token_slot_probe_code(FEE_REFUND_CALLER), + ); + fund( + &mut db, + FEE_REFUND_CALLER, + (FEE_REFUND_GAS_LIMIT as u128 * FEE_REFUND_GAS_PRICE) as u64, + ); + let tx = MorphTxEnv { + tx_type: if fee_token_id.is_some() { + MORPH_TX_TYPE_ID + } else { + 0 + }, + kind: TxKind::Call(FEE_REFUND_TOKEN), + fee_token_id, + ..fee_refund_tx() + }; + let result = + transact(&mut fee_refund_evm(db), tx, FEE_REFUND_CALLER).expect("probe must execute"); + assert!(result.status, "expected success, got {result:?}"); + U256::from_be_slice(&result.output) + } + + #[test] + fn main_frame_sees_the_fee_token_slot_cold() { + let eth = run_token_slot_probe(None); + let token = run_token_slot_probe(Some(FEE_REFUND_TOKEN_ID)); + assert_eq!(token, eth); + assert_eq!(token, U256::from(2_100 + 3 + 2 + 2)); + } + + /// `TSTORE(0, 1)` before forwarding `transfer` to an ERC20 implementation, and a report of + /// `TLOAD(0)` when called with no calldata. + fn transient_writing_token_code(implementation: Address) -> Bytes { + let delegate = delegate_body(implementation); + // Layout: dispatch | delegate | transfer prefix | report. + let dispatch_len = 14; + let delegate_start = dispatch_len; + let transfer_prefix = delegate_start + 1 + delegate.len(); + let report = transfer_prefix + 8; + + let mut code = vec![ + 0x36, // CALLDATASIZE + 0x60, + 0x44, // PUSH1 68 + 0x14, // EQ + 0x60, + u8::try_from(transfer_prefix).unwrap(), // PUSH1 + 0x57, // JUMPI + 0x36, // CALLDATASIZE + 0x15, // ISZERO + 0x60, + u8::try_from(report).unwrap(), // PUSH1 + 0x57, // JUMPI + 0x60, + u8::try_from(delegate_start).unwrap(), // PUSH1 + 0x56, // JUMP + ]; + code.truncate(dispatch_len); + code.push(0x5b); // JUMPDEST + code.extend_from_slice(&delegate); + assert_eq!(code.len(), transfer_prefix); + code.extend_from_slice(&[ + 0x5b, // JUMPDEST + 0x60, + 0x01, // PUSH1 1 + 0x5f, // PUSH0 + 0x5d, // TSTORE + 0x60, + u8::try_from(delegate_start).unwrap(), // PUSH1 + 0x56, // JUMP + ]); + assert_eq!(code.len(), report); + code.extend_from_slice(&[ + 0x5b, // JUMPDEST + 0x5f, // PUSH0 + 0x5c, // TLOAD + 0x5f, // PUSH0 + 0x52, // MSTORE + 0x60, 0x20, // PUSH1 32 + 0x5f, // PUSH0 + 0xf3, // RETURN + ]); + Bytes::from(code) + } + + /// The deduction's transient writes must not leak into the main transaction: + /// `StateDB.Prepare` resets transient storage in go-ethereum. + #[test] + fn main_frame_does_not_see_the_fee_frames_transient_storage() { + const IMPLEMENTATION: Address = address!("3000000000000000000000000000000000000004"); + let fee = U256::from(FEE_REFUND_TOKEN_FEE * 2); + let mut db = fee_refund_db(fee); + insert_contract(&mut db, IMPLEMENTATION, fee_refund_slotless_erc20_code()); + insert_contract( + &mut db, + FEE_REFUND_TOKEN, + transient_writing_token_code(IMPLEMENTATION), + ); + let tx = MorphTxEnv { + kind: TxKind::Call(FEE_REFUND_TOKEN), + ..fee_refund_tx() + }; + + let result = + transact(&mut fee_refund_evm(db), tx, FEE_REFUND_CALLER).expect("probe must execute"); + + assert!(result.status, "expected success, got {result:?}"); + assert_eq!(U256::from_be_slice(&result.output), U256::ZERO); + } + + /// Forwards to `implementation`, emitting `LOG1(topic)` first when called with `transfer` + /// calldata. `balanceOf` runs in a static frame, where a log would halt it. + fn logging_token_code(implementation: Address, topic: u8) -> Bytes { + const DELEGATE: u8 = 13; + let mut code = vec![ + 0x36, // CALLDATASIZE + 0x60, 0x44, // PUSH1 68 + 0x14, // EQ + 0x15, // ISZERO + 0x60, DELEGATE, // PUSH1 + 0x57, // JUMPI + 0x60, topic, // PUSH1 topic + 0x5f, // PUSH0 + 0x5f, // PUSH0 + 0xa1, // LOG1 + 0x5b, // JUMPDEST + ]; + assert_eq!(code.len(), DELEGATE as usize + 1); + code.extend_from_slice(&delegate_body(implementation)); + Bytes::from(code) + } + + /// `LOG1(topic)`, then `REVERT` when `reverts`. + fn logging_target_code(topic: u8, reverts: bool) -> Bytes { + let mut code = vec![ + 0x60, topic, // PUSH1 topic + 0x5f, // PUSH0 + 0x5f, // PUSH0 + 0xa1, // LOG1 + ]; + if reverts { + code.extend_from_slice(&[0x5f, 0x5f, 0xfd]); // PUSH0; PUSH0; REVERT + } else { + code.push(0x00); // STOP + } + Bytes::from(code) + } + + fn logged_topic(log: &Log) -> u8 { + log.topics()[0].0[31] + } + + /// Runs a token-fee transaction whose token logs `0xaa` and whose target logs `0xbb`. + fn run_logging_token_fee_tx(reverts: bool) -> Vec { + const IMPLEMENTATION: Address = address!("3000000000000000000000000000000000000004"); + let fee = U256::from(FEE_REFUND_TOKEN_FEE); + let mut db = fee_refund_db(fee); + insert_contract(&mut db, IMPLEMENTATION, fee_refund_slotless_erc20_code()); + insert_contract( + &mut db, + FEE_REFUND_TOKEN, + logging_token_code(IMPLEMENTATION, 0xaa), + ); + insert_contract( + &mut db, + FEE_REFUND_TARGET, + logging_target_code(0xbb, reverts), + ); + + let result = transact(&mut fee_refund_evm(db), fee_refund_tx(), FEE_REFUND_CALLER) + .expect("token-fee MorphTx must execute"); + assert_eq!(result.status, !reverts); + result.logs + } + + /// Logs read in the order things happened: deduction, main frame, refund. + #[test] + fn fee_logs_surround_the_main_frame_logs() { + let logs = run_logging_token_fee_tx(false); + assert_eq!( + logs.iter().map(logged_topic).collect::>(), + vec![0xaa, 0xbb, 0xaa] + ); + } + + /// go-ethereum's fee logs live outside the state snapshot, so a reverted main frame keeps + /// them while dropping its own. + #[test] + fn fee_logs_survive_a_reverted_main_frame() { + let logs = run_logging_token_fee_tx(true); + assert_eq!( + logs.iter().map(logged_topic).collect::>(), + vec![0xaa, 0xaa] + ); + } + + /// Records every frame and instruction an inspector is shown. + #[derive(Debug, Default)] + struct CountingInspector { + calls: usize, + steps: usize, + logs: usize, + } + + impl Inspector for CountingInspector { + fn step(&mut self, _interp: &mut Interpreter<'_, '_, MorphEvmTypes>) { + self.steps += 1; + } + + fn log(&mut self, _log: &Log, _host: &mut MorphEvm<'_>) { + self.logs += 1; + } + + fn call( + &mut self, + _interp: &mut Interpreter<'_, '_, MorphEvmTypes>, + _message: &mut Message, + ) -> Option> { + self.calls += 1; + None + } + } + + /// Runs the logging token-fee transaction with `inspector` installed. + fn inspect_logging_tx(inspector: &mut dyn Inspector) { + const IMPLEMENTATION: Address = address!("3000000000000000000000000000000000000004"); + let mut db = fee_refund_db(U256::from(FEE_REFUND_TOKEN_FEE)); + insert_contract(&mut db, IMPLEMENTATION, fee_refund_slotless_erc20_code()); + insert_contract( + &mut db, + FEE_REFUND_TOKEN, + logging_token_code(IMPLEMENTATION, 0xaa), + ); + insert_contract(&mut db, FEE_REFUND_TARGET, logging_target_code(0xbb, false)); + let mut evm = fee_refund_evm(db); + let tx = Recovered::new_unchecked(fee_refund_tx(), FEE_REFUND_CALLER); + let result = evm + .transact_with_inspector(&tx, inspector) + .expect("token-fee MorphTx must execute") + .discard(); + assert!(result.status, "expected success, got {result:?}"); } + /// Tracers see a token-fee transaction the way go-ethereum presents it: the fee frames are + /// system calls, and the only frame left is the transaction's own. #[test] - fn deduction_sstore_refund_reaches_transaction_gas() { - let fee = U256::from(FEE_REFUND_TOKEN_FEE); - let (gas, refund, balance) = fee_refund_run_token_fee_tx(fee); - assert_eq!((gas, refund), (16_800, 4_200)); - assert_eq!(balance, fee - U256::from(168_000)); - let (gas, refund, balance) = fee_refund_run_token_fee_tx(fee + U256::from(1)); - assert_eq!((gas, refund), (21_000, 0)); - assert_eq!(balance, fee + U256::from(1) - U256::from(210_000)); + fn inspectors_do_not_see_fee_frames() { + let mut filtered = crate::FeeFrameFilter::new(CountingInspector::default()); + inspect_logging_tx(&mut filtered); + let filtered = filtered.into_inner(); + + assert_eq!(filtered.calls, 1, "only the main frame is a traced call"); + assert_eq!(filtered.logs, 1, "only the main frame's log is traced"); + // The main frame is `PUSH1 PUSH0 PUSH0 LOG1 STOP`. + assert_eq!(filtered.steps, 5); + + // Control: the fee frames really do run, and an unfiltered inspector sees them. + let mut unfiltered = CountingInspector::default(); + inspect_logging_tx(&mut unfiltered); + assert!(unfiltered.calls > filtered.calls); + assert!(unfiltered.logs > filtered.logs); } + // ========================================================================= + // Native-fee and L1 message settlement + // ========================================================================= + #[test] - fn balance_queries_reject_state_writes() { - let mut evm = fee_refund_evm(U256::from(FEE_REFUND_TOKEN_FEE)); - let code = mutating_return_code(1, 1); - evm.ctx_mut().journal_mut().db_mut().insert_account_info( - FEE_REFUND_TOKEN, - AccountInfo { - code_hash: keccak256(&code), - code: Some(Bytecode::new_raw(code)), + fn eth_fee_pays_the_whole_fee_to_the_beneficiary() { + let caller = FEE_REFUND_CALLER; + let mut db = InMemoryDB::default(); + fund(&mut db, caller, 10_000_000); + let mut evm = evm_on( + db, + MorphHardfork::default(), + MorphBlockEnv { + basefee: U256::from(5), + beneficiary: FEE_REFUND_BENEFICIARY, + gas_limit: U256::from(30_000_000), ..Default::default() }, ); - assert!(evm_call_balance_of(&mut evm, FEE_REFUND_TOKEN, FEE_REFUND_CALLER).is_err()); + let tx = MorphTxEnv { + gas_limit: 100_000, + gas_price: 10, + kind: TxKind::Call(FEE_REFUND_TARGET), + ..Default::default() + }; + + let result = transact(&mut evm, tx, caller).unwrap(); + + assert!(result.status); + assert_eq!(result.tx_gas_used(), 21_000); + let caller_after = evm + .state_mut() + .account_info_untracked(&caller) + .unwrap() + .unwrap(); + assert_eq!(caller_after.balance, U256::from(10_000_000 - 210_000u64)); + assert_eq!(caller_after.nonce, 1); + let beneficiary = evm + .state_mut() + .account_info_untracked(&FEE_REFUND_BENEFICIARY) + .unwrap() + .unwrap(); + assert_eq!( + beneficiary.balance, + U256::from(210_000u64), + "Morph burns no base fee" + ); } #[test] - fn internal_calls_preserve_origin_and_effective_gas_price() { - for (opcode, expected) in [ - (0x32, U256::from_be_slice(FEE_REFUND_CALLER.as_slice())), - (0x3a, U256::from(3)), - ] { - let mut evm = fee_refund_evm(U256::from(FEE_REFUND_TOKEN_FEE)); - evm.tx.inner.caller = FEE_REFUND_CALLER; - evm.tx.inner.tx_type = MORPH_TX_TYPE_ID; - evm.tx.inner.gas_price = 10; - evm.tx.inner.gas_priority_fee = Some(2); - let code = Bytes::from(vec![opcode, 0x5f, 0x52, 0x60, 0x20, 0x5f, 0xf3]); - evm.ctx_mut().journal_mut().db_mut().insert_account_info( - FEE_REFUND_TOKEN, - AccountInfo { - code_hash: keccak256(&code), - code: Some(Bytecode::new_raw(code)), - ..Default::default() - }, - ); - assert_eq!( - evm_call_balance_of(&mut evm, FEE_REFUND_TOKEN, FEE_REFUND_BENEFICIARY).unwrap(), - expected - ); - assert_eq!(evm.tx.inner.caller, FEE_REFUND_CALLER); - } + fn eth_fee_requires_balance_for_the_max_fee_and_the_l1_fee() { + let caller = FEE_REFUND_CALLER; + let mut db = InMemoryDB::default(); + // Enough for the effective fee, not for the max fee. + fund(&mut db, caller, 1_000_000); + let mut evm = evm_on(db, MorphHardfork::default(), MorphBlockEnv::default()); + let tx = MorphTxEnv { + tx_type: EIP1559_TX_TYPE, + chain_id: Some(1), + gas_limit: 100_000, + gas_price: 11, + gas_priority_fee: Some(1), + kind: TxKind::Call(FEE_REFUND_TARGET), + ..Default::default() + }; + + assert!(matches!( + transact(&mut evm, tx, caller), + Err(HandlerError::InsufficientFunds { .. }) + )); } - #[test] - fn zero_token_transfer_does_not_call_the_contract() { - let mut evm = fee_refund_evm(U256::ZERO); - let code = mutating_return_code(1, 0); - evm.ctx_mut().journal_mut().db_mut().insert_account_info( - FEE_REFUND_TOKEN, - AccountInfo { - code_hash: keccak256(&code), - code: Some(Bytecode::new_raw(code)), - ..Default::default() - }, - ); - transfer_erc20_with_evm( - &mut evm, - FEE_REFUND_CALLER, - FEE_REFUND_BENEFICIARY, - FEE_REFUND_TOKEN, - U256::ZERO, - Some(U256::ZERO), - ) - .unwrap(); - assert!(evm.ctx_ref().journal().state.is_empty()); + /// `PUSH0 PUSH0 SSTORE STOP` against a set slot 0: clears it, earning a refund. + fn storage_clearing_code() -> Bytes { + Bytes::from_static(&[0x5f, 0x5f, 0x55, 0x00]) } - /// Runs one transaction against `code` deployed at [`FEE_REFUND_TARGET`] and - /// returns what the main frame returned. `fee_token_id` selects the call-mode - /// token-fee path or the ordinary ETH-fee path. - fn fee_refund_run_probe(code: Bytes, fee_token_id: Option) -> Bytes { - let mut evm = fee_refund_evm(U256::from(FEE_REFUND_TOKEN_FEE)); - let db = evm.ctx_mut().journal_mut().db_mut(); - insert_contract(db, FEE_REFUND_TARGET, code); - db.insert_account_info( - FEE_REFUND_CALLER, - AccountInfo { - balance: U256::from(FEE_REFUND_GAS_LIMIT as u128 * FEE_REFUND_GAS_PRICE), + #[test] + fn l1_message_pays_no_fees_and_keeps_no_refund() { + let caller = FEE_REFUND_CALLER; + let mut db = InMemoryDB::default(); + insert_contract(&mut db, FEE_REFUND_TARGET, storage_clearing_code()); + db.insert_account_storage(&FEE_REFUND_TARGET, &U256::ZERO, &U256::from(1)); + let mut evm = evm_on( + db, + MorphHardfork::default(), + MorphBlockEnv { + beneficiary: FEE_REFUND_BENEFICIARY, ..Default::default() }, ); let tx = MorphTxEnv { - inner: TxEnv { - tx_type: if fee_token_id.is_some() { - MORPH_TX_TYPE_ID - } else { - 0 - }, - caller: FEE_REFUND_CALLER, - gas_limit: FEE_REFUND_GAS_LIMIT, - gas_price: FEE_REFUND_GAS_PRICE, - kind: TxKind::Call(FEE_REFUND_TARGET), - ..Default::default() - }, - fee_token_id, + tx_type: L1_TX_TYPE_ID, + gas_limit: 100_000, + kind: TxKind::Call(FEE_REFUND_TARGET), + // A queue index, unrelated to the sender's account nonce. + nonce: 77, ..Default::default() }; - let result = evm.transact_one(tx).expect("probe must execute"); - assert!(result.is_success(), "expected success, got {result:?}"); - result.output().cloned().unwrap_or_default() - } - /// Minimal proxy: copies its calldata into memory and `DELEGATECALL`s - /// `implementation`, the way mainnet's call-mode fee tokens reach theirs. - fn delegating_proxy_code(implementation: Address) -> Bytes { - let mut code = vec![ - 0x36, // CALLDATASIZE (size) - 0x5f, // PUSH0 (offset) - 0x5f, // PUSH0 (destOffset) - 0x37, // CALLDATACOPY - 0x5f, // PUSH0 (retSize) - 0x5f, // PUSH0 (retOffset) - 0x36, // CALLDATASIZE (argsSize) - 0x5f, // PUSH0 (argsOffset) - 0x73, // PUSH20 implementation - ]; - code.extend_from_slice(implementation.as_slice()); - code.extend_from_slice(&[ - 0x5a, // GAS - 0xf4, // DELEGATECALL - 0x3d, // RETURNDATASIZE (size) - 0x5f, // PUSH0 (offset) - 0x5f, // PUSH0 (destOffset) - 0x3e, // RETURNDATACOPY - 0x50, // POP (DELEGATECALL success flag) - 0x3d, // RETURNDATASIZE (size) - 0x5f, // PUSH0 (offset) - 0xf3, // RETURN - ]); - Bytes::from(code) - } + let result = transact(&mut evm, tx, caller).unwrap(); - /// Same ERC20, except `balanceOf` returns its result through the identity - /// precompile, reading the precompile's arguments out of memory. - fn fee_refund_precompile_erc20_code() -> Bytes { - let mut code = vec![ - 0x36, // CALLDATASIZE - 0x60, 0x44, // PUSH1 68 - 0x14, // EQ - 0x60, 0x1e, // PUSH1 30 (transfer JUMPDEST) - 0x57, // JUMPI - // balanceOf(address), answered by identity(mem[0..32]) - 0x60, 0x04, // PUSH1 4 - 0x35, // CALLDATALOAD - 0x54, // SLOAD - 0x5f, // PUSH0 - 0x52, // MSTORE - 0x60, 0x20, // PUSH1 32 (retSize) - 0x60, 0x20, // PUSH1 32 (retOffset) - 0x60, 0x20, // PUSH1 32 (argsSize) - 0x5f, // PUSH0 (argsOffset) - 0x60, 0x04, // PUSH1 4 (identity precompile) - 0x5a, // GAS - 0xfa, // STATICCALL - 0x50, // POP - 0x60, 0x20, // PUSH1 32 (size) - 0x60, 0x20, // PUSH1 32 (offset) - 0xf3, // RETURN - ]; - assert_eq!(code.len(), 30, "the transfer JUMPDEST moved"); - code.extend_from_slice(&fee_refund_slotless_erc20_code()[19..]); - Bytes::from(code) + assert!(result.status); + assert_eq!(result.refunded, 0, "L1 messages keep no refund"); + // 21_000 + PUSH0 + PUSH0 + SSTORE (cold 2_100 + 2_900). + assert_eq!(result.tx_gas_used(), 21_000 + 2 + 2 + 5_000); + assert_eq!(result.ext.l1_data_fee, U256::ZERO); + let sender = evm + .state_mut() + .account_info_untracked(&caller) + .unwrap() + .unwrap(); + assert_eq!(sender.nonce, 1, "the account nonce advances regardless"); + assert!( + evm.state_mut() + .account_info_untracked(&FEE_REFUND_BENEFICIARY) + .unwrap() + .is_none(), + "the fee recipient is untouched" + ); } - /// A precompile called from inside a fee frame resolves its arguments against - /// the context's shared buffer, so the fee frames have to keep writing into that - /// buffer rather than into one of their own. + /// An L1 message prepaid on L1 must run even if its gas limit does not cover intrinsic gas. #[test] - fn fee_token_frames_reach_a_precompile_through_memory() { - let fee = U256::from(FEE_REFUND_TOKEN_FEE); - let mut evm = fee_refund_evm(fee); - let db = evm.ctx_mut().journal_mut().db_mut(); - insert_contract(db, FEE_REFUND_TOKEN, fee_refund_precompile_erc20_code()); - assert_eq!( - fee_refund_run_fee_tx(&mut evm), - fee_refund_run_token_fee_tx(fee) - ); + fn l1_message_below_intrinsic_gas_consumes_its_gas_limit() { + let caller = FEE_REFUND_CALLER; + let mut evm = evm_with_spec(MorphHardfork::default()); + let tx = MorphTxEnv { + tx_type: L1_TX_TYPE_ID, + gas_limit: 20_000, + kind: TxKind::Call(FEE_REFUND_TARGET), + ..Default::default() + }; + + let result = transact(&mut evm, tx, caller).unwrap(); + + assert_eq!(result.tx_gas_used(), 20_000); } - /// Mainnet's call-mode fee tokens are proxies, so a fee frame's nested - /// `DELEGATECALL` reads its calldata back out of the frame's memory. #[test] - fn fee_token_frames_reach_a_delegating_proxy_implementation() { - const IMPLEMENTATION: Address = address!("3000000000000000000000000000000000000004"); - let fee = U256::from(FEE_REFUND_TOKEN_FEE); - let mut evm = fee_refund_evm(fee); - let db = evm.ctx_mut().journal_mut().db_mut(); - insert_contract(db, IMPLEMENTATION, fee_refund_slotless_erc20_code()); - insert_contract(db, FEE_REFUND_TOKEN, delegating_proxy_code(IMPLEMENTATION)); + fn registry_only_accepts_eip7702_from_prague() { + let caller = FEE_REFUND_CALLER; + let tx = MorphTxEnv { + tx_type: EIP7702_TX_TYPE, + chain_id: Some(1), + gas_limit: 100_000, + kind: TxKind::Call(FEE_REFUND_TARGET), + authorization_list: vec![sample_signed_authorization()], + ..Default::default() + }; - // Indistinguishable from the same transaction against an unproxied token: - // the implementation saw exactly the calldata the fee frame wrote. - assert_eq!( - fee_refund_run_fee_tx(&mut evm), - fee_refund_run_token_fee_tx(fee) - ); + let mut cancun = evm_with_spec(MorphHardfork::Morph203); + assert!(matches!( + transact(&mut cancun, tx.clone(), caller), + Err(HandlerError::UnsupportedTransactionType(EIP7702_TX_TYPE)) + )); + + let mut prague = evm_with_spec(MorphHardfork::Viridian); + assert!(transact(&mut prague, tx, caller).is_ok()); } - /// Runs the standard call-mode token-fee MorphTx on an already-built `evm` and - /// reports it the way [`fee_refund_run_token_fee_tx`] does. - fn fee_refund_run_fee_tx( - evm: &mut MorphEvm, NoOpInspector>, - ) -> (u64, u64, U256) { - let result = evm - .transact_one(MorphTxEnv { - inner: TxEnv { - tx_type: MORPH_TX_TYPE_ID, - caller: FEE_REFUND_CALLER, - gas_limit: FEE_REFUND_GAS_LIMIT, - gas_price: FEE_REFUND_GAS_PRICE, - kind: TxKind::Call(FEE_REFUND_TARGET), - ..Default::default() - }, - fee_token_id: Some(FEE_REFUND_TOKEN_ID), - ..Default::default() - }) - .expect("token-fee MorphTx must execute"); - assert!(result.is_success(), "expected success, got {result:?}"); - ( - result.tx_gas_used(), - result.gas().final_refunded(), - fee_refund_present_value(evm, FEE_REFUND_CALLER), - ) + /// `; STOP`, for an opcode that takes no arguments. + fn opcode_probe(opcode: u8) -> Bytes { + Bytes::from(vec![opcode, 0x00]) } - /// go-ethereum allocates a fresh `Memory` for every interpreter run - /// (`core/vm/interpreter.go`), so a transaction's frame always starts on zeroed - /// memory. The fee-token frames run on the transaction's shared memory buffer, - /// so they have to hand it back the length they found it at. + /// Runs `code` as the main frame and returns whether it succeeded and its gas used. + fn run_opcode_probe(spec: MorphHardfork, code: Bytes) -> (bool, u64) { + let mut db = InMemoryDB::default(); + insert_contract(&mut db, FEE_REFUND_TARGET, code); + let mut evm = evm_on(db, spec, MorphBlockEnv::default()); + let tx = MorphTxEnv { + gas_limit: 100_000, + kind: TxKind::Call(FEE_REFUND_TARGET), + ..Default::default() + }; + let result = transact(&mut evm, tx, FEE_REFUND_CALLER).unwrap(); + (result.status, result.tx_gas_used()) + } + + /// SELFDESTRUCT, BLOBHASH and BLOBBASEFEE halt on Morph, consuming the whole gas limit. #[test] - fn fee_token_frames_do_not_leak_memory_into_the_main_frame() { - // `MSIZE` and `MLOAD(0)`, each returned as the frame's 32-byte output. - for probe in [ - vec![0x59, 0x5f, 0x52, 0x60, 0x20, 0x5f, 0xf3], - vec![0x5f, 0x51, 0x5f, 0x52, 0x60, 0x20, 0x5f, 0xf3], + fn disabled_opcodes_halt_and_consume_all_gas() { + for code in [ + // PUSH0; SELFDESTRUCT + Bytes::from_static(&[0x5f, 0xff]), + // PUSH0; BLOBHASH + Bytes::from_static(&[0x5f, 0x49, 0x00]), + opcode_probe(0x4a), // BLOBBASEFEE ] { - let code = Bytes::from(probe); - assert_eq!( - U256::from_be_slice(&fee_refund_run_probe(code.clone(), None)), - U256::ZERO, - "ETH-fee control" - ); assert_eq!( - U256::from_be_slice(&fee_refund_run_probe(code, Some(FEE_REFUND_TOKEN_ID))), - U256::ZERO, - "a token-fee main frame must start on zeroed memory too" + run_opcode_probe(MorphHardfork::Celadon, code.clone()), + (false, 100_000), + "{code}" ); } } + + /// BLOCKHASH answers from the chain id and number rather than the header chain. + #[test] + fn blockhash_uses_morph_derivation() { + // PUSH4 2662437; BLOCKHASH; PUSH0; MSTORE; PUSH1 32; PUSH0; RETURN + let code = alloy_primitives::bytes!("630028a025405f5260205ff3"); + let mut db = InMemoryDB::default(); + insert_contract(&mut db, FEE_REFUND_TARGET, code); + let env = morph_evm_env( + MorphHardfork::default(), + 2818, + 30_000_000, + MorphBlockEnv { + number: U256::from(2_662_438u64), + ..Default::default() + }, + ); + let mut evm = morph_evm(db, env); + let tx = MorphTxEnv { + gas_limit: 100_000, + kind: TxKind::Call(FEE_REFUND_TARGET), + ..Default::default() + }; + + let result = transact(&mut evm, tx, FEE_REFUND_CALLER).unwrap(); + + assert!(result.status, "{result:?}"); + // Golden vector captured from geth debug_traceTransaction for block 2662438. + assert_eq!( + B256::from_slice(&result.output), + b256!("6d2426d9b8d6f63ec1a38d3a4e7b88f318ebe9f0d837c4781852168c5bd2678e") + ); + } } /// Alt-token refund rounding, gated on Celadon. @@ -3066,16 +3095,13 @@ mod tests { #[cfg(test)] mod refund_rounding_tests { use super::*; - use crate::{L2_TOKEN_REGISTRY_ADDRESS, MorphTxEnv, TokenFeeInfo, compute_mapping_slot}; - use alloy_primitives::{Address, TxKind, U256, address}; - use morph_chainspec::hardfork::MorphHardfork; - use morph_primitives::MORPH_TX_TYPE_ID; - use revm::{ - context::TxEnv, - database::{CacheDB, EmptyDB}, - inspector::NoOpInspector, - state::AccountInfo, + use crate::{ + L2_TOKEN_REGISTRY_ADDRESS, MorphBlockEnv, TokenFeeInfo, compute_mapping_slot, + evm::{morph_evm, morph_evm_env}, }; + use alloy_consensus::transaction::Recovered; + use alloy_primitives::{TxKind, address}; + use evm2::evm::{AccountInfo, InMemoryDB}; const CALLER: Address = address!("1000000000000000000000000000000000000001"); const BENEFICIARY: Address = address!("2000000000000000000000000000000000000002"); @@ -3092,13 +3118,10 @@ mod refund_rounding_tests { compute_mapping_slot_for_address(BALANCE_SLOT, account) } - fn token_balance( - evm: &mut MorphEvm, NoOpInspector>, - account: Address, - ) -> U256 { - let journal = evm.ctx.journal_mut(); - journal.load_account_mut(TOKEN).expect("load token"); - *journal.sload(TOKEN, slot_of(account)).expect("sload") + fn token_balance(evm: &mut MorphEvm<'_>, account: Address) -> U256 { + evm.state_mut() + .storage_slot_untracked(&TOKEN, &slot_of(account)) + .expect("read token balance") } fn ceil_to_token(eth_amount: u64) -> U256 { @@ -3110,6 +3133,15 @@ mod refund_rounding_tests { .eth_to_token_amount(U256::from(eth_amount)) } + fn block() -> MorphBlockEnv { + MorphBlockEnv { + beneficiary: BENEFICIARY, + basefee: U256::ZERO, + gas_limit: U256::from(30_000_000), + ..Default::default() + } + } + // ------------------------------------------------------------------------- // Whole-transaction coverage: deduction, call, refund // ------------------------------------------------------------------------- @@ -3117,14 +3149,13 @@ mod refund_rounding_tests { /// Registers the fee token in the L2TokenRegistry on the direct-slot path. /// /// `balanceSlot` is stored one-based, so zero there means "call mode". - fn register_slot_mode_token(db: &mut CacheDB) { + fn register_slot_mode_token(db: &mut InMemoryDB) { let mut token_id_bytes = [0u8; 32]; token_id_bytes[30..32].copy_from_slice(&FEE_TOKEN_ID.to_be_bytes()); let base = compute_mapping_slot(U256::from(151), &token_id_bytes); let mut put = |slot: U256, value: U256| { - db.insert_account_storage(L2_TOKEN_REGISTRY_ADDRESS, slot, value) - .unwrap(); + db.insert_account_storage(&L2_TOKEN_REGISTRY_ADDRESS, &slot, &value); }; put(base, U256::from_be_bytes(TOKEN.into_word().0)); put(base + U256::from(1), BALANCE_SLOT + U256::from(1)); @@ -3140,21 +3171,16 @@ mod refund_rounding_tests { } /// A funded caller with the fee token registered on the direct-slot path. - fn slot_mode_evm(spec: MorphHardfork) -> MorphEvm, NoOpInspector> { - let mut db = CacheDB::new(EmptyDB::default()); - db.insert_account_info(TOKEN, AccountInfo::default()); - db.insert_account_info(CALLER, AccountInfo::default()); + fn slot_mode_evm(spec: MorphHardfork) -> MorphEvm<'static> { + let mut db = InMemoryDB::default(); + // Not empty, so that EIP-161 keeps the touched token when the transaction commits. + db.insert_account_info(&TOKEN, AccountInfo::default().with_nonce(1)); + db.insert_account_info(&CALLER, AccountInfo::default()); register_slot_mode_token(&mut db); - db.insert_account_storage(TOKEN, slot_of(CALLER), U256::from(STARTING_BALANCE)) - .unwrap(); - db.insert_account_storage(TOKEN, slot_of(BENEFICIARY), U256::ZERO) - .unwrap(); + db.insert_account_storage(&TOKEN, &slot_of(CALLER), &U256::from(STARTING_BALANCE)); + db.insert_account_storage(&TOKEN, &slot_of(BENEFICIARY), &U256::ZERO); - let mut evm = MorphEvm::new(MorphContext::new(db, spec), NoOpInspector); - evm.block.inner.beneficiary = BENEFICIARY; - evm.block.inner.basefee = 0; - evm.block.inner.gas_limit = 30_000_000; - evm + morph_evm(db, morph_evm_env(spec, 1, 30_000_000, block())) } /// `calldata_len` bytes of non-zero calldata shift the transaction's gas @@ -3162,15 +3188,11 @@ mod refund_rounding_tests { /// `PRICE_RATIO`. fn fee_tx(gas_limit: u64, calldata_len: usize) -> MorphTxEnv { MorphTxEnv { - inner: TxEnv { - tx_type: MORPH_TX_TYPE_ID, - caller: CALLER, - kind: TxKind::Call(Address::repeat_byte(0x0e)), - gas_limit, - gas_price: 1, - data: alloy_primitives::Bytes::from(vec![0x01; calldata_len]), - ..Default::default() - }, + tx_type: MORPH_TX_TYPE_ID, + kind: TxKind::Call(Address::repeat_byte(0x0e)), + gas_limit, + gas_price: 1, + data: Bytes::from(vec![0x01; calldata_len]), fee_token_id: Some(FEE_TOKEN_ID), ..Default::default() } @@ -3180,15 +3202,16 @@ mod refund_rounding_tests { /// `(net token spend, gas used)`. fn net_token_spend(spec: MorphHardfork, gas_limit: u64, calldata_len: usize) -> (U256, u64) { let mut evm = slot_mode_evm(spec); + let tx = Recovered::new_unchecked(fee_tx(gas_limit, calldata_len), CALLER); let result = evm - .transact_one(fee_tx(gas_limit, calldata_len)) - .expect("token-fee MorphTx must execute"); - assert!(result.is_success(), "expected success, got {result:?}"); - let gas_used = result.tx_gas_used(); + .transact(&tx) + .expect("token-fee MorphTx must execute") + .commit(); + assert!(result.status, "expected success, got {result:?}"); ( U256::from(STARTING_BALANCE) - token_balance(&mut evm, CALLER), - gas_used, + result.tx_gas_used(), ) } @@ -3202,18 +3225,19 @@ mod refund_rounding_tests { fn deduction_records_the_rounding_credit_for_the_refund() { for (gas_limit, want_credit) in [(99_999u64, 0u64), (100_000, 2), (100_001, 1)] { let mut evm = slot_mode_evm(MorphHardfork::Celadon); - evm.tx = fee_tx(gas_limit, 0); - MorphEvmHandler::default() - .validate_against_state_and_deduct_caller( - &mut evm, - &mut InitialAndFloorGas::default(), - ) - .expect("deduction must succeed"); + let tx = fee_tx(gas_limit, 0); + let tx_env = TxEnvExt { + origin: CALLER, + gas_price: U256::from(1), + ..TxEnvExt::default() + }; + let charged = deduct_token_fee(&mut evm, &tx, CALLER, &tx_env, FEE_TOKEN_ID) + .unwrap_or_else(|err| panic!("deduction must succeed: {err}")); // The prepaid fee is `gas_limit` at price 1, so the credit is what // rounding `gas_limit / PRICE_RATIO` up left unused. assert_eq!( - evm.cached_alt_fee_rounding_credit, + charged.token_fee.unwrap().rounding_credit, U256::from(want_credit), "gas_limit {gas_limit}" ); @@ -3227,41 +3251,6 @@ mod refund_rounding_tests { /// have modulo `PRICE_RATIO`; the credit only changes the refund for some of /// those combinations, and the final assertion holds the sweep to covering /// them. - /// The credit belongs to one transaction. It is only read next to - /// `cached_token_fee_info`, which the same deduction writes, so a stale value - /// cannot reach a refund today. Clearing it with the other per-transaction - /// caches keeps that true without depending on where the reads happen. - #[test] - fn the_rounding_credit_does_not_outlive_its_transaction() { - let handler = MorphEvmHandler::default(); - let mut evm = slot_mode_evm(MorphHardfork::Celadon); - - evm.tx = fee_tx(100_000, 0); - handler - .validate_against_state_and_deduct_caller(&mut evm, &mut InitialAndFloorGas::default()) - .expect("deduction must succeed"); - assert_eq!(evm.cached_alt_fee_rounding_credit, U256::from(2u64)); - - // The next transaction on the same EVM pays no token fee. An L1 message is - // the shortest such path: it clears the caches and returns. - evm.tx = MorphTxEnv { - inner: TxEnv { - tx_type: morph_primitives::L1_TX_TYPE_ID, - caller: CALLER, - kind: TxKind::Call(Address::repeat_byte(0x0e)), - gas_limit: 100_000, - ..Default::default() - }, - ..Default::default() - }; - handler - .validate_against_state_and_deduct_caller(&mut evm, &mut InitialAndFloorGas::default()) - .expect("an L1 message needs no fee"); - - assert!(evm.cached_token_fee_info.is_none()); - assert_eq!(evm.cached_alt_fee_rounding_credit, U256::ZERO); - } - #[test] fn celadon_charges_the_ceiling_of_the_net_fee_end_to_end() { let mut seen_remainders = [false; PRICE_RATIO as usize]; @@ -3319,57 +3308,53 @@ mod refund_rounding_tests { // The refund step in isolation // ------------------------------------------------------------------------- - /// An EVM parked right before `reimburse_caller_token_fee`, holding the state - /// the deduction phase would have left behind: the fee already in the vault, - /// and `rounding_credit` recorded from the deduction's rounding-up. - fn evm_after_deduction( - spec: MorphHardfork, - rounding_credit: U256, - ) -> MorphEvm, NoOpInspector> { - let mut db = CacheDB::new(EmptyDB::default()); - db.insert_account_info(TOKEN, AccountInfo::default()); - db.insert_account_storage(TOKEN, slot_of(BENEFICIARY), U256::from(VAULT_BALANCE)) - .unwrap(); - db.insert_account_storage(TOKEN, slot_of(CALLER), U256::ZERO) - .unwrap(); + /// An EVM parked right before the refund, holding the state the deduction phase would + /// have left behind: the fee already in the vault. + fn evm_after_deduction(spec: MorphHardfork) -> MorphEvm<'static> { + let mut db = InMemoryDB::default(); + db.insert_account_info(&TOKEN, AccountInfo::default()); + db.insert_account_storage(&TOKEN, &slot_of(BENEFICIARY), &U256::from(VAULT_BALANCE)); + db.insert_account_storage(&TOKEN, &slot_of(CALLER), &U256::ZERO); - let mut evm = MorphEvm::new(MorphContext::new(db, spec), NoOpInspector); - evm.block.inner.beneficiary = BENEFICIARY; - evm.block.inner.basefee = 0; - evm.tx = MorphTxEnv { - inner: TxEnv { - tx_type: MORPH_TX_TYPE_ID, - caller: CALLER, - kind: TxKind::Call(Address::ZERO), - gas_limit: 100_000, - // With a zero basefee the effective gas price is 1, so the ETH to - // refund equals the gas left and the arithmetic reads directly. - gas_price: 1, - ..Default::default() - }, - fee_token_id: Some(FEE_TOKEN_ID), - ..Default::default() + morph_evm(db, morph_evm_env(spec, 1, 30_000_000, block())) + } + + /// Refunds `gas_left` worth of gas at a gas price of 1, so the ETH to refund equals the + /// gas left and the arithmetic reads directly. + fn refund(evm: &mut MorphEvm<'_>, gas_left: u64, rounding_credit: U256) { + let tx_env = TxEnvExt { + origin: CALLER, + gas_price: U256::from(1), + ..TxEnvExt::default() }; - evm.cached_token_fee_info = Some(TokenFeeInfo { - token_address: TOKEN, - is_active: true, - price_ratio: U256::from(PRICE_RATIO), - scale: U256::from(1u64), - caller: CALLER, - balance: U256::ZERO, - balance_slot: Some(BALANCE_SLOT), - ..Default::default() - }); - evm.cached_alt_fee_rounding_credit = rounding_credit; - evm + reimburse_token_fee( + evm, + &tx_env, + CALLER, + U256::from(1), + gas_left, + AppliedTokenFee { + info: TokenFeeInfo { + token_address: TOKEN, + is_active: true, + price_ratio: U256::from(PRICE_RATIO), + scale: U256::from(1u64), + caller: CALLER, + balance: U256::ZERO, + balance_slot: Some(BALANCE_SLOT), + ..Default::default() + }, + rounding_credit, + refund_counter: 0, + }, + ) + .expect("refund must not fail"); } /// Refunds `gas_left` worth of gas and reports what reached the caller. fn refund_with(spec: MorphHardfork, gas_left: u64, rounding_credit: U256) -> U256 { - let mut evm = evm_after_deduction(spec, rounding_credit); - MorphEvmHandler::default() - .reimburse_caller_token_fee(&mut evm, &Gas::new(gas_left)) - .expect("refund must not fail"); + let mut evm = evm_after_deduction(spec); + refund(&mut evm, gas_left, rounding_credit); token_balance(&mut evm, CALLER) } @@ -3419,22 +3404,16 @@ mod refund_rounding_tests { U256::from(1u64) ); - let mut evm = evm_after_deduction(MorphHardfork::Celadon, U256::ZERO); - MorphEvmHandler::default() - .reimburse_caller_token_fee(&mut evm, &Gas::new(2)) - .unwrap(); + let mut evm = evm_after_deduction(MorphHardfork::Celadon); + refund(&mut evm, 2, U256::ZERO); assert!( - evm.post_fee_logs.is_empty(), + evm.logs().is_empty(), "a zero refund must emit no Transfer log" ); - // Asserted before any read of our own: `token_balance` would itself pull - // the account and slot into the journal. assert!( - evm.ctx - .journal_mut() - .state - .get(&TOKEN) - .is_none_or(|token| token.storage.is_empty()), + evm.state() + .loaded_accounts() + .all(|(address, mut slots)| *address != TOKEN || slots.next().is_none()), "a zero refund must not load or write the token's balance slots" ); assert_eq!( diff --git a/crates/revm/src/l1block.rs b/crates/revm/src/l1block.rs index e99f2f6a..4e36d17f 100644 --- a/crates/revm/src/l1block.rs +++ b/crates/revm/src/l1block.rs @@ -22,8 +22,8 @@ //! | isCurie | bool | 9 | Curie hardfork flag | use alloy_primitives::{Address, U256, address}; +use evm2::evm::Database; use morph_chainspec::hardfork::MorphHardfork; -use revm::Database; // ============================================================================= // Gas Price Oracle Constants @@ -124,9 +124,24 @@ impl L1BlockInfo { db: &mut DB, hardfork: MorphHardfork, ) -> Result { - let l1_base_fee = db.storage(L1_GAS_PRICE_ORACLE_ADDRESS, GPO_L1_BASE_FEE_SLOT)?; - let l1_fee_overhead = db.storage(L1_GAS_PRICE_ORACLE_ADDRESS, GPO_OVERHEAD_SLOT)?; - let l1_base_fee_scalar = db.storage(L1_GAS_PRICE_ORACLE_ADDRESS, GPO_SCALAR_SLOT)?; + Self::try_fetch_with( + |slot| db.get_storage(&L1_GAS_PRICE_ORACLE_ADDRESS, &slot), + hardfork, + ) + } + + /// Fetches the L1 block info through `read`, which returns a storage slot of the L1 Gas + /// Price Oracle contract. + /// + /// The handler reads through the transaction overlay with this; it must not warm anything, + /// because go-ethereum reads these slots with `GetState`, outside the access list. + pub fn try_fetch_with( + mut read: impl FnMut(U256) -> Result, + hardfork: MorphHardfork, + ) -> Result { + let l1_base_fee = read(GPO_L1_BASE_FEE_SLOT)?; + let l1_fee_overhead = read(GPO_OVERHEAD_SLOT)?; + let l1_base_fee_scalar = read(GPO_SCALAR_SLOT)?; if !hardfork.is_curie() { Ok(Self { @@ -136,11 +151,9 @@ impl L1BlockInfo { ..Default::default() }) } else { - let l1_blob_base_fee = - db.storage(L1_GAS_PRICE_ORACLE_ADDRESS, GPO_L1_BLOB_BASE_FEE_SLOT)?; - let l1_commit_scalar = - db.storage(L1_GAS_PRICE_ORACLE_ADDRESS, GPO_COMMIT_SCALAR_SLOT)?; - let l1_blob_scalar = db.storage(L1_GAS_PRICE_ORACLE_ADDRESS, GPO_BLOB_SCALAR_SLOT)?; + let l1_blob_base_fee = read(GPO_L1_BLOB_BASE_FEE_SLOT)?; + let l1_commit_scalar = read(GPO_COMMIT_SCALAR_SLOT)?; + let l1_blob_scalar = read(GPO_BLOB_SCALAR_SLOT)?; // calldata component of commit fees (calldata gas + execution) let calldata_gas = l1_commit_scalar.saturating_mul(l1_base_fee); diff --git a/crates/revm/src/lib.rs b/crates/revm/src/lib.rs index a887c914..f8884bad 100644 --- a/crates/revm/src/lib.rs +++ b/crates/revm/src/lib.rs @@ -1,12 +1,12 @@ -//! Morph-specific revm implementations. +//! Morph-specific EVM execution on top of evm2. //! //! This crate provides low-level EVM execution logic for Morph L2, including //! custom transaction validation, fee handling, and L1 data fee calculation. //! //! # Main Components //! -//! - [`MorphEvm`]: The main EVM type with Morph-specific handler -//! - [`handler::MorphEvmHandler`]: Custom handler implementing fee deduction and reimbursement +//! - [`MorphEvm`]: An evm2 EVM with the Morph type family and transaction handler +//! - [`handler`]: Transaction handler implementing fee deduction and reimbursement //! - [`L1BlockInfo`]: L1 gas price oracle data for L1 data fee calculation //! - [`TokenFeeInfo`]: Token registry data for Morph transaction fee support //! @@ -27,27 +27,15 @@ //! //! # Error Types //! -//! - [`MorphHaltReason`]: EVM halt reasons (extends revm's `HaltReason`) -//! - [`MorphInvalidTransaction`]: Invalid transaction errors +//! - [`MorphInvalidTransaction`]: Invalid transaction errors, carried by +//! [`evm2::registry::HandlerError::External`] #![cfg_attr(not(test), warn(unused_crate_dependencies))] #![cfg_attr(docsrs, feature(doc_cfg))] mod block; -// Suppress unused_crate_dependencies warnings -#[cfg(not(test))] -use alloy_consensus as _; -use alloy_sol_types as _; -#[cfg(not(test))] -use reth_ethereum_primitives as _; -#[cfg(not(test))] -use tracing as _; - -mod common; -pub use common::{MorphStateAccess, MorphTx}; pub mod error; pub mod evm; -pub mod exec; pub mod handler; pub mod l1block; pub mod precompiles; @@ -55,8 +43,11 @@ pub mod token_fee; mod tx; pub use block::MorphBlockEnv; -pub use error::{MorphHaltReason, MorphInvalidTransaction}; -pub use evm::MorphEvm; +pub use error::MorphInvalidTransaction; +pub use evm::{ + FeeFrameFilter, MorphEvm, MorphEvmEnv, MorphEvmTypes, MorphMessageExt, MorphTxResultExt, + morph_evm, morph_evm_env, morph_version, +}; pub use l1block::{ GPO_BLOB_SCALAR_SLOT, GPO_COMMIT_SCALAR_SLOT, @@ -71,9 +62,9 @@ pub use l1block::{ L1_GAS_PRICE_ORACLE_ADDRESS, L1BlockInfo, }; -pub use precompiles::MorphPrecompiles; +pub use precompiles::morph_precompiles; pub use token_fee::{ - L2_TOKEN_REGISTRY_ADDRESS, MorphEvmEnv, TokenFeeInfo, compute_mapping_slot, + L2_TOKEN_REGISTRY_ADDRESS, TokenFeeInfo, compute_mapping_slot, compute_mapping_slot_for_address, encode_balance_of_calldata, }; pub use tx::{MorphTxEnv, MorphTxExt}; diff --git a/crates/revm/src/precompiles.rs b/crates/revm/src/precompiles.rs index d6a578a1..4ef7c251 100644 --- a/crates/revm/src/precompiles.rs +++ b/crates/revm/src/precompiles.rs @@ -27,30 +27,31 @@ //! via `StateDB.Prepare` (EIP-2929). CALL costs 100 gas (warm) instead of 2600 (cold). //! //! 2. When called, go-eth's CALL handler sets `gas = 0` for any non-revert error, consuming -//! all forwarded gas. revm's `PrecompileError` result also causes all forwarded gas to -//! be consumed (parent does not reclaim gas when sub-call is not ok-or-revert). +//! all forwarded gas. A `PrecompileHalt` also consumes all forwarded gas (the parent does +//! not reclaim gas when the sub-call neither succeeds nor reverts). //! //! Omitting these stubs causes morph-reth to treat 0x03/0x09 as cold empty accounts (2600 //! base cost, forwarded gas returned), creating a gas mismatch vs go-ethereum. +use crate::evm::{MorphEvm, MorphEvmTypes}; use alloy_primitives::Address; -use morph_chainspec::hardfork::MorphHardfork; -use revm::{ - context::Cfg, - context_interface::ContextTr, - handler::{EthPrecompiles, PrecompileProvider}, - interpreter::{CallInputs, InterpreterResult}, - precompile::{ - Precompile, PrecompileHalt, PrecompileId, PrecompileOutput, PrecompileResult, Precompiles, +use evm2::{ + SpecId, + interpreter::{GasTracker, Message}, + precompiles::{ + BLS12_381_G1_ADD, BLS12_381_G1_MSM, BLS12_381_G2_ADD, BLS12_381_G2_MSM, + BLS12_381_MAP_FP_TO_G1, BLS12_381_MAP_FP2_TO_G2, BLS12_381_PAIRING, MODEXP_OSAKA, + P256VERIFY_OSAKA, Precompile, PrecompileError, PrecompileHalt, PrecompileId, PrecompileMap, + PrecompileResult, Precompiles, bn254, modexp, }, - primitives::{AddressSet, OnceLock, hardfork::SpecId}, + utils::u64_to_address, }; -use std::string::String; +use morph_chainspec::hardfork::MorphHardfork; +use std::{borrow::Cow, sync::OnceLock}; /// Standard precompile addresses pub mod addresses { - use super::Address; - use revm::precompile::u64_to_address; + use super::{Address, u64_to_address}; /// ecrecover precompile address (1) pub const ECRECOVER: Address = u64_to_address(1); @@ -90,62 +91,42 @@ pub mod addresses { pub const P256_VERIFY: Address = u64_to_address(256); } -/// Morph precompile provider. +/// Precompile table of a Morph hardfork. +type MorphPrecompileMap = PrecompileMap; + +/// Returns the precompile provider of a Morph hardfork. /// -/// Implements Morph-specific precompile sets that match the Go implementation. -/// Each hardfork has specific precompiles enabled/disabled. -#[derive(Debug, Clone)] -pub struct MorphPrecompiles { - /// Inner Ethereum precompile provider. - inner: EthPrecompiles, - /// Current Morph hardfork. - spec: MorphHardfork, +/// Maps hardforks to their precompile sets based on the Go implementation: +/// +pub fn morph_precompiles(spec: MorphHardfork) -> Precompiles { + Precompiles::new(Cow::Borrowed(precompiles_for(spec))) } -impl MorphPrecompiles { - /// Create a new precompile provider with the given Morph hardfork. - /// - /// Maps hardforks to their precompile sets based on the Go implementation: - /// - #[inline] - pub fn new_with_spec(spec: MorphHardfork) -> Self { - let precompiles = match spec { - // Bernoulli and Curie share the same precompile set - // Go implementation has no PrecompiledContractsCurie - MorphHardfork::Bernoulli | MorphHardfork::Curie => bernoulli(), - // Morph203 and Viridian share the same precompile set - MorphHardfork::Morph203 | MorphHardfork::Viridian => morph203(), - // Emerald and Jade share the same precompile set. - MorphHardfork::Emerald | MorphHardfork::Jade | MorphHardfork::Celadon => emerald(), - hardfork => unreachable!("unsupported Morph hardfork: {hardfork:?}"), - }; - - Self { - inner: EthPrecompiles { - precompiles, - spec: SpecId::default(), - }, - spec, - } - } - - /// Returns the underlying precompiles. - #[inline] - pub fn precompiles(&self) -> &'static Precompiles { - self.inner.precompiles +/// Returns the precompile table of a Morph hardfork. +fn precompiles_for(spec: MorphHardfork) -> &'static MorphPrecompileMap { + match spec { + // Bernoulli and Curie share the same precompile set + // Go implementation has no PrecompiledContractsCurie + MorphHardfork::Bernoulli | MorphHardfork::Curie => bernoulli(), + // Morph203 and Viridian share the same precompile set + MorphHardfork::Morph203 | MorphHardfork::Viridian => morph203(), + // Emerald and Jade share the same precompile set. + MorphHardfork::Emerald | MorphHardfork::Jade | MorphHardfork::Celadon => emerald(), + hardfork => unreachable!("unsupported Morph hardfork: {hardfork:?}"), } +} - /// Returns whether the address is a precompile. - #[inline] - pub fn contains(&self, address: &Address) -> bool { - self.inner.contains(address) - } +/// The Berlin precompiles Morph's sets derive from. +fn berlin() -> Precompiles { + Precompiles::base(SpecId::BERLIN) } -impl Default for MorphPrecompiles { - fn default() -> Self { - Self::new_with_spec(MorphHardfork::default()) - } +/// A non-fatal failure: the CALL fails and burns its forwarded gas, as go-ethereum's CALL +/// handler does for any non-revert precompile error. +fn halt(reason: &'static str) -> PrecompileResult { + Err(PrecompileError::Halt(PrecompileHalt::Other(Cow::Borrowed( + reason, + )))) } /// Disabled stub for ripemd160 (0x03) in Bernoulli/Curie hardfork. @@ -153,11 +134,12 @@ impl Default for MorphPrecompiles { /// Returns a `PrecompileHalt` so the CALL handler treats the call as failure and /// burns all forwarded gas, matching go-ethereum's behavior where a disabled /// precompile error causes the CALL handler to consume all remaining gas. -fn ripemd160_disabled(_input: &[u8], _gas_limit: u64, reservoir: u64) -> PrecompileResult { - Ok(PrecompileOutput::halt( - PrecompileHalt::other("ripemd160 precompile disabled in Bernoulli/Curie hardfork"), - reservoir, - )) +fn ripemd160_disabled( + _evm: &mut MorphEvm<'_>, + _message: &Message, + _gas: &mut GasTracker, +) -> PrecompileResult { + halt("ripemd160 precompile disabled in Bernoulli/Curie hardfork") } /// Disabled stub for blake2f (0x09) in Bernoulli/Curie hardfork. @@ -165,11 +147,12 @@ fn ripemd160_disabled(_input: &[u8], _gas_limit: u64, reservoir: u64) -> Precomp /// Returns a `PrecompileHalt` so the CALL handler treats the call as failure and /// burns all forwarded gas, matching go-ethereum's behavior where a disabled /// precompile error causes the CALL handler to consume all remaining gas. -fn blake2f_disabled(_input: &[u8], _gas_limit: u64, reservoir: u64) -> PrecompileResult { - Ok(PrecompileOutput::halt( - PrecompileHalt::other("blake2f precompile disabled in Bernoulli/Curie hardfork"), - reservoir, - )) +fn blake2f_disabled( + _evm: &mut MorphEvm<'_>, + _message: &Message, + _gas: &mut GasTracker, +) -> PrecompileResult { + halt("blake2f precompile disabled in Bernoulli/Curie hardfork") } /// Checks if a 32-byte big-endian length field at `offset` in `data` exceeds 32. @@ -197,25 +180,22 @@ fn modexp_len_exceeds_32(data: &[u8], offset: usize) -> bool { /// that go-ethereum rejects, causing a consensus split. /// /// Ref: -fn modexp_with_32byte_limit(input: &[u8], gas_limit: u64, reservoir: u64) -> PrecompileResult { +fn modexp_with_32byte_limit( + _evm: &mut MorphEvm<'_>, + message: &Message, + gas: &mut GasTracker, +) -> PrecompileResult { + let input = message.input.as_ref(); // The first 96 bytes of modexp input are three 32-byte big-endian length fields: // [0..32] = base_len, [32..64] = exp_len, [64..96] = mod_len if modexp_len_exceeds_32(input, 0) || modexp_len_exceeds_32(input, 32) || modexp_len_exceeds_32(input, 64) { - return Ok(PrecompileOutput::halt( - PrecompileHalt::other( - "modexp temporarily only accepts inputs of 32 bytes (256 bits) or less", - ), - reservoir, - )); + return halt("modexp temporarily only accepts inputs of 32 bytes (256 bits) or less"); } - Precompiles::berlin() - .get(&addresses::MODEXP) - .expect("Berlin precompiles must include modexp") - .execute(input, gas_limit, reservoir) + modexp::run_berlin(input, gas) } /// Wraps BN256 pairing with go-ethereum's 4-pair input length limit. @@ -228,21 +208,16 @@ fn modexp_with_32byte_limit(input: &[u8], gas_limit: u64, reservoir: u64) -> Pre /// /// Ref: fn bn256_pairing_with_4pair_limit( - input: &[u8], - gas_limit: u64, - reservoir: u64, + _evm: &mut MorphEvm<'_>, + message: &Message, + gas: &mut GasTracker, ) -> PrecompileResult { + let input = message.input.as_ref(); if input.len() > 4 * 192 { - return Ok(PrecompileOutput::halt( - PrecompileHalt::other("bad elliptic curve pairing size"), - reservoir, - )); + return halt("bad elliptic curve pairing size"); } - Precompiles::berlin() - .get(&addresses::BN256_PAIRING) - .expect("Berlin precompiles must include BN256 pairing") - .execute(input, gas_limit, reservoir) + bn254::pair::run_istanbul(input, gas) } /// Returns precompiles for Bernoulli hardfork. @@ -252,30 +227,30 @@ fn bn256_pairing_with_4pair_limit( /// consume all forwarded gas and return failure when called. /// /// Matches: -pub fn bernoulli() -> &'static Precompiles { - static INSTANCE: OnceLock = OnceLock::new(); +pub fn bernoulli() -> &'static MorphPrecompileMap { + static INSTANCE: OnceLock = OnceLock::new(); INSTANCE.get_or_init(|| { // Start from Berlin (9 precompiles including 0x03 and 0x09). - let mut precompiles = Precompiles::berlin().clone(); + let mut precompiles = berlin().as_map().clone(); // Replace ripemd160 (0x03) and blake2f (0x09) with disabled stubs. - // This keeps them in warm_addresses() so EIP-2929 warms them (100 gas instead of - // 2600 cold), matching go-ethereum's PrecompiledContractsBernoulli behavior. + // This keeps them warmed by EIP-2929 (100 gas instead of 2600 cold), + // matching go-ethereum's PrecompiledContractsBernoulli behavior. precompiles.extend([ Precompile::new( - PrecompileId::Ripemd160, addresses::RIPEMD160, + PrecompileId::Ripemd160, ripemd160_disabled, ), - Precompile::new(PrecompileId::Blake2F, addresses::BLAKE2F, blake2f_disabled), + Precompile::new(addresses::BLAKE2F, PrecompileId::Blake2F, blake2f_disabled), ]); // Replace modexp (0x05) with 32-byte input limit wrapper. // go-ethereum's Bernoulli modexp has eip2565=true but neither eip7823 nor eip7883, - // which enforces base/exp/mod <= 32 bytes. Berlin modexp in revm has no such limit. + // which enforces base/exp/mod <= 32 bytes. Berlin modexp has no such limit. precompiles.extend([Precompile::new( - PrecompileId::ModExp, addresses::MODEXP, + PrecompileId::ModExp, modexp_with_32byte_limit, )]); @@ -289,28 +264,28 @@ pub fn bernoulli() -> &'static Precompiles { /// Enabled: ecrecover, sha256, ripemd160, identity, modexp, bn256 ops, blake2f /// /// Matches: PrecompiledContractsMorph203 in Go -pub fn morph203() -> &'static Precompiles { - static INSTANCE: OnceLock = OnceLock::new(); +pub fn morph203() -> &'static MorphPrecompileMap { + static INSTANCE: OnceLock = OnceLock::new(); INSTANCE.get_or_init(|| { // Start from Bernoulli and re-enable blake2f + ripemd160 let mut precompiles = bernoulli().clone(); - let berlin = Precompiles::berlin(); + let berlin = berlin(); // Re-enable blake2f (0x09) — was disabled stub in Bernoulli - if let Some(blake2f) = berlin.get(&addresses::BLAKE2F) { - precompiles.extend([blake2f.clone()]); + if let Some(blake2f) = berlin.as_map().get(&addresses::BLAKE2F) { + precompiles.extend([blake2f]); } // Re-enable ripemd160 (0x03) — was disabled stub in Bernoulli - if let Some(ripemd) = berlin.get(&addresses::RIPEMD160) { - precompiles.extend([ripemd.clone()]); + if let Some(ripemd) = berlin.as_map().get(&addresses::RIPEMD160) { + precompiles.extend([ripemd]); } // Replace BN256 pairing (0x08) with 4-pair limited version. // go-ethereum's Morph203 uses `limitInputLength: true` which caps // pairing input to 4 pairs (768 bytes). precompiles.extend([Precompile::new( - PrecompileId::Bn254Pairing, addresses::BN256_PAIRING, + PrecompileId::Bn254Pairing, bn256_pairing_with_4pair_limit, )]); @@ -329,38 +304,27 @@ pub fn morph203() -> &'static Precompiles { /// - Does **NOT** include KZG Point Evaluation (0x0a) — go-ethereum omits it /// /// Ref: -pub fn emerald() -> &'static Precompiles { - static INSTANCE: OnceLock = OnceLock::new(); +pub fn emerald() -> &'static MorphPrecompileMap { + static INSTANCE: OnceLock = OnceLock::new(); INSTANCE.get_or_init(|| { let mut precompiles = morph203().clone(); - let osaka = Precompiles::osaka(); - - // Upgrade modexp (0x05) from 32-byte-limited wrapper to osaka version. - // Emerald uses eip7823=true (1024-byte input cap) + eip7883=true (new gas formula), - // which replaces the Bernoulli~Viridian 32-byte restriction. - if let Some(modexp) = osaka.get(&addresses::MODEXP) { - precompiles.extend([modexp.clone()]); - } - - // Add BLS12-381 precompiles (EIP-2537): 0x0b through 0x11 - for addr in [ - addresses::BLS12_G1ADD, - addresses::BLS12_G1MULTIEXP, - addresses::BLS12_G2ADD, - addresses::BLS12_G2MULTIEXP, - addresses::BLS12_PAIRING, - addresses::BLS12_MAP_FP_TO_G1, - addresses::BLS12_MAP_FP2_TO_G2, - ] { - if let Some(precompile) = osaka.get(&addr) { - precompiles.extend([precompile.clone()]); - } - } - // Add P256verify (RIP-7212) at 0x100 - if let Some(p256) = osaka.get(&addresses::P256_VERIFY) { - precompiles.extend([p256.clone()]); - } + precompiles.extend([ + // Upgrade modexp (0x05) from the 32-byte-limited wrapper to the Osaka version. + // Emerald uses eip7823=true (1024-byte input cap) + eip7883=true (new gas formula), + // which replaces the Bernoulli~Viridian 32-byte restriction. + MODEXP_OSAKA::(), + // Add BLS12-381 precompiles (EIP-2537): 0x0b through 0x11 + BLS12_381_G1_ADD::(), + BLS12_381_G1_MSM::(), + BLS12_381_G2_ADD::(), + BLS12_381_G2_MSM::(), + BLS12_381_PAIRING::(), + BLS12_381_MAP_FP_TO_G1::(), + BLS12_381_MAP_FP2_TO_G2::(), + // Add P256verify (RIP-7212) at 0x100 + P256VERIFY_OSAKA::(), + ]); // NOTE: KZG Point Evaluation (0x0a) is intentionally NOT included. // go-ethereum's PrecompiledContractsEmerald skips 0x0a entirely. @@ -369,64 +333,44 @@ pub fn emerald() -> &'static Precompiles { }) } -impl PrecompileProvider for MorphPrecompiles -where - CTX: ContextTr>, -{ - type Output = InterpreterResult; - - #[inline] - fn set_spec(&mut self, spec: ::Spec) -> bool { - if spec == self.spec { - return false; - } - *self = Self::new_with_spec(spec); - true - } - - #[inline] - fn run( - &mut self, - context: &mut CTX, - inputs: &CallInputs, - ) -> Result, String> { - self.inner.run(context, inputs) - } - - #[inline] - fn warm_addresses(&self) -> &AddressSet { - self.inner.warm_addresses() - } - - #[inline] - fn contains(&self, address: &Address) -> bool { - Self::contains(self, address) - } -} - #[cfg(test)] mod tests { use super::*; - use revm::precompile::PrecompileStatus; + use crate::{MorphBlockEnv, evm::morph_evm_env}; + use alloy_primitives::Bytes; + use evm2::evm::InMemoryDB; + + /// Runs `precompile` on `input` with `gas_limit` gas. + fn execute( + precompile: &Precompile, + input: &[u8], + gas_limit: u64, + ) -> PrecompileResult { + let env = morph_evm_env( + MorphHardfork::Celadon, + 1, + u64::MAX, + MorphBlockEnv::default(), + ); + let mut evm = crate::evm::morph_evm(InMemoryDB::default(), env); + let message = Message:: { + input: Bytes::copy_from_slice(input).into(), + gas_limit, + ..Default::default() + }; + precompile.run()(&mut evm, &message, &mut GasTracker::new(gas_limit)) + } - /// Returns true if the precompile execution result should be considered a failed - /// CALL (halt status or fatal error). Mirrors the old `result.is_err()` semantics - /// from revm 36 where rejection variants like `PrecompileError::Other` were errors. + /// Returns true if the precompile execution result should be considered a failed CALL. fn is_call_failure(result: &PrecompileResult) -> bool { - match result { - Ok(output) => matches!(output.status, PrecompileStatus::Halt(_)), - Err(_) => true, - } + result.is_err() } - /// Extracts a `PrecompileHalt` from a result that is expected to be a halt-on-Ok. + /// Extracts the halt reason from a result that is expected to be a halt. fn halt_reason(result: PrecompileResult) -> PrecompileHalt { match result { - Ok(output) => match output.status { - PrecompileStatus::Halt(reason) => reason, - other => panic!("expected halt status, got: {other:?}"), - }, - Err(err) => panic!("expected halt-on-Ok, got fatal error: {err:?}"), + Err(PrecompileError::Halt(reason)) => reason, + other => panic!("expected a halt, got: {other:?}"), } } @@ -462,7 +406,7 @@ mod tests { input[31] = 33; // base_len = 33 input[63] = 32; // exp_len = 32 input[95] = 32; // mod_len = 32 - let result = modexp.execute(&input, 100_000, 0); + let result = execute(&modexp, &input, 100_000); assert!( is_call_failure(&result), "modexp with base_len=33 should be rejected" @@ -470,7 +414,7 @@ mod tests { // base_len=32, exp_len=32, mod_len=32 — should succeed input[31] = 32; - let result = modexp.execute(&input, 100_000, 0); + let result = execute(&modexp, &input, 100_000); assert!( !is_call_failure(&result), "modexp with all lens=32 should succeed" @@ -479,10 +423,10 @@ mod tests { #[test] fn test_curie_uses_bernoulli_precompiles() { - let bernoulli_p = MorphPrecompiles::new_with_spec(MorphHardfork::Bernoulli); - let curie_p = MorphPrecompiles::new_with_spec(MorphHardfork::Curie); + let bernoulli_p = precompiles_for(MorphHardfork::Bernoulli); + let curie_p = precompiles_for(MorphHardfork::Curie); - assert_eq!(bernoulli_p.precompiles().len(), curie_p.precompiles().len()); + assert_eq!(bernoulli_p.len(), curie_p.len()); assert!(curie_p.contains(&addresses::SHA256)); assert!(curie_p.contains(&addresses::RIPEMD160)); assert!(curie_p.contains(&addresses::BLAKE2F)); @@ -513,7 +457,7 @@ mod tests { // 5 pairs (960 bytes) — exceeds 4-pair limit, should be rejected let input = vec![0u8; 5 * 192]; - let result = pairing.execute(&input, 1_000_000, 0); + let result = execute(&pairing, &input, 1_000_000); assert!( is_call_failure(&result), "pairing with 5 pairs should be rejected" @@ -522,7 +466,7 @@ mod tests { // 4 pairs (768 bytes) — within limit, should not be rejected for size // (may still fail due to invalid curve points, but not for size) let input = vec![0u8; 4 * 192]; - let result = pairing.execute(&input, 1_000_000, 0); + let result = execute(&pairing, &input, 1_000_000); // Zero-input pairing is valid and returns true assert!( !is_call_failure(&result), @@ -578,7 +522,7 @@ mod tests { input[31] = 64; // base_len = 64 input[63] = 32; // exp_len = 32 input[95] = 64; // mod_len = 64 - let result = modexp.execute(&input, 1_000_000, 0); + let result = execute(&modexp, &input, 1_000_000); assert!( !is_call_failure(&result), "Emerald modexp should accept base_len=64" @@ -594,25 +538,22 @@ mod tests { #[test] fn test_hardfork_specific_precompiles() { - let bernoulli_p = MorphPrecompiles::new_with_spec(MorphHardfork::Bernoulli); - let curie_p = MorphPrecompiles::new_with_spec(MorphHardfork::Curie); - let morph203_p = MorphPrecompiles::new_with_spec(MorphHardfork::Morph203); - let viridian_p = MorphPrecompiles::new_with_spec(MorphHardfork::Viridian); - let emerald_p = MorphPrecompiles::new_with_spec(MorphHardfork::Emerald); + let bernoulli_p = precompiles_for(MorphHardfork::Bernoulli); + let curie_p = precompiles_for(MorphHardfork::Curie); + let morph203_p = precompiles_for(MorphHardfork::Morph203); + let viridian_p = precompiles_for(MorphHardfork::Viridian); + let emerald_p = precompiles_for(MorphHardfork::Emerald); // Bernoulli/Curie: disabled stubs present, same set assert!(bernoulli_p.contains(&addresses::RIPEMD160)); assert!(bernoulli_p.contains(&addresses::BLAKE2F)); - assert_eq!(bernoulli_p.precompiles().len(), curie_p.precompiles().len()); + assert_eq!(bernoulli_p.len(), curie_p.len()); // Morph203/Viridian: re-enabled, no P256verify, same set assert!(morph203_p.contains(&addresses::RIPEMD160)); assert!(morph203_p.contains(&addresses::BLAKE2F)); assert!(!morph203_p.contains(&addresses::P256_VERIFY)); - assert_eq!( - morph203_p.precompiles().len(), - viridian_p.precompiles().len() - ); + assert_eq!(morph203_p.len(), viridian_p.len()); // Emerald: full set with BLS12-381 + P256verify, no KZG assert!(emerald_p.contains(&addresses::P256_VERIFY)); @@ -627,7 +568,7 @@ mod tests { // Calling the disabled stub should halt (consuming all forwarded gas at the // caller, since the CALL frame treats `Halt` as failure). - let result = ripemd.execute(b"hello", 100_000, 0); + let result = execute(&ripemd, b"hello", 100_000); assert!( is_call_failure(&result), "disabled ripemd160 should halt the call" @@ -650,7 +591,7 @@ mod tests { // Calling the disabled stub should halt (consuming all forwarded gas at the // caller, since the CALL frame treats `Halt` as failure). - let result = blake2f.execute(b"hello", 100_000, 0); + let result = execute(&blake2f, b"hello", 100_000); assert!( is_call_failure(&result), "disabled blake2f should halt the call" @@ -672,7 +613,7 @@ mod tests { let ripemd = precompiles.get(&addresses::RIPEMD160).unwrap(); // In Morph203, ripemd160 is re-enabled and should work (not return disabled halt) - let result = ripemd.execute(b"hello", 100_000, 0); + let result = execute(&ripemd, b"hello", 100_000); assert!( !is_call_failure(&result), "morph203 ripemd160 should be functional: {result:?}" @@ -686,10 +627,8 @@ mod tests { // blake2f requires specific input format (213 bytes), but the point is it should // NOT return the "disabled" halt. An invalid-input halt is acceptable. - let result = blake2f.execute(b"hello", 100_000, 0); - if let Ok(output) = &result - && let PrecompileStatus::Halt(PrecompileHalt::Other(msg)) = &output.status - { + let result = execute(&blake2f, b"hello", 100_000); + if let Err(PrecompileError::Halt(PrecompileHalt::Other(msg))) = &result { assert!( !msg.contains("disabled"), "morph203 blake2f should NOT be disabled: {msg}" @@ -704,7 +643,7 @@ mod tests { // 5 pairs (960 bytes) — Bernoulli uses Berlin pairing with no 4-pair limit let input = vec![0u8; 5 * 192]; - let result = pairing.execute(&input, 1_000_000, 0); + let result = execute(&pairing, &input, 1_000_000); // Should succeed (zero-padded valid points), NOT rejected for size assert!( !is_call_failure(&result), @@ -719,7 +658,7 @@ mod tests { // Exactly 4 pairs (768 bytes) — should succeed let input = vec![0u8; 4 * 192]; - let result = pairing.execute(&input, 1_000_000, 0); + let result = execute(&pairing, &input, 1_000_000); assert!( !is_call_failure(&result), "pairing with exactly 4 pairs should succeed" @@ -727,7 +666,7 @@ mod tests { // 4 pairs + 1 byte (769 bytes) — should be rejected let input = vec![0u8; 4 * 192 + 1]; - let result = pairing.execute(&input, 1_000_000, 0); + let result = execute(&pairing, &input, 1_000_000); assert!( is_call_failure(&result), "pairing with 769 bytes should be rejected" @@ -736,12 +675,12 @@ mod tests { #[test] fn test_jade_uses_emerald_precompiles() { - let emerald_p = MorphPrecompiles::new_with_spec(MorphHardfork::Emerald); - let jade_p = MorphPrecompiles::new_with_spec(MorphHardfork::Jade); + let emerald_p = precompiles_for(MorphHardfork::Emerald); + let jade_p = precompiles_for(MorphHardfork::Jade); assert_eq!( - emerald_p.precompiles().len(), - jade_p.precompiles().len(), + emerald_p.len(), + jade_p.len(), "Jade should use same precompile set as Emerald" ); assert!(jade_p.contains(&addresses::P256_VERIFY)); @@ -751,12 +690,12 @@ mod tests { #[test] fn test_default_precompiles_use_jade() { - let default_p = MorphPrecompiles::default(); - let jade_p = MorphPrecompiles::new_with_spec(MorphHardfork::Jade); + let default_p = precompiles_for(MorphHardfork::default()); + let jade_p = precompiles_for(MorphHardfork::Jade); assert_eq!( - default_p.precompiles().len(), - jade_p.precompiles().len(), + default_p.len(), + jade_p.len(), "Default precompiles should match Jade" ); } @@ -793,13 +732,13 @@ mod tests { 0x5a, 0x9c, 0x45, 0x49, ]); - let result = ecrecover.execute(&input, 10_000, 0); + let result = execute(&ecrecover, &input, 10_000); assert!( !is_call_failure(&result), "valid ecrecover should succeed: {result:?}" ); - let output = result.unwrap().bytes; + let output = result.unwrap().into_bytes(); assert_eq!(output.len(), 32, "ecrecover output must be 32 bytes"); // First 12 bytes must be zero (address is right-aligned in 32 bytes) @@ -821,7 +760,7 @@ mod tests { let precompiles = bernoulli(); let sha256 = precompiles.get(&addresses::SHA256).unwrap(); - let result = sha256.execute(&[], 100_000, 0); + let result = execute(&sha256, &[], 100_000); assert!( !is_call_failure(&result), "sha256 of empty input should succeed" @@ -833,11 +772,7 @@ mod tests { 0xb9, 0x24, 0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c, 0xa4, 0x95, 0x99, 0x1b, 0x78, 0x52, 0xb8, 0x55, ]; - assert_eq!( - &result.unwrap().bytes[..], - &expected, - "sha256(\"\") mismatch" - ); + assert_eq!(result.unwrap().bytes(), &expected, "sha256(\"\") mismatch"); } /// Identity (0x04) passes through its input unchanged. @@ -847,10 +782,10 @@ mod tests { let identity = precompiles.get(&addresses::IDENTITY).unwrap(); let input: &[u8] = &[0x12, 0x34, 0xab, 0xcd]; - let result = identity.execute(input, 100_000, 0); + let result = execute(&identity, input, 100_000); assert!(!is_call_failure(&result), "identity should succeed"); assert_eq!( - &result.unwrap().bytes[..], + result.unwrap().bytes(), input, "identity must return input unchanged" ); diff --git a/crates/revm/src/token_fee.rs b/crates/revm/src/token_fee.rs index 445035c2..012a5269 100644 --- a/crates/revm/src/token_fee.rs +++ b/crates/revm/src/token_fee.rs @@ -5,21 +5,17 @@ //! //! Reference: -use alloy_evm::Database; use alloy_primitives::{Address, Bytes, U256, address, keccak256}; -use morph_chainspec::hardfork::MorphHardfork; -use revm::Database as RevmDatabase; -use revm::{context_interface::result::EVMError, inspector::NoOpInspector}; +use evm2::{ + env::TxEnvExt, + evm::{Database, Db}, + registry::HandlerError, +}; -use crate::{MorphEvm, MorphInvalidTransaction}; - -/// The environment a fee-token `balanceOf` call is evaluated in. -/// -/// Produced by `ConfigureEvm::evm_env` for the block whose state is being read, so the pool -/// resolves the same balance the execution layer would. go-ethereum builds the equivalent -/// `vm.BlockContext` from the header before querying a call-mode token -/// (`pool.getBalanceFunc`, core/tx_pool.go:330). -pub type MorphEvmEnv = alloy_evm::EvmEnv; +use crate::{ + MorphInvalidTransaction, + evm::{MorphEvmEnv, morph_evm}, +}; /// L2 Token Registry contract address on Morph L2. /// Reference: @@ -79,11 +75,19 @@ impl TokenRegistryEntry { } /// Load fee-token metadata without reading a caller's token balance. - pub(crate) fn load( + pub(crate) fn load( db: &mut DB, token_id: u16, ) -> Result, DB::Error> { - read_registry_entry(db, token_id) + Self::load_with(|address, slot| db.get_storage(&address, &slot), token_id) + } + + /// As [`Self::load`], reading storage through `read`. + pub(crate) fn load_with( + read: impl FnMut(Address, U256) -> Result, + token_id: u16, + ) -> Result, E> { + read_registry_entry(read, token_id) } /// Reject registry entries that cannot produce a valid token-denominated fee. @@ -103,7 +107,7 @@ impl TokenRegistryEntry { db: &mut DB, caller: Address, env: &MorphEvmEnv, - ) -> Result> { + ) -> Result { let balance = read_token_balance_with_fallback( db, self.token_address, @@ -114,13 +118,18 @@ impl TokenRegistryEntry { Ok(self.into_fee_info(caller, balance)) } - fn load_storage_only( + fn load_storage_only( self, db: &mut DB, caller: Address, ) -> Result { let balance = if let Some(slot) = self.balance_slot { - read_balance_from_storage(db, self.token_address, caller, slot)? + read_balance_from_storage( + |address, slot| db.get_storage(&address, &slot), + self.token_address, + caller, + slot, + )? } else { U256::ZERO }; @@ -162,8 +171,8 @@ impl TokenFeeInfo { token_id: u16, caller: Address, env: &MorphEvmEnv, - ) -> Result, EVMError> { - let entry = match TokenRegistryEntry::load(db, token_id)? { + ) -> Result, HandlerError> { + let entry = match TokenRegistryEntry::load(db, token_id).map_err(database_error::)? { Some(e) => e, None => return Ok(None), }; @@ -177,7 +186,7 @@ impl TokenFeeInfo { /// known — the caller's ERC20 balance directly from contract storage. /// Unlike [`Self::load_for_caller`] this never spins up a temporary /// `MorphEvm`, so it is callable from RPC code paths that only have - /// `revm::Database` (no `Debug` bound, no `MorphContext` setup). + /// a typed [`Database`] and no block environment. /// /// Behaviour: /// - Returns `Ok(None)` if the token is not registered. @@ -186,7 +195,7 @@ impl TokenFeeInfo { /// slot is unknown — callers are expected to skip token-balance /// enforcement in that case (the handler re-checks the balance via /// an EVM call during execution). - pub fn load_storage_only( + pub fn load_storage_only( db: &mut DB, token_id: u16, caller: Address, @@ -199,6 +208,23 @@ impl TokenFeeInfo { entry.load_storage_only(db, caller).map(Some) } + /// As [`Self::load_storage_only`], reading storage through `read`. + pub fn load_storage_only_with( + mut read: impl FnMut(Address, U256) -> Result, + token_id: u16, + caller: Address, + ) -> Result, E> { + let entry = match TokenRegistryEntry::load_with(&mut read, token_id)? { + Some(e) => e, + None => return Ok(None), + }; + let balance = match entry.balance_slot { + Some(slot) => read_balance_from_storage(&mut read, entry.token_address, caller, slot)?, + None => U256::ZERO, + }; + Ok(Some(entry.into_fee_info(caller, balance))) + } + /// Calculate the token amount required for a given ETH amount, rounding up. /// /// Uses the price ratio and scale to convert ETH value to token amount. @@ -264,10 +290,10 @@ impl TokenFeeInfo { } } -fn read_registry_entry( - db: &mut DB, +fn read_registry_entry( + mut read: impl FnMut(Address, U256) -> Result, token_id: u16, -) -> Result, DB::Error> { +) -> Result, E> { // Get the base slot for this token_id in tokenRegistry mapping let mut token_id_bytes = [0u8; 32]; token_id_bytes[30..32].copy_from_slice(&token_id.to_be_bytes()); @@ -279,13 +305,13 @@ fn read_registry_entry( // base + 2: isActive (1 byte) + decimals (1 byte) + padding // base + 3: scale (32 bytes) - let slot_0 = db.storage(L2_TOKEN_REGISTRY_ADDRESS, base)?; + let slot_0 = read(L2_TOKEN_REGISTRY_ADDRESS, base)?; let token_address = Address::from_word(slot_0.into()); if token_address == Address::default() { return Ok(None); } - let balance_slot_raw = db.storage(L2_TOKEN_REGISTRY_ADDRESS, base + U256::from(1))?; + let balance_slot_raw = read(L2_TOKEN_REGISTRY_ADDRESS, base + U256::from(1))?; let balance_slot = if !balance_slot_raw.is_zero() { Some(balance_slot_raw.saturating_sub(U256::from(1))) } else { @@ -293,16 +319,16 @@ fn read_registry_entry( }; // isActive at byte 31, decimals at byte 30 (big-endian) - let slot_2 = db.storage(L2_TOKEN_REGISTRY_ADDRESS, base + U256::from(2))?; + let slot_2 = read(L2_TOKEN_REGISTRY_ADDRESS, base + U256::from(2))?; let bytes = slot_2.to_be_bytes::<32>(); let is_active = bytes[31] != 0; let decimals = bytes[30]; - let scale = db.storage(L2_TOKEN_REGISTRY_ADDRESS, base + U256::from(3))?; + let scale = read(L2_TOKEN_REGISTRY_ADDRESS, base + U256::from(3))?; // Get price ratio from priceRatio mapping let price_ratio = read_mapping_value( - db, + &mut read, L2_TOKEN_REGISTRY_ADDRESS, PRICE_RATIO_SLOT, &token_id_bytes, @@ -343,13 +369,19 @@ pub fn compute_mapping_slot_for_address(base_slot: U256, account: Address) -> U2 /// Load a value from a mapping in contract storage. #[inline] -fn read_mapping_value( - db: &mut DB, +fn read_mapping_value( + read: &mut impl FnMut(Address, U256) -> Result, contract: Address, base_slot: U256, key: &[u8; 32], -) -> Result { - db.storage(contract, compute_mapping_slot(base_slot, key)) +) -> Result { + read(contract, compute_mapping_slot(base_slot, key)) +} + +/// Wraps a typed database error the way evm2's database adapter does. +fn database_error(error: DB::Error) -> HandlerError { + let fatal = DB::is_fatal(&error); + evm2::DatabaseError::new(error, fatal).into() } /// Read ERC20 balance with EVM call fallback. @@ -362,40 +394,48 @@ fn read_token_balance_with_fallback( account: Address, balance_slot: Option, env: &MorphEvmEnv, -) -> Result> { +) -> Result { if let Some(slot) = balance_slot { - return Ok(read_balance_from_storage(db, token, account, slot)?); + return read_balance_from_storage( + |address, slot| db.get_storage(&address, &slot), + token, + account, + slot, + ) + .map_err(database_error::); } // Call mode: stand the EVM up in the caller's environment rather than a default one, // and make the same `balanceOf` call the execution layer makes, so both reach the same // answer for a token whose balance depends on block context or `msg.sender`. - let db: &mut dyn Database = db; - let mut evm = MorphEvm::from_env(db, env.clone(), NoOpInspector {}); + let mut evm = morph_evm(Db::new(db), env.clone()); // ORIGIN follows this client's own execution layer, which resolves the same // `balanceOf` against the transaction's `caller`. go-ethereum's pool instead builds // its query on an empty `vm.TxContext{}` (core/tx_pool.go:341), leaving ORIGIN at the // zero address and disagreeing with go-ethereum's own execution layer. Admission // exists to predict what the builder will be able to include, so it follows execution // rather than the other client's pool. GASPRICE is the one input this query still - // cannot match: it stays at the `TxEnv` default of zero because the effective price - // depends on the next block's base fee, which admission does not know. go-ethereum's - // pool has the same gap. - evm.tx.inner.caller = account; - crate::handler::evm_call_balance_of(&mut evm, token, account) + // cannot match: it stays at zero because the effective price depends on the next + // block's base fee, which admission does not know. go-ethereum's pool has the same gap. + let tx_env = TxEnvExt { + origin: account, + chain_id: U256::from(evm.version().chain_id), + ..TxEnvExt::default() + }; + crate::handler::evm_call_balance_of(&mut evm, &tx_env, token, account) } /// Read ERC20 balance directly from storage slot. #[inline] -pub(crate) fn read_balance_from_storage( - db: &mut DB, +pub(crate) fn read_balance_from_storage( + mut read: impl FnMut(Address, U256) -> Result, token: Address, account: Address, balance_slot: U256, -) -> Result { +) -> Result { let mut key = [0u8; 32]; key[12..32].copy_from_slice(account.as_slice()); - read_mapping_value(db, token, balance_slot, &key) + read_mapping_value(&mut read, token, balance_slot, &key) } /// Encode ERC20 `balanceOf(address)` calldata. @@ -414,10 +454,14 @@ pub fn encode_balance_of_calldata(account: Address) -> Bytes { pub(crate) mod tests { use super::*; + use crate::MorphBlockEnv; use alloy_primitives::{B256, address, bytes}; - use revm::bytecode::Bytecode; - use revm::database::{CacheDB, EmptyDB}; - use revm::state::AccountInfo; + use evm2::{ + bytecode::Bytecode, + evm::{AccountInfo, CacheDB, DynDatabase, EmptyDB, InMemoryDB}, + interpreter::Word, + }; + use morph_chainspec::hardfork::MorphHardfork; /// The storage read failure injected by [`UnreadableTokenDb`], distinguishable from any /// error a real database would report. Shared with the handler tests. @@ -432,52 +476,76 @@ pub(crate) mod tests { impl core::error::Error for TokenReadFailure {} - impl revm::database_interface::DBErrorMarker for TokenReadFailure {} - /// Fails every storage read of `token` with [`TokenReadFailure`]; everything else reads /// normally, so a failure a test observes comes from that token's storage. Shared with the /// handler tests. #[derive(Debug)] pub(crate) struct UnreadableTokenDb { - pub(crate) inner: CacheDB, + pub(crate) inner: InMemoryDB, pub(crate) token: Address, } - impl RevmDatabase for UnreadableTokenDb { + impl Database for UnreadableTokenDb { type Error = TokenReadFailure; - fn basic(&mut self, address: Address) -> Result, Self::Error> { - Ok(self.inner.basic(address).unwrap()) + fn get_account(&mut self, address: &Address) -> Result, Self::Error> { + Ok(DynDatabase::get_account(&mut self.inner, address).unwrap()) } - fn code_by_hash(&mut self, code_hash: B256) -> Result { - Ok(self.inner.code_by_hash(code_hash).unwrap()) + fn get_code_by_hash(&mut self, code_hash: &B256) -> Result { + Ok(DynDatabase::get_code_by_hash(&mut self.inner, code_hash).unwrap()) } - fn storage(&mut self, address: Address, index: U256) -> Result { - if address == self.token { + fn get_storage(&mut self, address: &Address, key: &Word) -> Result { + if *address == self.token { return Err(TokenReadFailure); } - Ok(self.inner.storage(address, index).unwrap()) + Ok(DynDatabase::get_storage(&mut self.inner, address, key).unwrap()) } - fn block_hash(&mut self, number: u64) -> Result { - Ok(self.inner.block_hash(number).unwrap()) + fn get_block_hash(&mut self, number: &Word) -> Result { + Ok(DynDatabase::get_block_hash(&mut self.inner, number).unwrap()) + } + } + + /// Whether `error` carries the failure injected by [`UnreadableTokenDb`]. + pub(crate) fn is_token_read_failure(error: &HandlerError) -> bool { + matches!(error, HandlerError::Database(db) if db.downcast_ref::().is_some()) + } + + /// Adapts an infallible in-memory database to the typed [`Database`] the public token-fee + /// helpers take. + #[derive(Debug)] + pub(crate) struct Plain(pub(crate) InMemoryDB); + + impl Database for Plain { + type Error = evm2::DatabaseError; + + fn get_account(&mut self, address: &Address) -> Result, Self::Error> { + DynDatabase::get_account(&mut self.0, address) + } + + fn get_code_by_hash(&mut self, code_hash: &B256) -> Result { + DynDatabase::get_code_by_hash(&mut self.0, code_hash) + } + + fn get_storage(&mut self, address: &Address, key: &Word) -> Result { + DynDatabase::get_storage(&mut self.0, address, key) + } + + fn get_block_hash(&mut self, number: &Word) -> Result { + DynDatabase::get_block_hash(&mut self.0, number) } } /// Registry state for a call-mode token (no `balanceSlot`) whose `balanceOf` returns /// storage slot 0, so reading it is a storage read of the token contract. - fn call_mode_token_state(token: Address, balance: u64) -> CacheDB { + fn call_mode_token_state(token: Address, balance: u64) -> InMemoryDB { call_mode_token_state_with_code(token, balance, bytes!("6000545f5260205ff3")) } /// As [`call_mode_token_state`], with an explicit `balanceOf` implementation. - fn call_mode_token_state_with_code( - token: Address, - balance: u64, - code: Bytes, - ) -> CacheDB { + fn call_mode_token_state_with_code(token: Address, balance: u64, code: Bytes) -> InMemoryDB { let mut db = CacheDB::new(EmptyDB::default()); let mut token_id_bytes = [0u8; 32]; token_id_bytes[31] = 1; @@ -497,20 +565,14 @@ pub(crate) mod tests { U256::from(1), // priceRatio ), ] { - db.insert_account_storage(L2_TOKEN_REGISTRY_ADDRESS, slot, value) - .unwrap(); + db.insert_account_storage(&L2_TOKEN_REGISTRY_ADDRESS, &slot, &value); } db.insert_account_info( - token, - AccountInfo { - code_hash: alloy_primitives::keccak256(code.as_ref()), - code: Some(Bytecode::new_raw(code)), - ..Default::default() - }, + &token, + AccountInfo::default().with_code(Bytecode::new_legacy(code)), ); - db.insert_account_storage(token, U256::ZERO, U256::from(balance)) - .unwrap(); + db.insert_account_storage(&token, &U256::ZERO, &U256::from(balance)); db } @@ -522,19 +584,18 @@ pub(crate) mod tests { // TIMESTAMP PUSH0 MSTORE PUSH1 0x20 PUSH0 RETURN — a `balanceOf` that reports the // block time, so an answer produced under the wrong environment is visible. - let mut db = call_mode_token_state_with_code(token, 0, bytes!("425f5260205ff3")); + let db = call_mode_token_state_with_code(token, 0, bytes!("425f5260205ff3")); let env = MorphEvmEnv::new( - revm::context::CfgEnv::new_with_spec(MorphHardfork::Emerald), - crate::MorphBlockEnv { - inner: revm::context::BlockEnv { - timestamp: U256::from(TIMESTAMP), - ..Default::default() - }, + MorphHardfork::Emerald, + MorphBlockEnv { + timestamp: U256::from(TIMESTAMP), + ..Default::default() }, + 1, ); - let info = TokenFeeInfo::load_for_caller(&mut db, 1, caller, &env) + let info = TokenFeeInfo::load_for_caller(&mut Plain(db), 1, caller, &env) .unwrap() .unwrap(); @@ -547,13 +608,10 @@ pub(crate) mod tests { fn balance_of_fallback_reports_a_failed_state_read_instead_of_a_zero_balance() { let token = address!("5300000000000000000000000000000000000042"); let caller = address!("0000000000000000000000000000000000000001"); - let env = MorphEvmEnv::new( - revm::context::CfgEnv::new_with_spec(MorphHardfork::Emerald), - crate::MorphBlockEnv::default(), - ); + let env = MorphEvmEnv::new(MorphHardfork::Emerald, MorphBlockEnv::default(), 1); // Readable state: the fallback reaches the token and reads the balance. - let mut readable = call_mode_token_state(token, 10_000_000); + let mut readable = Plain(call_mode_token_state(token, 10_000_000)); let info = TokenFeeInfo::load_for_caller(&mut readable, 1, caller, &env) .unwrap() .unwrap(); @@ -565,10 +623,8 @@ pub(crate) mod tests { inner: call_mode_token_state(token, 10_000_000), token, }; - assert_eq!( - TokenFeeInfo::load_for_caller(&mut unreadable, 1, caller, &env).unwrap_err(), - EVMError::Database(TokenReadFailure) - ); + let error = TokenFeeInfo::load_for_caller(&mut unreadable, 1, caller, &env).unwrap_err(); + assert!(is_token_read_failure(&error), "{error:?}"); } #[test] diff --git a/crates/revm/src/tx.rs b/crates/revm/src/tx.rs index bcf4afdb..529763ad 100644 --- a/crates/revm/src/tx.rs +++ b/crates/revm/src/tx.rs @@ -1,41 +1,66 @@ //! Morph transaction environment. //! -//! This module defines the Morph-specific transaction environment with token fee support. +//! This module defines the flat, execution-facing view of a Morph transaction: one shape for +//! every transaction type, with token-fee fields where they apply. use alloy_consensus::{ - EthereumTxEnvelope, SignableTransaction, Transaction as AlloyTransaction, TxEip4844, + SignableTransaction, Transaction as AlloyTransaction, transaction::Recovered, }; -use alloy_eips::eip2718::Encodable2718; -use alloy_eips::eip2930::AccessList; -use alloy_eips::eip7702::RecoveredAuthority; -use alloy_primitives::{Address, B256, Bytes, Signature, TxKind, U256}; +use alloy_eips::{ + Typed2718, + eip2718::{Encodable2718, WithEncoded}, + eip2930::AccessList, + eip7702::{RecoveredAuthorization, SignedAuthorization}, +}; +use alloy_primitives::{B256, Bytes, ChainId, Signature, TxKind, U256}; +use evm2::ethereum::LazyAuthorization; use morph_primitives::{ L1_TX_TYPE_ID, MORPH_TX_TYPE_ID, MorphTxEnvelope, TxMorph, transaction::morph_transaction::{MORPH_TX_VERSION_1, MORPH_TX_VERSION_2}, }; -use reth_evm::{FromRecoveredTx, FromTxWithEncoded, ToTxEnv, TransactionEnvMut}; -use revm::context::{Transaction, TxEnv}; -use revm::context_interface::transaction::{ - AccessListItem, RecoveredAuthorization, SignedAuthorization, -}; -use std::ops::{Deref, DerefMut}; +use reth_evm::{FromRecoveredTx, FromTxWithEncoded, TransactionEnvMut}; -/// Re-export Either for authorization list -use alloy_consensus::transaction::Either; +/// EIP-2718 type byte of a legacy transaction. +const LEGACY_TX_TYPE: u8 = 0x00; +/// EIP-2718 type byte of an EIP-2930 transaction. +const EIP2930_TX_TYPE: u8 = 0x01; /// Morph transaction environment with token fee support. /// -/// This wraps the standard [`TxEnv`] and adds Morph-specific fields for: -/// - L1 message detection (tx_type 0x7E) -/// - TxMorph with token-based gas payment (tx_type 0x7F) -/// - RLP encoded transaction bytes for L1 data fee calculation -/// - Version, reference, and memo fields for extended MorphTx functionality +/// The fields follow the semantics of the consensus transaction they were built from: +/// - [`Self::tx_type`] selects the handler (0x7E L1 message, 0x7F MorphTx, or a standard type) +/// - [`Self::rlp_bytes`] holds the encoded transaction for the L1 data fee calculation +/// - [`Self::version`], [`Self::fee_token_id`], [`Self::fee_limit`], [`Self::reference`] and +/// [`Self::memo`] carry the extended MorphTx fields +/// +/// The sender is not part of this type: execution receives it as +/// `Recovered`, alongside the signature-recovery result. /// /// Reference: #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct MorphTxEnv { - /// Inner transaction environment. - pub inner: TxEnv, + /// EIP-2718 transaction type byte. + pub tx_type: u8, + /// Gas limit. + pub gas_limit: u64, + /// Legacy gas price, or the maximum fee per gas for dynamic-fee transactions. + pub gas_price: u128, + /// Maximum priority fee per gas, when the transaction type has one. + pub gas_priority_fee: Option, + /// Call target or contract creation. + pub kind: TxKind, + /// Transferred value. + pub value: U256, + /// Call data or initcode. + pub data: Bytes, + /// Sender nonce. + pub nonce: u64, + /// Chain id, when the transaction commits to one. + pub chain_id: Option, + /// EIP-2930 access list. + pub access_list: AccessList, + /// EIP-7702 authorizations, with their authorities recovered where possible. + pub authorization_list: Vec, /// RLP encoded transaction bytes. /// Used only for L1 data fee calculation. pub rlp_bytes: Option, @@ -48,25 +73,12 @@ pub struct MorphTxEnv { pub fee_limit: Option, /// Reference key for the transaction. /// Used for indexing and looking up transactions by external systems. - pub reference: Option, + pub reference: Option, /// Memo field for arbitrary data. pub memo: Option, } impl MorphTxEnv { - /// Create a new Morph transaction environment from a standard TxEnv. - pub fn new(inner: TxEnv) -> Self { - Self { - inner, - rlp_bytes: None, - version: None, - fee_token_id: None, - fee_limit: None, - reference: None, - memo: None, - } - } - /// Create a new Morph transaction environment with RLP bytes. pub fn with_rlp_bytes(mut self, rlp_bytes: Bytes) -> Self { self.rlp_bytes = Some(rlp_bytes); @@ -92,7 +104,7 @@ impl MorphTxEnv { } /// Set the reference. - pub fn with_reference(mut self, reference: alloy_primitives::B256) -> Self { + pub fn with_reference(mut self, reference: B256) -> Self { self.reference = Some(reference); self } @@ -103,6 +115,21 @@ impl MorphTxEnv { self } + /// Effective gas price paid per unit of gas at `base_fee`. + /// + /// Legacy and EIP-2930 transactions pay their gas price; the rest pay + /// `min(max_fee, base_fee + priority_fee)`. + #[inline] + pub fn effective_gas_price_at(&self, base_fee: u128) -> u128 { + if matches!(self.tx_type, LEGACY_TX_TYPE | EIP2930_TX_TYPE) { + return self.gas_price; + } + match self.gas_priority_fee { + Some(tip) => self.gas_price.min(base_fee.saturating_add(tip)), + None => self.gas_price, + } + } + /// Encodes this tx env into EIP-2718 bytes for L1 fee accounting. /// /// Used by simulation paths (`eth_call`, `eth_estimateGas`) that have env @@ -142,7 +169,7 @@ impl MorphTxEnv { // If version is missing (e.g. from an older transaction type), fall back to // the smallest version that can represent the request so the L1 fee is not // underpriced: V2 when an authorization list is present, otherwise V1. - let fallback = if self.inner.authorization_list.is_empty() { + let fallback = if self.authorization_list.is_empty() { MORPH_TX_VERSION_1 } else { MORPH_TX_VERSION_2 @@ -167,15 +194,15 @@ impl MorphTxEnv { }; Some(TxMorph { - chain_id: self.chain_id().unwrap_or(fallback_chain_id), - nonce: self.inner.nonce, - gas_limit: self.gas_limit(), - max_fee_per_gas: self.max_fee_per_gas(), - max_priority_fee_per_gas: self.max_priority_fee_per_gas().unwrap_or_default(), - to: self.kind(), - value: self.value(), + chain_id: self.chain_id.unwrap_or(fallback_chain_id), + nonce: self.nonce, + gas_limit: self.gas_limit, + max_fee_per_gas: self.gas_price, + max_priority_fee_per_gas: self.gas_priority_fee.unwrap_or_default(), + to: self.kind, + value: self.value, access_list: self.access_list.clone(), - input: self.input().clone(), + input: self.data.clone(), fee_token_id: self.fee_token_id.unwrap_or_default(), fee_limit: self.fee_limit.unwrap_or_default(), version, @@ -198,31 +225,31 @@ impl MorphTxEnv { signature: Signature, ) -> MorphTxEnvelope { debug_assert!( - !self.is_l1_msg() && self.inner.blob_hashes.is_empty(), - "L1 messages and blob transactions should not use fallback L1 fee calculation" + !self.is_l1_msg(), + "L1 messages should not use fallback L1 fee calculation" ); - let chain_id = self.chain_id().unwrap_or(fallback_chain_id); + let chain_id = self.chain_id.unwrap_or(fallback_chain_id); // geth maps a legacy `gasPrice` onto both EIP-1559 caps (`ToMessage`). - let max_priority_fee_per_gas = self.max_priority_fee_per_gas().unwrap_or(self.gas_price()); + let max_priority_fee_per_gas = self.gas_priority_fee.unwrap_or(self.gas_price); // SetCodeTx cannot be a create (`ErrSetCodeTxCreate`); geth falls // through to DynamicFeeTx when `to` is missing or the auth list is empty. - if !self.inner.authorization_list.is_empty() - && let Some(to) = self.kind().to().copied() + if !self.authorization_list.is_empty() + && let TxKind::Call(to) = self.kind { return MorphTxEnvelope::Eip7702( alloy_consensus::TxEip7702 { chain_id, - nonce: self.inner.nonce, - gas_limit: self.gas_limit(), - max_fee_per_gas: self.max_fee_per_gas(), + nonce: self.nonce, + gas_limit: self.gas_limit, + max_fee_per_gas: self.gas_price, max_priority_fee_per_gas, to, - value: self.value(), + value: self.value, access_list: self.access_list.clone(), authorization_list: self.signed_authorizations_for_l1_fee(signature), - input: self.input().clone(), + input: self.data.clone(), } .into_signed(signature), ); @@ -231,299 +258,210 @@ impl MorphTxEnv { MorphTxEnvelope::Eip1559( alloy_consensus::TxEip1559 { chain_id, - nonce: self.inner.nonce, - gas_limit: self.gas_limit(), - max_fee_per_gas: self.max_fee_per_gas(), + nonce: self.nonce, + gas_limit: self.gas_limit, + max_fee_per_gas: self.gas_price, max_priority_fee_per_gas, - to: self.kind(), - value: self.value(), + to: self.kind, + value: self.value, access_list: self.access_list.clone(), - input: self.input().clone(), + input: self.data.clone(), } .into_signed(signature), ) } fn signed_authorizations_for_l1_fee(&self, placeholder: Signature) -> Vec { - self.inner - .authorization_list + self.authorization_list .iter() .map(|auth| match auth { - Either::Left(signed) => signed.clone(), + LazyAuthorization::Signed(signed) => signed.clone(), // Recovered authorizations no longer carry their original // signature, so reuse the fee-sizing placeholder. - Either::Right(recovered) => { + LazyAuthorization::Recovered(recovered) => { recovered.clone().into_parts().0.into_signed(placeholder) } }) .collect() } - /// Create a new Morph transaction environment from a recovered transaction. - /// - /// This method: - /// - Converts the transaction to `TxEnv` - /// - Extracts the RLP-encoded transaction bytes for L1 data fee calculation - /// - Extracts fee_token_id for TxMorph (type 0x7F) - pub fn from_recovered_tx(tx: &MorphTxEnvelope, signer: Address) -> Self { - // Encode the transaction to RLP bytes for L1 data fee calculation - let rlp_bytes = tx.encoded_2718(); - Self::from_tx_with_rlp_bytes(tx, signer, Bytes::from(rlp_bytes)) + /// Builds the environment for `tx`, encoding it for the L1 data fee calculation. + pub fn from_envelope(tx: &MorphTxEnvelope) -> Self { + Self::from_envelope_with_rlp(tx, Bytes::from(tx.encoded_2718())) } - /// Create a new Morph transaction environment from a transaction with pre-encoded RLP bytes. + /// Builds the environment for `tx` from already encoded EIP-2718 bytes. /// - /// This is the core implementation used by both `from_recovered_tx` and `FromTxWithEncoded`. - fn from_tx_with_rlp_bytes(tx: &MorphTxEnvelope, signer: Address, rlp_bytes: Bytes) -> Self { - let tx_type: u8 = tx.tx_type().into(); - - // Extract MorphTx fields directly from the typed envelope — avoids an - // unnecessary encode→decode RLP roundtrip that the old helper performed. - let morph_tx_info = match tx { - MorphTxEnvelope::Morph(signed) => { - let morph = signed.tx(); - Some(DecodedMorphTxFields { - version: morph.version, - fee_token_id: morph.fee_token_id, - fee_limit: morph.fee_limit, - reference: morph.reference, - memo: morph.memo.clone(), - }) - } - _ => None, - }; - - // Build TxEnv from the transaction - let inner = TxEnv { - tx_type, - caller: signer, + /// This is the core implementation used by both the `FromRecoveredTx` and + /// `FromTxWithEncoded` conversions. + fn from_envelope_with_rlp(tx: &MorphTxEnvelope, rlp_bytes: Bytes) -> Self { + let mut env = Self { + tx_type: tx.tx_type().into(), gas_limit: AlloyTransaction::gas_limit(tx), gas_price: tx.effective_gas_price(None), + gas_priority_fee: AlloyTransaction::max_priority_fee_per_gas(tx), kind: AlloyTransaction::kind(tx), value: AlloyTransaction::value(tx), data: AlloyTransaction::input(tx).clone(), nonce: AlloyTransaction::nonce(tx), chain_id: AlloyTransaction::chain_id(tx), access_list: tx.access_list().cloned().unwrap_or_default(), - gas_priority_fee: AlloyTransaction::max_priority_fee_per_gas(tx), - blob_hashes: tx - .blob_versioned_hashes() - .map(|h| h.to_vec()) - .unwrap_or_default(), - max_fee_per_blob_gas: AlloyTransaction::max_fee_per_blob_gas(tx).unwrap_or(0), authorization_list: tx .authorization_list() .unwrap_or_default() .iter() .map(|auth| { - let authority = auth - .recover_authority() - .map_or(RecoveredAuthority::Invalid, RecoveredAuthority::Valid); - Either::Right(RecoveredAuthorization::new_unchecked( + LazyAuthorization::Recovered(RecoveredAuthorization::new_unchecked( auth.inner().clone(), - authority, + auth.recover_authority().map_or( + alloy_eips::eip7702::RecoveredAuthority::Invalid, + alloy_eips::eip7702::RecoveredAuthority::Valid, + ), )) }) .collect(), + rlp_bytes: Some(rlp_bytes), + ..Default::default() }; - // Use builder pattern to set Morph-specific fields - let mut env = Self::new(inner).with_rlp_bytes(rlp_bytes); - if let Some(info) = morph_tx_info { - env = env.with_version(info.version); - env = env.with_fee_token_id(info.fee_token_id); - env = env.with_fee_limit(info.fee_limit); - if let Some(reference) = info.reference { - env = env.with_reference(reference); - } - if let Some(memo) = info.memo - && !memo.is_empty() - { - env = env.with_memo(memo); - } + if let MorphTxEnvelope::Morph(signed) = tx { + let morph = signed.tx(); + env.version = Some(morph.version); + env.fee_token_id = Some(morph.fee_token_id); + env.fee_limit = Some(morph.fee_limit); + env.reference = morph.reference; + env.memo = morph.memo.clone().filter(|memo| !memo.is_empty()); } env } } -/// Extracted MorphTx fields from RLP-encoded bytes. -struct DecodedMorphTxFields { - version: u8, - fee_token_id: u16, - fee_limit: U256, - reference: Option, - memo: Option, -} - -impl Deref for MorphTxEnv { - type Target = TxEnv; - - fn deref(&self) -> &Self::Target { - &self.inner - } -} - -impl DerefMut for MorphTxEnv { - fn deref_mut(&mut self) -> &mut Self::Target { - &mut self.inner - } -} - -impl From for MorphTxEnv { - fn from(inner: TxEnv) -> Self { - Self::new(inner) - } -} - -impl From for TxEnv { - fn from(morph_tx: MorphTxEnv) -> Self { - morph_tx.inner - } -} - -// Implement ToTxEnv for MorphTxEnv (identity conversion) -impl ToTxEnv for MorphTxEnv { - fn to_tx_env(&self) -> Self { - self.clone() - } -} - -// Implement FromRecoveredTx for MorphTxEnv -impl FromRecoveredTx for MorphTxEnv { - fn from_recovered_tx(tx: &MorphTxEnvelope, sender: Address) -> Self { - Self::from_recovered_tx(tx, sender) - } -} - -impl FromRecoveredTx> for MorphTxEnv { - fn from_recovered_tx(tx: &EthereumTxEnvelope, sender: Address) -> Self { - TxEnv::from_recovered_tx(tx, sender).into() +impl Typed2718 for MorphTxEnv { + #[inline] + fn ty(&self) -> u8 { + self.tx_type } } -impl FromTxWithEncoded> for MorphTxEnv { - fn from_encoded_tx( - tx: &EthereumTxEnvelope, - sender: Address, - _encoded: Bytes, - ) -> Self { - >>::from_recovered_tx(tx, sender) +impl AlloyTransaction for MorphTxEnv { + #[inline] + fn chain_id(&self) -> Option { + self.chain_id } -} -// Implement FromTxWithEncoded for MorphTxEnv -impl FromTxWithEncoded for MorphTxEnv { - fn from_encoded_tx(tx: &MorphTxEnvelope, sender: Address, encoded: Bytes) -> Self { - Self::from_tx_with_rlp_bytes(tx, sender, encoded) + #[inline] + fn nonce(&self) -> u64 { + self.nonce } -} -impl TransactionEnvMut for MorphTxEnv { - fn set_gas_limit(&mut self, gas_limit: u64) { - self.inner.gas_limit = gas_limit; + #[inline] + fn gas_limit(&self) -> u64 { + self.gas_limit } - fn set_nonce(&mut self, nonce: u64) { - self.inner.nonce = nonce; + #[inline] + fn gas_price(&self) -> Option { + (!self.is_dynamic_fee()).then_some(self.gas_price) } - fn set_access_list(&mut self, access_list: AccessList) { - // Delegate so the upstream Legacy → Eip2930 tx_type upgrade applies. - // L1 fee encoding does not read that type byte; the access list still - // lands on the EIP-1559 envelope used for simulation fee sizing. - self.inner.set_access_list(access_list); + #[inline] + fn max_fee_per_gas(&self) -> u128 { + self.gas_price } -} - -// Implement the Transaction trait for MorphTxEnv by delegating to inner TxEnv -impl Transaction for MorphTxEnv { - type AccessListItem<'a> - = &'a AccessListItem - where - Self: 'a; - type Authorization<'a> - = &'a Either - where - Self: 'a; #[inline] - fn tx_type(&self) -> u8 { - self.inner.tx_type + fn max_priority_fee_per_gas(&self) -> Option { + self.gas_priority_fee } #[inline] - fn kind(&self) -> TxKind { - self.inner.kind + fn max_fee_per_blob_gas(&self) -> Option { + None } #[inline] - fn caller(&self) -> Address { - self.inner.caller + fn priority_fee_or_price(&self) -> u128 { + self.gas_priority_fee.unwrap_or(self.gas_price) } #[inline] - fn gas_limit(&self) -> u64 { - self.inner.gas_limit + fn effective_gas_price(&self, base_fee: Option) -> u128 { + match base_fee { + Some(base_fee) => self.effective_gas_price_at(base_fee as u128), + None => self.gas_price, + } } #[inline] - fn gas_price(&self) -> u128 { - self.inner.gas_price + fn is_dynamic_fee(&self) -> bool { + !matches!(self.tx_type, LEGACY_TX_TYPE | EIP2930_TX_TYPE) } #[inline] - fn value(&self) -> U256 { - self.inner.value + fn kind(&self) -> TxKind { + self.kind } #[inline] - fn nonce(&self) -> u64 { - self.inner.nonce + fn is_create(&self) -> bool { + self.kind.is_create() } #[inline] - fn chain_id(&self) -> Option { - self.inner.chain_id + fn value(&self) -> U256 { + self.value } #[inline] - fn access_list(&self) -> Option>> { - Some(self.inner.access_list.0.iter()) + fn input(&self) -> &Bytes { + &self.data } #[inline] - fn max_fee_per_gas(&self) -> u128 { - self.inner.gas_price + fn access_list(&self) -> Option<&AccessList> { + Some(&self.access_list) } #[inline] - fn max_fee_per_blob_gas(&self) -> u128 { - self.inner.max_fee_per_blob_gas + fn blob_versioned_hashes(&self) -> Option<&[B256]> { + None } + /// Always `None`: the environment stores authorizations in their execution form + /// ([`MorphTxEnv::authorization_list`]), which keeps recovered authorities rather than the + /// signed tuples this accessor would have to return. #[inline] - fn authorization_list_len(&self) -> usize { - self.inner.authorization_list.len() + fn authorization_list(&self) -> Option<&[SignedAuthorization]> { + None } +} - #[inline] - fn authorization_list(&self) -> impl Iterator> { - self.inner.authorization_list.iter() +impl FromRecoveredTx for MorphTxEnv { + fn from_recovered_tx(tx: Recovered) -> Self { + Self::from_envelope(tx.inner()) } +} - #[inline] - fn input(&self) -> &Bytes { - &self.inner.data +impl FromTxWithEncoded for MorphTxEnv { + fn from_tx_with_encoded(tx: WithEncoded>) -> Self { + let (encoded, recovered) = tx.split(); + Self::from_envelope_with_rlp(recovered.inner(), encoded) } +} - #[inline] - fn blob_versioned_hashes(&self) -> &[B256] { - &self.inner.blob_hashes +impl TransactionEnvMut for MorphTxEnv { + fn set_gas_limit(&mut self, gas_limit: u64) { + self.gas_limit = gas_limit; } - #[inline] - fn max_priority_fee_per_gas(&self) -> Option { - self.inner.gas_priority_fee + fn set_access_list(&mut self, access_list: AccessList) { + // An access list on a legacy request makes it EIP-2930. L1 fee encoding does not + // read that type byte; the access list still lands on the EIP-1559 envelope used + // for simulation fee sizing. + self.access_list = access_list; + if self.tx_type == LEGACY_TX_TYPE { + self.tx_type = EIP2930_TX_TYPE; + } } } @@ -550,12 +488,12 @@ pub trait MorphTxExt { impl MorphTxExt for MorphTxEnv { #[inline] fn is_l1_msg(&self) -> bool { - self.inner.tx_type == L1_TX_TYPE_ID + self.tx_type == L1_TX_TYPE_ID } #[inline] fn is_morph_tx(&self) -> bool { - self.inner.tx_type == MORPH_TX_TYPE_ID + self.tx_type == MORPH_TX_TYPE_ID } #[inline] @@ -569,28 +507,24 @@ impl MorphTxExt for MorphTxEnv { } } -impl MorphTxExt for TxEnv { - #[inline] - fn is_l1_msg(&self) -> bool { - self.tx_type == L1_TX_TYPE_ID - } - - #[inline] - fn is_morph_tx(&self) -> bool { - self.tx_type == MORPH_TX_TYPE_ID - } -} - #[cfg(test)] mod tests { use super::*; - use alloy_eips::eip2718::Decodable2718; - use revm::context_interface::transaction::TransactionType; + use alloy_eips::{ + eip2718::Decodable2718, + eip7702::{Authorization, RecoveredAuthority}, + }; + use alloy_primitives::Address; + + const EIP1559_TX_TYPE: u8 = 0x02; + const EIP7702_TX_TYPE: u8 = 0x04; #[test] fn test_l1_msg_detection() { - let mut tx = MorphTxEnv::default(); - tx.inner.tx_type = L1_TX_TYPE_ID; + let tx = MorphTxEnv { + tx_type: L1_TX_TYPE_ID, + ..Default::default() + }; assert!(tx.is_l1_msg()); assert!(!tx.is_morph_tx()); @@ -600,44 +534,43 @@ mod tests { #[test] fn test_morph_tx_detection() { - let mut tx = MorphTxEnv::default(); - tx.inner.tx_type = MORPH_TX_TYPE_ID; + let tx = MorphTxEnv { + tx_type: MORPH_TX_TYPE_ID, + ..Default::default() + }; assert!(tx.is_morph_tx()); assert!(!tx.is_l1_msg()); } #[test] - fn test_txenv_morph_tx_detection() { - let tx = TxEnv { + fn typed_2718_reports_the_type_byte() { + let tx = MorphTxEnv { tx_type: MORPH_TX_TYPE_ID, ..Default::default() }; - assert!(tx.is_morph_tx()); - - let regular_tx = TxEnv::default(); - assert!(!regular_tx.is_morph_tx()); + assert_eq!(tx.ty(), MORPH_TX_TYPE_ID); } #[test] - fn test_deref() { - let tx = MorphTxEnv { - inner: TxEnv { - gas_limit: 21000, - ..Default::default() - }, + fn effective_gas_price_uses_the_transaction_fee_model() { + let legacy = MorphTxEnv { + gas_price: 10, ..Default::default() }; - assert_eq!(tx.gas_limit, 21000); - assert_eq!(tx.inner.gas_limit, 21000); - } + assert_eq!(legacy.effective_gas_price_at(1), 10); - #[test] - fn test_transaction_trait() { - let tx = MorphTxEnv::default(); - // Test that Transaction trait methods work - assert_eq!(Transaction::gas_limit(&tx), tx.inner.gas_limit); - assert_eq!(Transaction::caller(&tx), tx.inner.caller); - assert_eq!(Transaction::value(&tx), tx.inner.value); + let dynamic = MorphTxEnv { + tx_type: EIP1559_TX_TYPE, + gas_price: 10, + gas_priority_fee: Some(2), + ..Default::default() + }; + assert_eq!(dynamic.effective_gas_price_at(1), 3); + assert_eq!( + dynamic.effective_gas_price_at(100), + 10, + "capped by the max fee" + ); } #[test] @@ -652,14 +585,11 @@ mod tests { #[test] fn test_encode_for_l1_fee_legacy() { let tx = MorphTxEnv { - inner: TxEnv { - chain_id: Some(53077), - gas_limit: 21_000, - gas_price: 1, - nonce: 1, - kind: TxKind::Call(Address::ZERO), - ..Default::default() - }, + chain_id: Some(53077), + gas_limit: 21_000, + gas_price: 1, + nonce: 1, + kind: TxKind::Call(Address::ZERO), ..Default::default() }; let encoded = tx.encode_for_l1_fee(53077); @@ -673,14 +603,11 @@ mod tests { #[test] fn encode_for_l1_fee_uses_go_ethereum_placeholder_signature_shape() { let tx = MorphTxEnv { - inner: TxEnv { - chain_id: Some(53077), - gas_limit: 21_000, - gas_price: 1, - nonce: 1, - kind: TxKind::Call(Address::ZERO), - ..Default::default() - }, + chain_id: Some(53077), + gas_limit: 21_000, + gas_price: 1, + nonce: 1, + kind: TxKind::Call(Address::ZERO), ..Default::default() }; let encoded = tx.encode_for_l1_fee(53077); @@ -698,22 +625,19 @@ mod tests { #[test] fn encode_for_l1_fee_dynamic_matches_go_ethereum_bytes() { let tx = MorphTxEnv { - inner: TxEnv { - tx_type: TransactionType::Eip1559.into(), - chain_id: Some(1), - gas_limit: 8_000_000, - gas_price: 16, - gas_priority_fee: Some(16), - nonce: 0, - kind: TxKind::Call(Address::with_last_byte(0xf1)), - data: Bytes::from_static(&[ - 0x22, 0xcf, 0xae, 0xfc, 0x92, 0xe4, 0xed, 0xb9, 0xb0, 0xae, 0x01, 0xa6, 0x3a, - 0x95, 0xdf, 0x11, 0xf1, 0x27, 0x9b, 0x7b, 0x6b, 0xdd, 0xe4, 0xe0, 0x48, 0xf6, - 0xec, 0xe8, 0xf8, 0xc8, 0xf2, 0xc2, 0xde, 0x97, 0x54, 0x4a, 0x16, 0x3f, 0x7d, - 0x30, 0x23, 0x15, 0xee, 0x0f, 0x78, 0x69, 0xfb, 0xdc, 0xfd, 0x86, - ]), - ..Default::default() - }, + tx_type: EIP1559_TX_TYPE, + chain_id: Some(1), + gas_limit: 8_000_000, + gas_price: 16, + gas_priority_fee: Some(16), + nonce: 0, + kind: TxKind::Call(Address::with_last_byte(0xf1)), + data: Bytes::from_static(&[ + 0x22, 0xcf, 0xae, 0xfc, 0x92, 0xe4, 0xed, 0xb9, 0xb0, 0xae, 0x01, 0xa6, 0x3a, 0x95, + 0xdf, 0x11, 0xf1, 0x27, 0x9b, 0x7b, 0x6b, 0xdd, 0xe4, 0xe0, 0x48, 0xf6, 0xec, 0xe8, + 0xf8, 0xc8, 0xf2, 0xc2, 0xde, 0x97, 0x54, 0x4a, 0x16, 0x3f, 0x7d, 0x30, 0x23, 0x15, + 0xee, 0x0f, 0x78, 0x69, 0xfb, 0xdc, 0xfd, 0x86, + ]), ..Default::default() }; @@ -726,15 +650,12 @@ mod tests { #[test] fn encode_for_l1_fee_sizes_eip2930_request_as_eip1559_like_geth() { let tx = MorphTxEnv { - inner: TxEnv { - tx_type: TransactionType::Eip2930.into(), - chain_id: Some(53077), - gas_limit: 21_000, - gas_price: 1, - nonce: 1, - kind: TxKind::Call(Address::ZERO), - ..Default::default() - }, + tx_type: EIP2930_TX_TYPE, + chain_id: Some(53077), + gas_limit: 21_000, + gas_price: 1, + nonce: 1, + kind: TxKind::Call(Address::ZERO), ..Default::default() }; @@ -756,12 +677,9 @@ mod tests { ( "no fee fields", MorphTxEnv { - inner: TxEnv { - chain_id: Some(2818), - gas_limit: 21_000, - kind: TxKind::Call(Address::ZERO), - ..Default::default() - }, + chain_id: Some(2818), + gas_limit: 21_000, + kind: TxKind::Call(Address::ZERO), ..Default::default() }, 103, @@ -769,13 +687,10 @@ mod tests { ( "gasPrice only", MorphTxEnv { - inner: TxEnv { - chain_id: Some(2818), - gas_limit: 21_000, - gas_price: 1_000_000_000, - kind: TxKind::Call(Address::ZERO), - ..Default::default() - }, + chain_id: Some(2818), + gas_limit: 21_000, + gas_price: 1_000_000_000, + kind: TxKind::Call(Address::ZERO), ..Default::default() }, 111, @@ -783,14 +698,11 @@ mod tests { ( "gasPrice + empty access list", MorphTxEnv { - inner: TxEnv { - tx_type: TransactionType::Eip2930.into(), - chain_id: Some(2818), - gas_limit: 21_000, - gas_price: 1_000_000_000, - kind: TxKind::Call(Address::ZERO), - ..Default::default() - }, + tx_type: EIP2930_TX_TYPE, + chain_id: Some(2818), + gas_limit: 21_000, + gas_price: 1_000_000_000, + kind: TxKind::Call(Address::ZERO), ..Default::default() }, 111, @@ -815,17 +727,14 @@ mod tests { #[test] fn encode_for_l1_fee_empty_authorization_list_stays_eip1559() { let tx = MorphTxEnv { - inner: TxEnv { - tx_type: TransactionType::Eip7702.into(), - chain_id: Some(53077), - gas_limit: 100_000, - gas_price: 20_000_000_000, - gas_priority_fee: Some(1_000_000_000), - nonce: 1, - kind: TxKind::Call(Address::with_last_byte(0xf1)), - authorization_list: vec![], - ..Default::default() - }, + tx_type: EIP7702_TX_TYPE, + chain_id: Some(53077), + gas_limit: 100_000, + gas_price: 20_000_000_000, + gas_priority_fee: Some(1_000_000_000), + nonce: 1, + kind: TxKind::Call(Address::with_last_byte(0xf1)), + authorization_list: vec![], ..Default::default() }; @@ -839,25 +748,15 @@ mod tests { #[test] fn encode_for_l1_fee_authorization_list_without_to_stays_eip1559() { - let authorization = alloy_eips::eip7702::Authorization { - chain_id: U256::from(53077), - address: Address::with_last_byte(0x42), - nonce: 7, - }; - let signed_authorization = - authorization.into_signed(Signature::new(U256::from(1), U256::from(2), true)); let tx = MorphTxEnv { - inner: TxEnv { - tx_type: TransactionType::Eip7702.into(), - chain_id: Some(53077), - gas_limit: 100_000, - gas_price: 20_000_000_000, - gas_priority_fee: Some(1_000_000_000), - nonce: 1, - kind: TxKind::Create, - authorization_list: vec![Either::Left(signed_authorization)], - ..Default::default() - }, + tx_type: EIP7702_TX_TYPE, + chain_id: Some(53077), + gas_limit: 100_000, + gas_price: 20_000_000_000, + gas_priority_fee: Some(1_000_000_000), + nonce: 1, + kind: TxKind::Create, + authorization_list: vec![LazyAuthorization::Signed(sample_signed_authorization())], ..Default::default() }; @@ -871,25 +770,16 @@ mod tests { #[test] fn encode_for_l1_fee_preserves_eip7702_authorization_list() { - let authorization = alloy_eips::eip7702::Authorization { - chain_id: U256::from(53077), - address: Address::with_last_byte(0x42), - nonce: 7, - }; - let signed_authorization = - authorization.into_signed(Signature::new(U256::from(1), U256::from(2), true)); + let signed_authorization = sample_signed_authorization(); let tx = MorphTxEnv { - inner: TxEnv { - tx_type: TransactionType::Eip7702.into(), - chain_id: Some(53077), - gas_limit: 100_000, - gas_price: 20_000_000_000, - gas_priority_fee: Some(1_000_000_000), - nonce: 1, - kind: TxKind::Call(Address::with_last_byte(0xf1)), - authorization_list: vec![Either::Left(signed_authorization.clone())], - ..Default::default() - }, + tx_type: EIP7702_TX_TYPE, + chain_id: Some(53077), + gas_limit: 100_000, + gas_price: 20_000_000_000, + gas_priority_fee: Some(1_000_000_000), + nonce: 1, + kind: TxKind::Call(Address::with_last_byte(0xf1)), + authorization_list: vec![LazyAuthorization::Signed(signed_authorization.clone())], ..Default::default() }; @@ -907,21 +797,18 @@ mod tests { fn set_access_list_upgrades_legacy_tx_type_like_upstream() { let mut tx = MorphTxEnv::default(); tx.set_access_list(AccessList::default()); - assert_eq!(tx.inner.tx_type, u8::from(TransactionType::Eip2930)); + assert_eq!(tx.tx_type, EIP2930_TX_TYPE); } #[test] fn test_encode_for_l1_fee_morph_tx() { let tx = MorphTxEnv { - inner: TxEnv { - tx_type: MORPH_TX_TYPE_ID, - chain_id: Some(53077), - gas_limit: 21_000, - gas_price: 1, - nonce: 1, - kind: TxKind::Call(Address::ZERO), - ..Default::default() - }, + tx_type: MORPH_TX_TYPE_ID, + chain_id: Some(53077), + gas_limit: 21_000, + gas_price: 1, + nonce: 1, + kind: TxKind::Call(Address::ZERO), fee_token_id: Some(1), fee_limit: Some(U256::from(1000)), ..Default::default() @@ -930,7 +817,7 @@ mod tests { } fn sample_signed_authorization() -> SignedAuthorization { - alloy_eips::eip7702::Authorization { + Authorization { chain_id: U256::from(53077), address: Address::with_last_byte(0x42), nonce: 7, @@ -938,22 +825,16 @@ mod tests { .into_signed(Signature::new(U256::from(1), U256::from(2), true)) } - fn morph_v2_tx_env( - version: Option, - authorization: Either, - ) -> MorphTxEnv { + fn morph_v2_tx_env(version: Option, authorization: LazyAuthorization) -> MorphTxEnv { MorphTxEnv { - inner: TxEnv { - tx_type: MORPH_TX_TYPE_ID, - chain_id: Some(53077), - gas_limit: 100_000, - gas_price: 20_000_000_000, - gas_priority_fee: Some(1_000_000_000), - nonce: 1, - kind: TxKind::Call(Address::with_last_byte(0xf1)), - authorization_list: vec![authorization], - ..Default::default() - }, + tx_type: MORPH_TX_TYPE_ID, + chain_id: Some(53077), + gas_limit: 100_000, + gas_price: 20_000_000_000, + gas_priority_fee: Some(1_000_000_000), + nonce: 1, + kind: TxKind::Call(Address::with_last_byte(0xf1)), + authorization_list: vec![authorization], version, fee_token_id: Some(1), fee_limit: Some(U256::from(1000)), @@ -969,7 +850,7 @@ mod tests { let signed_authorization = sample_signed_authorization(); let tx = morph_v2_tx_env( Some(MORPH_TX_VERSION_2), - Either::Left(signed_authorization.clone()), + LazyAuthorization::Signed(signed_authorization.clone()), ); let encoded = tx.encode_for_l1_fee(53077); @@ -987,10 +868,7 @@ mod tests { // Sanity: the list actually contributes bytes versus the V1 shape. let v1 = MorphTxEnv { version: Some(MORPH_TX_VERSION_1), - inner: TxEnv { - authorization_list: vec![], - ..tx.inner.clone() - }, + authorization_list: vec![], ..tx }; assert!(encoded.len() > v1.encode_for_l1_fee(53077).len()); @@ -998,7 +876,10 @@ mod tests { #[test] fn encode_for_l1_fee_morph_tx_version_fallback_picks_v2_with_authorizations() { - let tx = morph_v2_tx_env(None, Either::Left(sample_signed_authorization())); + let tx = morph_v2_tx_env( + None, + LazyAuthorization::Signed(sample_signed_authorization()), + ); let encoded = tx.encode_for_l1_fee(53077); let decoded = MorphTxEnvelope::decode_2718(&mut encoded.as_ref()).unwrap(); @@ -1010,10 +891,7 @@ mod tests { // Without a list the fallback stays V1. let no_list = MorphTxEnv { - inner: TxEnv { - authorization_list: vec![], - ..tx.inner.clone() - }, + authorization_list: vec![], ..tx }; let encoded = no_list.encode_for_l1_fee(53077); @@ -1023,14 +901,17 @@ mod tests { #[test] fn encode_for_l1_fee_morph_tx_v2_recovered_authorization_uses_placeholder_signature() { let recovered = RecoveredAuthorization::new_unchecked( - alloy_eips::eip7702::Authorization { + Authorization { chain_id: U256::from(53077), address: Address::with_last_byte(0x42), nonce: 7, }, RecoveredAuthority::Valid(Address::with_last_byte(0x99)), ); - let tx = morph_v2_tx_env(Some(MORPH_TX_VERSION_2), Either::Right(recovered)); + let tx = morph_v2_tx_env( + Some(MORPH_TX_VERSION_2), + LazyAuthorization::Recovered(recovered), + ); let encoded = tx.encode_for_l1_fee(53077); let decoded = MorphTxEnvelope::decode_2718(&mut encoded.as_ref()).unwrap(); @@ -1073,12 +954,12 @@ mod tests { B256::ZERO, )); - let env = MorphTxEnv::from_recovered_tx(&envelope, Address::with_last_byte(0x01)); + let env = MorphTxEnv::from_envelope(&envelope); assert_eq!(env.version, Some(MORPH_TX_VERSION_2)); - assert_eq!(env.inner.tx_type, MORPH_TX_TYPE_ID); - assert_eq!(env.inner.authorization_list.len(), 1); - match &env.inner.authorization_list[0] { - Either::Right(recovered) => { + assert_eq!(env.tx_type, MORPH_TX_TYPE_ID); + assert_eq!(env.authorization_list.len(), 1); + match &env.authorization_list[0] { + LazyAuthorization::Recovered(recovered) => { let (authorization, _authority) = recovered.clone().into_parts(); assert_eq!(&authorization, signed_authorization.inner()); } diff --git a/crates/rpc/Cargo.toml b/crates/rpc/Cargo.toml index b729f42c..fc3703e5 100644 --- a/crates/rpc/Cargo.toml +++ b/crates/rpc/Cargo.toml @@ -14,7 +14,7 @@ workspace = true morph-primitives = { workspace = true, features = ["serde-bincode-compat", "reth-codec"] } morph-chainspec.workspace = true morph-reference-index.workspace = true -morph-revm = { workspace = true, features = ["rpc"] } +morph-revm.workspace = true morph-evm = { workspace = true, features = ["rpc"] } morph-proofs.workspace = true diff --git a/crates/rpc/src/error.rs b/crates/rpc/src/error.rs index 63cac662..f2be3be1 100644 --- a/crates/rpc/src/error.rs +++ b/crates/rpc/src/error.rs @@ -1,10 +1,9 @@ //! Error types for Morph RPC use alloy_primitives::B256; -use morph_evm::MorphEvmConfig; +use evm2::interpreter::InstrStop; use reth_errors::ProviderError; -use reth_evm::revm::context::result::EVMError; -use reth_evm::{HaltReasonFor, InvalidTxError}; +use reth_evm::BlockExecutionError; use reth_rpc_convert::TransactionConversionError; use reth_rpc_eth_types::{ EthApiError, @@ -90,9 +89,6 @@ pub enum MorphEthApiError { impl MorphEthApiError { /// JSON-RPC error code reported for [`Self::StateNotAvailable`]. - /// - /// Exposed so other error types that mean the same thing to a client can report it without - /// duplicating the literal. Used by the historical-proof window errors in [`crate::state`]. pub const STATE_NOT_AVAILABLE_CODE: i32 = -32005; } @@ -172,8 +168,8 @@ impl AsEthApiError for MorphEthApiError { // We get it for free since we have `#[from] EthApiError` above. /// Converts EVM halt reasons to [`MorphEthApiError`]. -impl FromEvmHalt> for MorphEthApiError { - fn from_evm_halt(halt: HaltReasonFor, gas_limit: u64) -> Self { +impl FromEvmHalt for MorphEthApiError { + fn from_evm_halt(halt: InstrStop, gas_limit: u64) -> Self { Self::Eth(EthApiError::from_evm_halt(halt, gas_limit)) } } @@ -192,13 +188,12 @@ impl From for MorphEthApiError { } } -/// Converts [`EVMError`] to [`MorphEthApiError`]. -impl From> for MorphEthApiError -where - T: Into, - TxError: InvalidTxError, -{ - fn from(err: EVMError) -> Self { +/// Converts [`BlockExecutionError`] to [`MorphEthApiError`]. +/// +/// Standard rejections keep their Ethereum JSON-RPC error; Morph's own are reported with their +/// message as a rejected transaction. +impl From for MorphEthApiError { + fn from(err: BlockExecutionError) -> Self { Self::Eth(err.into()) } } diff --git a/crates/rpc/src/eth/call.rs b/crates/rpc/src/eth/call.rs index a1718bbf..236edeeb 100644 --- a/crates/rpc/src/eth/call.rs +++ b/crates/rpc/src/eth/call.rs @@ -3,23 +3,22 @@ //! [`Call::caller_gas_allowance`] is overridden so `eth_estimateGas` caps //! gas by `balance − value − l1_fee` (ETH path) or the fee token balance //! (MorphTx `fee_token_id > 0`). `eth_call` and `eth_createAccessList` -//! are detected via `cfg_env.disable_block_gas_limit = true` and fall -//! through to the upstream allowance without the L1-fee extension. +//! are detected by the block gas limit check being disabled and keep the +//! plain ETH allowance, without the L1-fee extension. use crate::MorphEthApiError; use crate::eth::{MorphEthApi, MorphNodeCore}; -use alloy_evm::call::{CallError, caller_gas_allowance as upstream_caller_gas_allowance}; use alloy_primitives::U256; +use evm2::EvmFeatures; use morph_chainspec::{MorphChainSpec, MorphHardforks}; use morph_revm::{L1BlockInfo, MorphTxExt, TokenFeeInfo}; -use reth_evm::{EvmEnvFor, TxEnvFor}; +use reth_evm::{Database, EvmEnv, EvmEnvFor, TxEnvFor}; use reth_provider::ChainSpecProvider; use reth_rpc_eth_api::{ EthApiTypes, RpcNodeCore, helpers::{Call, EthCall, estimate::EstimateCall}, }; use reth_rpc_eth_types::EthApiError; -use revm::{Database, context::Transaction as RevmTransaction}; impl EthCall for MorphEthApi where @@ -74,14 +73,22 @@ where // eth_call / eth_createAccessList: no L1-fee cap. Token-fee callers // can have zero ETH, so defer to the handler instead of the // upstream ETH allowance. - if evm_env.cfg_env.disable_block_gas_limit { + if !evm_env + .version() + .feature(EvmFeatures::BLOCK_GAS_LIMIT_CHECK) + { if tx_env.fee_token_id.is_some_and(|id| id > 0) { return Ok(u64::MAX); } - return upstream_caller_gas_allowance(&mut db, tx_env).map_err(|e| match e { - CallError::Database(db_err) => MorphEthApiError::Eth(db_err.into()), - CallError::InsufficientFunds(_) => MorphEthApiError::InsufficientFundsForTransfer, - }); + let balance = db + .get_account(&tx_env.signer()) + .map_err(|e| MorphEthApiError::Eth(e.into()))? + .map(|account| account.balance) + .unwrap_or_default(); + let available = balance + .checked_sub(tx_env.value) + .ok_or(MorphEthApiError::InsufficientFundsForTransfer)?; + return Ok(gas_allowance_from_balance(available, tx_env.gas_price)); } // eth_estimateGas path. @@ -90,12 +97,12 @@ where if let Some(fee_token_id) = tx_env.fee_token_id.filter(|id| *id > 0) { return self.caller_gas_allowance_with_token( &mut db, - tx_env.caller(), - tx_env.value(), + tx_env.signer(), + tx_env.value, l1_fee, fee_token_id, tx_env.fee_limit, - tx_env.gas_price(), + tx_env.gas_price, ); } @@ -103,12 +110,12 @@ where // precision so the remainder is not lost across the two // subtractions. let balance = db - .basic(tx_env.caller()) + .get_account(&tx_env.signer()) .map_err(|e| MorphEthApiError::Eth(e.into()))? .map(|acc| acc.balance) .unwrap_or_default(); let available = balance - .checked_sub(tx_env.value()) + .checked_sub(tx_env.value) .ok_or(MorphEthApiError::InsufficientFundsForTransfer)?; // Reject at `l1_fee >= available` so the RPC surfaces the real // reason rather than a downstream "gas required exceeds allowance 0". @@ -117,7 +124,7 @@ where } Ok(gas_allowance_from_balance( available - l1_fee, - tx_env.gas_price(), + tx_env.gas_price, )) } } @@ -144,9 +151,9 @@ where return Ok(U256::ZERO); } - let block_number = u64::try_from(evm_env.block_env.inner.number) + let block_number = u64::try_from(evm_env.block_env().number) .map_err(|_| EthApiError::InvalidParams("invalid block number".to_string()))?; - let timestamp = u64::try_from(evm_env.block_env.inner.timestamp) + let timestamp = u64::try_from(evm_env.block_env().timestamp) .map_err(|_| EthApiError::InvalidParams("invalid block timestamp".to_string()))?; let chain_spec = self.provider().chain_spec(); let hardfork = chain_spec.morph_hardfork_at(block_number, timestamp); @@ -176,7 +183,7 @@ where gas_price: u128, ) -> Result where - DB: revm::Database, + DB: Database, DB::Error: Into, { let token_fee_info = TokenFeeInfo::load_storage_only(db, fee_token_id, caller) @@ -185,7 +192,7 @@ where // ETH only needs to cover `value`; gas + L1 fee are paid in tokens. let eth_balance = db - .basic(caller) + .get_account(&caller) .map_err(|e| MorphEthApiError::Eth(e.into()))? .map(|acc| acc.balance) .unwrap_or_default(); @@ -239,7 +246,7 @@ fn token_gas_allowance( // - EVM-call mode (`balance_slot.is_none()`): RPC cannot resolve the // balance without spinning up an EVM (the handler does that at real // execution via `load_for_caller`). On the estimateGas path - // `disable_fee_charge=true` short-circuits the handler's check, so + // fee charging is off, which short-circuits the handler's check, so // there is no natural balance ceiling — we MUST enforce `gas_cap` // here, matching `eth_call`'s effective ceiling. Trusting a // user-supplied `fee_limit` alone would let `fee_limit = U256::MAX` diff --git a/crates/rpc/src/eth/mod.rs b/crates/rpc/src/eth/mod.rs index 6d57c11f..51642da0 100644 --- a/crates/rpc/src/eth/mod.rs +++ b/crates/rpc/src/eth/mod.rs @@ -8,10 +8,9 @@ use eyre::Result; use morph_chainspec::MorphChainSpec; use morph_evm::MorphEvmConfig; use morph_primitives::{MorphHeader, MorphPrimitives}; -use reth_node_api::{FullNodeComponents, FullNodeTypes, NodeTypes}; -use reth_node_builder::rpc::{EthApiBuilder, EthApiCtx}; -use reth_primitives_traits::RecoveredBlock; -use reth_provider::{BlockReader, ChainSpecProvider}; +use reth_node_api::{FullNodeComponents, NodeTypes}; +use reth_node_builder::rpc::{EthApiBuilder, EthApiCtx, RpcNodeCoreFor}; +use reth_provider::ChainSpecProvider; use reth_rpc::EthApi; use reth_rpc_convert::{RpcConvert, RpcConverter, RpcTypes}; use reth_rpc_eth_api::{ @@ -23,7 +22,7 @@ use reth_rpc_eth_api::{ }, }; use reth_rpc_eth_types::{ - EthApiError, EthStateCache, FeeHistoryCache, GasPriceOracle, StateCacheDb, + EthApiError, EthApiSettings, EthStateCache, FeeHistoryCache, GasPriceOracle, }; use reth_tasks::{ Runtime, @@ -79,10 +78,6 @@ where Evm = MorphEvmConfig, Types: NodeTypes, Provider: ChainSpecProvider, - > + crate::eth::MorphNodeCore - + reth_rpc_eth_api::RpcNodeCore< - Provider = ::Provider, - Pool = ::Pool, >, NetworkT: RpcTypes< Header = RpcHeader, @@ -92,12 +87,12 @@ where >, MorphRpcConverter: reth_rpc_convert::RpcConvert< Network = NetworkT, - Primitives = ::Primitives, + Primitives = MorphPrimitives, Error = reth_rpc_eth_types::EthApiError, - Evm = ::Evm, + Evm = MorphEvmConfig, >, { - type EthApi = MorphEthApi>; + type EthApi = MorphEthApi, MorphRpcConverter>; async fn build_eth_api(self, ctx: EthApiCtx<'_, N>) -> Result { let rpc_converter = RpcConverter::new(MorphReceiptConverter::default()); @@ -161,6 +156,10 @@ where fn converter(&self) -> &Self::RpcConvert { self.inner.eth_api.converter() } + + fn eth_api_settings(&self) -> &EthApiSettings { + self.inner.eth_api.eth_api_settings() + } } impl RpcNodeCore for MorphEthApi @@ -395,16 +394,6 @@ where MorphEthApiError: reth_rpc_eth_types::error::FromEvmError, Rpc: RpcConvert, { - fn apply_pre_execution_changes( - &self, - _block: &RecoveredBlock<::Block>, - _db: &mut StateCacheDb, - ) -> Result<(), Self::Error> { - // Morph must skip Ethereum's 4788-style pre-block system calls during replay. - // Standard Morph headers omit parentBeaconBlockRoot, so the default Ethereum - // SystemCaller prelude would fail with "EIP-4788 beacon root missing". - Ok(()) - } } impl GetBlockAccessList for MorphEthApi diff --git a/crates/rpc/src/eth/proofs.rs b/crates/rpc/src/eth/proofs.rs index 0f1bb898..86babbd7 100644 --- a/crates/rpc/src/eth/proofs.rs +++ b/crates/rpc/src/eth/proofs.rs @@ -277,7 +277,7 @@ where .map_err(Eth::Error::from_eth_err)? .proof(Default::default(), address, &storage_keys) .map_err(Eth::Error::from_eth_err)?; - Ok(proof.into_eip1186_response(keys)) + Ok(proof.into_eip1186_response_with(keys, true)) }) .await; @@ -317,7 +317,7 @@ where .map_err(EthApiError::Internal) .map_err(Eth::Error::from)?; let storage_keys = slots.into_iter().map(JsonStorageKey::from).collect(); - Ok(proof.into_eip1186_response(storage_keys)) + Ok(proof.into_eip1186_response_with(storage_keys, true)) }) .collect() }) diff --git a/crates/rpc/src/eth/transaction.rs b/crates/rpc/src/eth/transaction.rs index dfcf238d..1e4d471f 100644 --- a/crates/rpc/src/eth/transaction.rs +++ b/crates/rpc/src/eth/transaction.rs @@ -1,15 +1,21 @@ //! Morph transaction conversion for `eth_` RPC responses. use crate::MorphTransactionRequest; -use alloy_consensus::{EthereumTxEnvelope, SignableTransaction, TxEip4844}; +use alloy_consensus::{ + EthereumTxEnvelope, SignableTransaction, TxEip4844, TxType, transaction::Recovered, +}; use alloy_network::TxSigner; use alloy_primitives::{B256, Signature, TxKind, U64, U256}; use alloy_rpc_types_eth::AccessList; -use reth_rpc_convert::{SignTxRequestError, SignableTxRequest, TryIntoSimTx, TryIntoTxEnv}; +use evm2::ethereum::LazyAuthorization; +use reth_rpc_convert::{ + EthTxEnvError, SignTxRequestError, SignableTxRequest, TryIntoSimTx, TryIntoTxEnv, + normalize_transaction_request, +}; use reth_rpc_eth_types::EthApiError; use morph_primitives::{MorphTxEnvelope, TxMorph}; -use morph_revm::{MorphBlockEnv, MorphTxEnv}; +use morph_revm::{MorphEvmEnv, MorphTxEnv}; use reth_evm::EvmEnv; /// Converts a [`MorphTransactionRequest`] into a simulated transaction envelope. @@ -99,21 +105,15 @@ impl SignableTxRequest for MorphTransactionRequest { /// Also encodes the transaction for L1 fee calculation. /// The MorphTx version is derived from the content, see /// [`try_build_morph_tx_from_request`]. -impl TryIntoTxEnv for MorphTransactionRequest { +impl TryIntoTxEnv, MorphEvmEnv> for MorphTransactionRequest { type Err = EthApiError; - fn try_into_tx_env( - self, - evm_env: &EvmEnv, - ) -> Result { + fn try_into_tx_env(self, evm_env: &MorphEvmEnv) -> Result, Self::Err> { let fee_token_id = self.fee_token_id; let fee_limit = self.fee_limit; let reference = normalize_reference(self.reference); let memo = self.memo; let mut inner = self.inner; - if inner.chain_id.is_none() { - inner.chain_id = Some(evm_env.cfg_env.chain_id); - } let legacy_gas_price = inner.gas_price; let has_authorizations = inner .authorization_list @@ -131,9 +131,33 @@ impl TryIntoTxEnv for MorphTransactionReq || is_nonzero_reference(reference.as_ref()) || memo.as_ref().is_some_and(|m| !m.is_empty()); - let inner_tx_env = inner.try_into_tx_env(evm_env).map_err(EthApiError::from)?; - - let mut tx_env = MorphTxEnv::new(inner_tx_env); + let tx_type = inner.minimal_tx_type(); + let fees = normalize_transaction_request(&mut inner, evm_env).map_err(EthApiError::from)?; + let kind = inner.to.unwrap_or(TxKind::Create); + if !is_morph_tx && tx_type == TxType::Eip7702 && kind.is_create() { + return Err(EthTxEnvError::AuthorizationListInvalidFields.into()); + } + let caller = inner.from.unwrap_or_default(); + + let mut tx_env = MorphTxEnv { + tx_type: tx_type.into(), + gas_limit: inner.gas.unwrap_or_default(), + gas_price: fees.gas_price.saturating_to(), + gas_priority_fee: fees.max_priority_fee_per_gas.map(|fee| fee.saturating_to()), + kind, + value: inner.value.unwrap_or_default(), + data: inner.input.into_input().unwrap_or_default(), + nonce: inner.nonce.unwrap_or_default(), + chain_id: inner.chain_id, + access_list: inner.access_list.unwrap_or_default(), + authorization_list: inner + .authorization_list + .unwrap_or_default() + .into_iter() + .map(LazyAuthorization::Signed) + .collect(), + ..Default::default() + }; if is_morph_tx { tx_env.fee_token_id = match fee_token_id { Some(id) => Some( @@ -145,17 +169,17 @@ impl TryIntoTxEnv for MorphTransactionReq tx_env.fee_limit = fee_limit; tx_env.reference = reference; tx_env.memo = memo; - tx_env.inner.tx_type = morph_primitives::MORPH_TX_TYPE_ID; + tx_env.tx_type = morph_primitives::MORPH_TX_TYPE_ID; // geth's `ToMessage` maps legacy `gasPrice` to both EIP-1559 caps. // Preserve that shape so fallback MorphTx encoding produces the // same L1 data fee. if let Some(gas_price) = legacy_gas_price { - tx_env.inner.gas_priority_fee = Some(gas_price); + tx_env.gas_priority_fee = Some(gas_price); } // Same static rule as `TxMorph::validate`, surfaced as a parameter // error so simulations fail with a clear message rather than an // EVM-level rejection. - if has_authorizations && tx_env.inner.kind.is_create() { + if has_authorizations && tx_env.kind.is_create() { return Err(EthApiError::InvalidParams( "MorphTx with an authorization list cannot create a contract".to_string(), )); @@ -165,9 +189,9 @@ impl TryIntoTxEnv for MorphTransactionReq // Required by `MorphEthApi::caller_gas_allowance` (eth/call.rs) to // recover the L1 data fee when capping `eth_estimateGas` allowance. - tx_env.rlp_bytes = Some(tx_env.encode_for_l1_fee(evm_env.cfg_env.chain_id)); + tx_env.rlp_bytes = Some(tx_env.encode_for_l1_fee(evm_env.chain_id())); - Ok(tx_env) + Ok(Recovered::new_unchecked(tx_env, caller)) } } @@ -290,12 +314,13 @@ mod tests { use alloy_eips::eip2718::Decodable2718; use alloy_primitives::{Address, B256, Bytes, address}; use alloy_rpc_types_eth::{TransactionInfo, TransactionInput, TransactionRequest}; + use evm2::EvmFeatures; use morph_chainspec::MorphHardfork; use morph_primitives::transaction::morph_transaction::{ MORPH_TX_VERSION_1, MORPH_TX_VERSION_2, }; + use morph_revm::{MorphBlockEnv, morph_evm_env}; use reth_rpc_convert::FromConsensusTx; - use revm::context::{BlockEnv, CfgEnv}; /// Helper function to create a basic TransactionRequest for testing fn create_basic_transaction_request() -> TransactionRequest { @@ -321,27 +346,20 @@ mod tests { } /// Helper function to create a basic EvmEnv for testing - fn create_evm_env(disable_fee_charge: bool) -> EvmEnv { - let mut cfg = CfgEnv::::default(); - cfg.disable_fee_charge = disable_fee_charge; - cfg.chain_id = 2818; - - // Construct MorphBlockEnv directly to avoid clippy warning + fn create_evm_env(disable_fee_charge: bool) -> MorphEvmEnv { let block_env = MorphBlockEnv { - inner: BlockEnv { - number: alloy_primitives::U256::from(1), - beneficiary: alloy_primitives::Address::ZERO, - timestamp: alloy_primitives::U256::from(1234567890), - gas_limit: 30000000u64, - basefee: 1000000000u64, - difficulty: alloy_primitives::U256::ZERO, - prevrandao: Some(B256::ZERO), - blob_excess_gas_and_price: None, - slot_num: 0, - }, + number: U256::from(1), + timestamp: U256::from(1234567890), + gas_limit: U256::from(30_000_000u64), + basefee: U256::from(1_000_000_000u64), + ..Default::default() }; - EvmEnv::new(cfg, block_env) + let mut evm_env = morph_evm_env(MorphHardfork::default(), 2818, 30_000_000, block_env); + if disable_fee_charge { + evm_env.version.features.remove(EvmFeatures::FEE_CHARGE); + } + evm_env } /// RLP bytes are always populated — even on `eth_call` where @@ -369,7 +387,7 @@ mod tests { "rlp_bytes should be populated even when disable_fee_charge = true" ); assert!( - !tx_env.rlp_bytes.unwrap().is_empty(), + !tx_env.rlp_bytes.as_ref().unwrap().is_empty(), "RLP bytes should not be empty" ); } @@ -404,7 +422,7 @@ mod tests { "eth_estimateGas should encode RLP bytes for L1 fee calculation" ); assert!( - !tx_env.rlp_bytes.unwrap().is_empty(), + !tx_env.rlp_bytes.as_ref().unwrap().is_empty(), "RLP bytes should not be empty" ); } @@ -426,8 +444,11 @@ mod tests { .try_into_tx_env(&evm_env) .expect("conversion should succeed"); - assert_eq!(tx_env.inner.tx_type, 0, "gasPrice-only request is Legacy"); - let encoded = tx_env.rlp_bytes.expect("rlp_bytes must be populated"); + assert_eq!(tx_env.tx_type, 0, "gasPrice-only request is Legacy"); + let encoded = tx_env + .rlp_bytes + .as_ref() + .expect("rlp_bytes must be populated"); assert_eq!( encoded.first().copied(), Some(0x02), @@ -473,7 +494,7 @@ mod tests { // Assert: Transaction type should be MorphTx (0x7F) assert_eq!( - tx_env.inner.tx_type, + tx_env.tx_type, morph_primitives::MORPH_TX_TYPE_ID, "Transaction type should be MorphTx (0x7F)" ); @@ -549,13 +570,13 @@ mod tests { let tx_env = json_request(serde_json::json!({ "version": "0x1" })) .try_into_tx_env(&create_evm_env(false)) .expect("a legacy version key alone is a standard request"); - assert_ne!(tx_env.inner.tx_type, morph_primitives::MORPH_TX_TYPE_ID); + assert_ne!(tx_env.tx_type, morph_primitives::MORPH_TX_TYPE_ID); assert!(tx_env.version.is_none()); let tx_env = json_request(serde_json::json!({ "feeTokenID": "0x1", "version": "0x2" })) .try_into_tx_env(&create_evm_env(false)) .expect("token fee request"); - assert_eq!(tx_env.inner.tx_type, morph_primitives::MORPH_TX_TYPE_ID); + assert_eq!(tx_env.tx_type, morph_primitives::MORPH_TX_TYPE_ID); assert_eq!( tx_env.version, Some(MORPH_TX_VERSION_1), @@ -626,12 +647,12 @@ mod tests { .try_into_tx_env(&evm_env) .expect("conversion should succeed"); - assert_eq!(tx_env.inner.tx_type, morph_primitives::MORPH_TX_TYPE_ID); + assert_eq!(tx_env.tx_type, morph_primitives::MORPH_TX_TYPE_ID); assert_eq!(tx_env.fee_token_id, Some(1)); assert_eq!(tx_env.fee_limit, Some(U256::from(1000000))); // The legacy gas price is still what the EVM prices the call with. - assert_eq!(tx_env.inner.gas_price, 1_000_000_000); - assert_eq!(tx_env.inner.gas_priority_fee, Some(1_000_000_000)); + assert_eq!(tx_env.gas_price, 1_000_000_000); + assert_eq!(tx_env.gas_priority_fee, Some(1_000_000_000)); let encoded = tx_env .rlp_bytes @@ -663,16 +684,16 @@ mod tests { .try_into_tx_env(&evm_env) .expect("conversion should default missing chain_id from EVM env"); - assert_eq!(tx_env.inner.chain_id, Some(2818)); + assert_eq!(tx_env.chain_id, Some(2818)); } /// MorphTx converted on the `eth_call` path still carries RLP bytes. /// /// Before reth v2.0.0 this test asserted `rlp_bytes.is_none()` on the /// assumption that `eth_call` fell through to the EVM handler, which - /// read `rlp_bytes` for L1 fee deduction. reth v2.0.0 sets - /// `cfg_env.disable_fee_charge = true` on `eth_call`, causing the - /// handler to short-circuit before reading `rlp_bytes`, and the RLP + /// read `rlp_bytes` for L1 fee deduction. reth v2.0.0 turned fee + /// charging off on `eth_call`, causing the handler to + /// short-circuit before reading `rlp_bytes`, and the RLP /// is instead needed by `MorphEthApi::caller_gas_allowance` to /// compute the L1 fee cap on `eth_estimateGas`. We now populate it /// unconditionally. @@ -698,13 +719,13 @@ mod tests { "rlp_bytes should be populated even when disable_fee_charge = true" ); assert!( - !tx_env.rlp_bytes.unwrap().is_empty(), + !tx_env.rlp_bytes.as_ref().unwrap().is_empty(), "RLP bytes should not be empty" ); // Transaction type should still be MorphTx assert_eq!( - tx_env.inner.tx_type, + tx_env.tx_type, morph_primitives::MORPH_TX_TYPE_ID, "Transaction type should still be MorphTx" ); @@ -738,7 +759,7 @@ mod tests { // Assert: Transaction type should NOT be MorphTx assert_ne!( - tx_env.inner.tx_type, + tx_env.tx_type, morph_primitives::MORPH_TX_TYPE_ID, "Transaction type should not be MorphTx for standard Ethereum tx" ); @@ -1062,15 +1083,18 @@ mod tests { .try_into_tx_env(&evm_env) .expect("conversion should succeed"); - assert_eq!(tx_env.inner.tx_type, morph_primitives::MORPH_TX_TYPE_ID); + assert_eq!(tx_env.tx_type, morph_primitives::MORPH_TX_TYPE_ID); assert_eq!(tx_env.version, Some(MORPH_TX_VERSION_2)); assert_eq!( - tx_env.inner.authorization_list.len(), + tx_env.authorization_list.len(), 1, "EVM env must carry the authorization list" ); - let encoded = tx_env.rlp_bytes.expect("rlp_bytes must be populated"); + let encoded = tx_env + .rlp_bytes + .as_ref() + .expect("rlp_bytes must be populated"); let envelope = MorphTxEnvelope::decode_2718(&mut encoded.as_ref()).expect("RLP should decode"); let MorphTxEnvelope::Morph(signed) = envelope else { @@ -1098,10 +1122,10 @@ mod tests { let tx_env = request .try_into_tx_env(&create_evm_env(false)) .expect("memo + list is a valid V2 request"); - assert_eq!(tx_env.inner.tx_type, morph_primitives::MORPH_TX_TYPE_ID); + assert_eq!(tx_env.tx_type, morph_primitives::MORPH_TX_TYPE_ID); assert_eq!(tx_env.version, Some(MORPH_TX_VERSION_2)); assert_eq!(tx_env.fee_token_id, None); - assert_eq!(tx_env.inner.authorization_list.len(), 1); + assert_eq!(tx_env.authorization_list.len(), 1); } /// `eth_call` / `eth_estimateGas` without authorizations (absent key or @@ -1123,11 +1147,14 @@ mod tests { let tx_env = request .try_into_tx_env(&create_evm_env(false)) .expect("memo without a list is a valid V1 request"); - assert_eq!(tx_env.inner.tx_type, morph_primitives::MORPH_TX_TYPE_ID); + assert_eq!(tx_env.tx_type, morph_primitives::MORPH_TX_TYPE_ID); assert_eq!(tx_env.version, Some(MORPH_TX_VERSION_1)); - assert!(tx_env.inner.authorization_list.is_empty()); + assert!(tx_env.authorization_list.is_empty()); - let encoded = tx_env.rlp_bytes.expect("rlp_bytes must be populated"); + let encoded = tx_env + .rlp_bytes + .as_ref() + .expect("rlp_bytes must be populated"); let envelope = MorphTxEnvelope::decode_2718(&mut encoded.as_ref()).expect("RLP should decode"); let MorphTxEnvelope::Morph(signed) = envelope else { @@ -1156,7 +1183,7 @@ mod tests { .try_into_tx_env(&create_evm_env(false)) .expect("CREATE without authorizations is valid"); assert_eq!(tx_env.version, Some(MORPH_TX_VERSION_1)); - assert!(tx_env.inner.kind.is_create()); + assert!(tx_env.kind.is_create()); } #[test] @@ -1193,7 +1220,7 @@ mod tests { let tx_env = request .try_into_tx_env(&create_evm_env(false)) .expect("conversion should succeed"); - assert_eq!(tx_env.inner.tx_type, 4, "plain SetCode request"); + assert_eq!(tx_env.tx_type, 4, "plain SetCode request"); assert!(tx_env.version.is_none()); assert_eq!( tx_env.rlp_bytes.as_ref().and_then(|b| b.first().copied()), diff --git a/crates/rpc/src/execution_witness.rs b/crates/rpc/src/execution_witness.rs index e030d64d..d9838d38 100644 --- a/crates/rpc/src/execution_witness.rs +++ b/crates/rpc/src/execution_witness.rs @@ -21,18 +21,22 @@ use alloy_eips::{BlockId, BlockNumberOrTag}; use alloy_primitives::B256; use alloy_rpc_types_debug::ExecutionWitness; use async_trait::async_trait; +use evm2::evm::{CacheDB, Db}; use jsonrpsee::{ core::RpcResult, proc_macros::rpc, types::{ErrorCode, ErrorObject}, }; use morph_proofs::{MorphProofsStorage, MorphProofsStore}; -use reth_evm::{ConfigureEvm, execute::Executor}; +use reth_evm::{ + ConfigureEvm, database::StateProviderDatabase, execute::Executor, + witness::ExecutionWitnessRecord, +}; use reth_metrics::metrics::Label; -use reth_revm::{State, database::StateProviderDatabase, witness::ExecutionWitnessRecord}; use reth_rpc_api::eth::helpers::FullEthApi; use reth_rpc_eth_api::FromEthApiError; use reth_rpc_eth_types::EthApiError; +use reth_storage_api::StateProvider as _; use reth_trie_common::ExecutionWitnessMode; use crate::{ @@ -135,28 +139,22 @@ where let state = factory .state_provider(Some(parent_id)) .map_err(Eth::Error::from_eth_err)?; - let mut db = StateProviderDatabase::new(&state); - let executor = factory.eth_api().evm_config().executor(&mut db); - - // The same `mode` must reach both halves: it decides which bytecodes are collected - // here and how the trie witness is computed below. Passing different values would ship - // codes that describe a different execution than the trie nodes. - // Since reth 2.5.2 the record is built from the post-execution state inside the - // closure; the provider result is unwrapped only after execution succeeded. - let mut witness = None; - executor - .execute_with_state_closure(&block, |statedb: &State<_>| { - witness = Some(ExecutionWitnessRecord::new(statedb).into_execution_witness( - &*state, - factory.eth_api().provider(), - block_number, - mode, - )); - }) + let mut db = CacheDB::new(Db::new(StateProviderDatabase::new( + (&state).into_evm_state_provider(), + ))); + let output = factory + .eth_api() + .evm_config() + .executor(&mut db) + .execute(&block) .map_err(|error| Eth::Error::from_eth_err(EthApiError::Internal(error.into())))?; - witness - .expect("state closure is called after successful execution") + // The codes are captured before the output is committed, so canonical witnesses only + // carry code read from the parent state. + let codes = ExecutionWitnessRecord::commit_execution(&mut db, &output.state); + ExecutionWitnessRecord::new(&db) + .with_canonical_codes(codes) + .into_execution_witness(&*state, factory.eth_api().provider(), block_number, mode) .map_err(Eth::Error::from_eth_err) }) .await; diff --git a/crates/rpc/src/state.rs b/crates/rpc/src/state.rs index 55d56c43..10af6fe9 100644 --- a/crates/rpc/src/state.rs +++ b/crates/rpc/src/state.rs @@ -2,6 +2,7 @@ use alloy_eips::BlockId; use alloy_primitives::B256; +use alloy_rpc_types_eth::error::EthRpcErrorCode; use jsonrpsee::types::ErrorObject; use morph_proofs::{MorphProofsStorage, MorphProofsStore, provider::MorphProofsStateProviderRef}; use reth_provider::{ @@ -12,8 +13,6 @@ use reth_rpc_eth_types::{EthApiError, error::ToRpcError}; use thiserror::Error; use tracing::warn; -use crate::error::MorphEthApiError; - /// A request cannot be served by the current durable proof window. /// /// `Display` carries the full diagnosis for server-side logs; [`ToRpcError`] deliberately sends the @@ -39,7 +38,8 @@ enum ProofWindowError { } impl ToRpcError for ProofWindowError { - /// Reports every variant as `StateNotAvailable` (-32005). + /// Reports every variant with the pruned-history code (4444), as reth does for its own proof + /// window (`EthApiError::ExceedsMaxProofWindow`). /// /// These are client conditions — a block tag this node cannot serve a proof for — so they must /// not surface as internal server errors, which is what any error reaching reth through @@ -48,9 +48,6 @@ impl ToRpcError for ProofWindowError { /// [`EthApiError::other`] keeps the code under our control and spares clients from /// string-matching on messages. /// - /// Not EIP-4444's 4444 (`PrunedHistoryUnavailable`), which is about missing block history; what - /// is unavailable here is a state proof for a block whose header and body we still serve. - /// /// `CanonicalMismatch` sends no hashes. The canonical hash is public via `eth_getBlockByNumber`, /// but the stored one would tell a caller which abandoned branch this node's proof database is /// stuck on, which is not otherwise observable. The full pair stays in the log line emitted at @@ -71,11 +68,7 @@ impl ToRpcError for ProofWindowError { format!("state proof unavailable for block {block}") } }; - ErrorObject::owned( - MorphEthApiError::STATE_NOT_AVAILABLE_CODE, - message, - None::<()>, - ) + ErrorObject::owned(EthRpcErrorCode::PrunedHistory.code(), message, None::<()>) } } @@ -227,7 +220,7 @@ mod tests { use alloy_primitives::B256; use reth_rpc_eth_types::error::ToRpcError; - use super::{MorphEthApiError, ProofWindowError, validate_canonical_anchor, validate_window}; + use super::{ProofWindowError, validate_canonical_anchor, validate_window}; #[test] fn rejects_an_empty_window() { @@ -266,7 +259,7 @@ mod tests { } #[test] - fn reports_every_window_condition_as_state_not_available() { + fn reports_every_window_condition_as_pruned_history() { // Not an internal server error: these are all "this node cannot serve a proof for that // block", which the client fixes by choosing another block, not by retrying. for error in [ @@ -284,7 +277,7 @@ mod tests { ] { assert_eq!( error.to_rpc_error().code(), - MorphEthApiError::STATE_NOT_AVAILABLE_CODE, + 4444, "unexpected code for {error:?}" ); } diff --git a/crates/txpool/src/maintain.rs b/crates/txpool/src/maintain.rs index 7f54f551..a51d8e0c 100644 --- a/crates/txpool/src/maintain.rs +++ b/crates/txpool/src/maintain.rs @@ -29,11 +29,10 @@ use futures::StreamExt; use morph_chainspec::hardfork::MorphHardforks; use morph_revm::L1BlockInfo; use reth_chainspec::ChainSpecProvider; +use reth_evm::{Database, database::StateProviderDatabase}; use reth_primitives_traits::AlloyBlockHeader; use reth_provider::CanonStateSubscriptions; -use reth_revm::Database; -use reth_revm::database::StateProviderDatabase; -use reth_storage_api::StateProviderFactory; +use reth_storage_api::{StateProvider as _, StateProviderFactory}; use reth_transaction_pool::{PoolTransaction, TransactionPool}; use std::collections::HashMap; @@ -177,7 +176,7 @@ where } }; - let mut db = StateProviderDatabase::new(state_provider); + let mut db = StateProviderDatabase::new((&state_provider).into_evm_state_provider()); // Fetch L1 block info for fee calculation let l1_block_info = match L1BlockInfo::try_fetch(&mut db, hardfork) { @@ -212,7 +211,7 @@ where sender_txs.sort_by_key(|pooled_tx| pooled_tx.transaction.nonce()); // Initialize sender ETH budget once. - let eth_balance = match db.basic(sender) { + let eth_balance = match db.get_account(&sender) { Ok(Some(account)) => account.balance, Ok(None) => U256::ZERO, Err(err) => { diff --git a/crates/txpool/src/morph_tx_validation.rs b/crates/txpool/src/morph_tx_validation.rs index dbcacf6d..4da1ae75 100644 --- a/crates/txpool/src/morph_tx_validation.rs +++ b/crates/txpool/src/morph_tx_validation.rs @@ -4,7 +4,6 @@ //! that is used by both the validator (for new transactions) and the maintenance //! task (for revalidating existing transactions). -use alloy_evm::Database; use alloy_primitives::{Address, U256}; use morph_chainspec::hardfork::MorphHardfork; use morph_primitives::{ @@ -12,6 +11,7 @@ use morph_primitives::{ transaction::morph_transaction::{MORPH_TX_VERSION_1, MORPH_TX_VERSION_2}, }; use morph_revm::{MorphEvmEnv, TokenFeeInfo}; +use reth_evm::Database; use crate::MorphTxError; @@ -125,10 +125,7 @@ pub fn validate_morph_tx( // is evaluated under the hardfork's defaults. That matches the pool's previous // behaviour; threading the real head environment through admission is txpool // work and does not belong in this change. - let env = MorphEvmEnv::new( - reth_revm::revm::context::CfgEnv::new_with_spec(input.hardfork), - morph_revm::MorphBlockEnv::default(), - ); + let env = MorphEvmEnv::new(input.hardfork, morph_revm::MorphBlockEnv::default(), 1); let token_info = TokenFeeInfo::load_for_caller(db, fee_token_id, input.sender, &env) .map_err(|err| MorphTxError::TokenInfoFetchFailed { token_id: fee_token_id, @@ -185,8 +182,8 @@ mod tests { use super::*; use alloy_consensus::Signed; use alloy_primitives::{B256, Signature, TxKind, address}; + use evm2::evm::EmptyDB; use morph_primitives::{TxMorph, transaction::morph_transaction::MORPH_TX_VERSION_1}; - use reth_revm::revm::database::EmptyDB; #[test] fn test_morph_tx_validation_input_construction() { diff --git a/crates/txpool/src/validator.rs b/crates/txpool/src/validator.rs index a6c1f955..b85e072e 100644 --- a/crates/txpool/src/validator.rs +++ b/crates/txpool/src/validator.rs @@ -17,12 +17,11 @@ use morph_primitives::MorphTxEnvelope; use morph_revm::L1BlockInfo; use parking_lot::RwLock; use reth_chainspec::ChainSpecProvider; -use reth_evm::ConfigureEvm; +use reth_evm::{ConfigureEvm, database::StateProviderDatabase}; use reth_primitives_traits::{ Block, BlockTy, GotExpected, SealedBlock, transaction::error::InvalidTransactionError, }; -use reth_revm::database::StateProviderDatabase; -use reth_storage_api::{BlockReaderIdExt, StateProviderFactory}; +use reth_storage_api::{BlockReaderIdExt, StateProvider as _, StateProviderFactory}; use reth_transaction_pool::{ EthPoolTransaction, EthTransactionValidator, PoolTransaction, TransactionOrigin, TransactionValidationOutcome, TransactionValidator, @@ -34,12 +33,12 @@ use std::sync::{ /// EIP-3860 max initcode size (`2 * MAX_CODE_SIZE = 2 * 24 576 = 49 152` bytes). /// -/// Reuses revm's canonical constant — the same `eip3860::MAX_INITCODE_SIZE` that -/// reth's `EthTransactionValidator` uses — so it stays pinned to the EIP-170 +/// Reuses evm2's canonical constant, the base of the limit reth's +/// `EthTransactionValidator` applies, so it stays pinned to the EIP-170 /// code-size base instead of a hand-copied literal. Enforced unconditionally at /// the txpool layer because Morph has been post-Shanghai since genesis; see /// `validate_one_with_state` for why we can't rely on reth's Shanghai-gated check. -const MAX_INITCODE_SIZE: usize = reth_revm::revm::primitives::eip3860::MAX_INITCODE_SIZE; +const MAX_INITCODE_SIZE: usize = evm2::constants::MAX_INITCODE_SIZE; /// Tracks L1 block info for the current chain head. /// @@ -229,7 +228,7 @@ where } }; - let mut db = StateProviderDatabase::new(provider); + let mut db = StateProviderDatabase::new((&provider).into_evm_state_provider()); let hardfork = self .chain_spec() .morph_hardfork_at(header.number(), header.timestamp()); @@ -437,7 +436,7 @@ where message: err.to_string(), })?; - let mut db = StateProviderDatabase::new(provider); + let mut db = StateProviderDatabase::new((&provider).into_evm_state_provider()); // Use shared validation logic with unified API (includes ETH balance check) let input = crate::MorphTxValidationInput { diff --git a/deny.toml b/deny.toml index d411d181..b4a7c439 100644 --- a/deny.toml +++ b/deny.toml @@ -82,6 +82,9 @@ license-files = [{ path = "LICENSE", hash = 0x001c7e6c }] unknown-registry = "warn" unknown-git = "deny" allow-git = [ - "https://github.com/morph-l2/reth", + "https://github.com/paradigmxyz/reth", + "https://github.com/paradigmxyz/reth-core", "https://github.com/sigp/discv5", + # evm2 has no crates.io release; reth requires this exact URL through a `[patch]`. + "https://www.github.com/alloy-rs/evm2", ] From 4db039393dbb3fecc4191b5d500a6e07b1515d6d Mon Sep 17 00:00:00 2001 From: panos-xyz Date: Sun, 15 Nov 2026 21:30:13 +0800 Subject: [PATCH 03/16] chore: bump reth to v2.11.0 Upgrade all workspace reth dependencies from v2.10.1 to v2.11.0 along with coupled evm2 (66687c18) and alloy-trie 0.9.9 (picking up the sparse trie leaf-deletion fix), and update hickory-* to 0.26.3 for cargo-deny. EVM and block execution: - Populate `*host.tx_env_mut()` unconditionally at the start of `prepare` before branching on L1 messages or fee deduction, and initialize it on standalone call-mode `balanceOf` queries in `token_fee.rs`. - Read `host.tx_env().chain_id` in `morph_blockhash`, matching `CHAINID`. - Read precompile input slices via `evm.message_input(message)`. - Introduce owned `MorphAuthorization` (`Signed` / `Recovered`) to adapt to lifetime-parameterized `evm2::ethereum::LazyAuthorization<'a>`. - Wrap installed inspectors in module-private `InstalledInspector` to implement `Evm::{with_inspector, take_inspector}` soundly and return `InspectorConfig::without_steps()` inside hidden fee frames. - Classify `IntrinsicGasGreaterThanCap` / `GasLimitBelowFloor` on `MorphInvalidTxError`, wrap handler errors in `evm2::AnyError`, and implement `BlockTransactionResult::into_result` on `MorphTxResult`. --- Cargo.lock | 804 +++++++++++++++--------------- Cargo.toml | 143 +++--- bin/morph-statetest/src/schema.rs | 5 +- crates/evm/src/block/mod.rs | 201 +++++++- crates/evm/src/evm.rs | 239 ++++++++- crates/revm/src/evm.rs | 45 +- crates/revm/src/handler.rs | 189 +++---- crates/revm/src/lib.rs | 2 +- crates/revm/src/precompiles.rs | 8 +- crates/revm/src/token_fee.rs | 7 +- crates/revm/src/tx.rs | 85 +++- crates/rpc/src/eth/transaction.rs | 5 +- deny.toml | 5 +- 13 files changed, 1142 insertions(+), 596 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d0fc5b87..e25d3bfc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -10,12 +10,12 @@ checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" [[package]] name = "aead" -version = "0.5.2" +version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" +checksum = "1973cfbc1a2daf9cf550e74e1f088c28e7f7d8c1e1418fb6c9dc5184b7e84c99" dependencies = [ - "crypto-common 0.1.7", - "generic-array", + "crypto-common 0.2.2", + "inout 0.2.6", ] [[package]] @@ -25,22 +25,33 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" dependencies = [ "cfg-if", - "cipher", + "cipher 0.4.4", "cpufeatures 0.2.17", ] +[[package]] +name = "aes" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc0fc36d7440d015b45468ba08a21e80e056ebbd014c611c6298bb7503e04bd1" +dependencies = [ + "cipher 0.5.2", + "cpubits", + "cpufeatures 0.3.0", +] + [[package]] name = "aes-gcm" -version = "0.10.3" +version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "831010a0f742e1209b3bcea8fab6a8e149051ba6099432c8cb2cc117dec3ead1" +checksum = "7f2b8006a0c83f52b62ba44a97b58bf76fe2f70a329e588f67f89691d93d498f" dependencies = [ "aead", - "aes", - "cipher", - "ctr", + "aes 0.9.4", + "cipher 0.5.2", + "ctr 0.10.1", + "ctutils", "ghash", - "subtle", ] [[package]] @@ -50,7 +61,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" dependencies = [ "cfg-if", - "getrandom 0.3.4", "once_cell", "version_check", "zerocopy", @@ -869,9 +879,9 @@ dependencies = [ [[package]] name = "alloy-trie" -version = "0.9.8" +version = "0.9.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b94e3e0a88f8db47250ac8a95fb825d020719f833eb1dc661bd3609c3bbece7d" +checksum = "70c7c04b6e5a7a2325f53d38c319a47d01c3609b44845ac2801bac9643fe26b9" dependencies = [ "alloy-primitives", "alloy-rlp", @@ -944,7 +954,7 @@ version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -955,7 +965,7 @@ checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" dependencies = [ "anstyle", "once_cell_polyfill", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -1536,6 +1546,12 @@ version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + [[package]] name = "base64ct" version = "1.8.3" @@ -1933,7 +1949,18 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" dependencies = [ "crypto-common 0.1.7", - "inout", + "inout 0.1.4", +] + +[[package]] +name = "cipher" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c" +dependencies = [ + "block-buffer 0.12.1", + "crypto-common 0.2.2", + "inout 0.2.6", ] [[package]] @@ -2380,7 +2407,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" dependencies = [ "generic-array", - "rand_core 0.6.4", "typenum", ] @@ -2401,7 +2427,16 @@ version = "0.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835" dependencies = [ - "cipher", + "cipher 0.4.4", +] + +[[package]] +name = "ctr" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baaca1c4b237092596f64d571e9db6ce4109c4ef9742e27590f1709594461f21" +dependencies = [ + "cipher 0.5.2", ] [[package]] @@ -2416,15 +2451,16 @@ dependencies = [ [[package]] name = "curve25519-dalek" -version = "4.1.3" +version = "5.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be" +checksum = "b5eed333089e2e1c1ac8c6c0398e5e2497b4c9926ca6d0365ed1e099afa5bc23" dependencies = [ "cfg-if", - "cpufeatures 0.2.17", + "cpufeatures 0.3.0", "curve25519-dalek-derive", - "digest 0.10.7", + "digest 0.11.3", "fiat-crypto", + "rand_core 0.10.1", "rustc_version 0.4.1", "subtle", "zeroize", @@ -2515,7 +2551,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ccc2776f0c61eca1ca32528f85548abd1a4be8fb53d1b21c013e4f18da1e7090" dependencies = [ "data-encoding", - "syn 2.0.117", + "syn 1.0.109", ] [[package]] @@ -2651,12 +2687,6 @@ dependencies = [ "unicode-xid", ] -[[package]] -name = "diff" -version = "0.1.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56254986775e3233ffa9c4d7d3faaf6d36a2c09d30b20687e9f88bc8bafc16c8" - [[package]] name = "digest" version = "0.9.0" @@ -2713,14 +2743,15 @@ dependencies = [ [[package]] name = "discv5" -version = "0.10.4" -source = "git+https://github.com/sigp/discv5?rev=7663c00#7663c00ee0837ea98547caaedede95d9d6736f4d" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "907a0cd56341d2fa9bba3a3fce8296cfb5878d6ec314340751e79836cccdc9da" dependencies = [ - "aes", + "aes 0.9.4", "aes-gcm", "alloy-rlp", "arrayvec", - "ctr", + "ctr 0.10.1", "delay_map", "enr", "fnv", @@ -2733,7 +2764,7 @@ dependencies = [ "more-asserts", "multiaddr", "parking_lot", - "rand 0.8.6", + "rand 0.10.2", "smallvec", "socket2", "tokio", @@ -2819,25 +2850,24 @@ dependencies = [ [[package]] name = "ed25519" -version = "2.2.3" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53" +checksum = "29fcf32e6c73d1079f83ab4d782de2d81620346a5f38c6237a86a22f8368980a" dependencies = [ - "pkcs8 0.10.2", - "signature 2.2.0", + "signature 3.0.0", ] [[package]] name = "ed25519-dalek" -version = "2.2.0" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9" +checksum = "6ebaa1a2bf1290ab3bfe5a7b771d050ebffab2711c19a81691c683a5144a25de" dependencies = [ "curve25519-dalek", "ed25519", - "rand_core 0.6.4", - "serde", - "sha2 0.10.9", + "rand_core 0.10.1", + "sha2 0.11.0", + "signature 3.0.0", "subtle", "zeroize", ] @@ -2906,21 +2936,20 @@ dependencies = [ [[package]] name = "enr" -version = "0.13.0" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "851bd664a3d3a3c175cff92b2f0df02df3c541b4895d0ae307611827aae46152" +checksum = "d7401327556f645a74cbcde3f95916ec8f989a46da39152d9cfe89d5ff036b8f" dependencies = [ "alloy-rlp", - "base64 0.22.1", + "base64 0.23.1", "bytes", "ed25519-dalek", "hex", - "k256 0.13.4", - "log", - "rand 0.8.6", - "secp256k1 0.30.0", + "k256 0.14.0", + "rand 0.10.2", + "secp256k1 0.33.1", "serde", - "sha3 0.10.9", + "sha3 0.12.0", "zeroize", ] @@ -2957,7 +2986,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -3014,11 +3043,12 @@ dependencies = [ [[package]] name = "evm2" version = "0.1.0" -source = "git+https://www.github.com/alloy-rs/evm2?rev=01df8f6a396d0250da286cb763faa6ec292d65b5#01df8f6a396d0250da286cb763faa6ec292d65b5" +source = "git+https://github.com/DaniPopes/evm2?rev=66687c18b34d3bdbb899f5eb7605070615c03475#66687c18b34d3bdbb899f5eb7605070615c03475" dependencies = [ "alloy-consensus", "alloy-eip7928", "alloy-eips", + "alloy-hardforks", "alloy-primitives", "ark-bls12-381", "ark-bn254", @@ -3052,7 +3082,7 @@ dependencies = [ [[package]] name = "evm2-inspectors" version = "0.1.0" -source = "git+https://www.github.com/alloy-rs/evm2?rev=01df8f6a396d0250da286cb763faa6ec292d65b5#01df8f6a396d0250da286cb763faa6ec292d65b5" +source = "git+https://github.com/DaniPopes/evm2?rev=66687c18b34d3bdbb899f5eb7605070615c03475#66687c18b34d3bdbb899f5eb7605070615c03475" dependencies = [ "alloy-consensus", "alloy-eip2930", @@ -3073,7 +3103,7 @@ dependencies = [ [[package]] name = "evm2-macros" version = "0.1.0" -source = "git+https://www.github.com/alloy-rs/evm2?rev=01df8f6a396d0250da286cb763faa6ec292d65b5#01df8f6a396d0250da286cb763faa6ec292d65b5" +source = "git+https://github.com/DaniPopes/evm2?rev=66687c18b34d3bdbb899f5eb7605070615c03475#66687c18b34d3bdbb899f5eb7605070615c03475" dependencies = [ "proc-macro2", "quote", @@ -3162,9 +3192,9 @@ dependencies = [ [[package]] name = "fiat-crypto" -version = "0.2.9" +version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" +checksum = "64cd1e32ddd350061ae6edb1b082d7c54915b5c672c389143b9a63403a109f24" [[package]] name = "filetime" @@ -3409,8 +3439,8 @@ dependencies = [ "libc", "log", "rustversion", - "windows-link 0.2.1", - "windows-result 0.4.1", + "windows-link 0.1.3", + "windows-result 0.3.4", ] [[package]] @@ -3467,11 +3497,10 @@ dependencies = [ [[package]] name = "ghash" -version = "0.5.1" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0d8a4362ccb29cb0b265253fb0a2728f592895ee6854fd9bc13f2ffda266ff1" +checksum = "2eecf2d5dc9b66b732b97707a0210906b1d30523eb773193ab777c0c84b3e8d5" dependencies = [ - "opaque-debug", "polyval", ] @@ -3598,12 +3627,6 @@ version = "0.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" -[[package]] -name = "hashbrown" -version = "0.13.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43a3c133739dddd0d2990f9a4bdf8eb4b21ef50e4851ca85ab661199821d510e" - [[package]] name = "hashbrown" version = "0.14.5" @@ -3645,11 +3668,11 @@ dependencies = [ [[package]] name = "hashlink" -version = "0.11.0" +version = "0.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea0b22561a9c04a7cb1a302c013e0259cd3b4bb619f145b32f72b8b4bcbed230" +checksum = "a596f1b20ed2cc5ecac41a164aaebc7258057060f06c0cf7a2ba3991ee7990fb" dependencies = [ - "hashbrown 0.16.1", + "hashbrown 0.17.0", ] [[package]] @@ -3681,9 +3704,9 @@ dependencies = [ [[package]] name = "hickory-net" -version = "0.26.1" +version = "0.26.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2295ed2f9c31e471e1428a8f88a3f0e1f4b27c15049592138d1eebe9c35b183" +checksum = "c480823ed7c2c5d0f09c41020cb6b7c28029ce60ec42dc942158dcf22f8e0a4d" dependencies = [ "async-trait", "cfg-if", @@ -3705,9 +3728,9 @@ dependencies = [ [[package]] name = "hickory-proto" -version = "0.26.1" +version = "0.26.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0bab31817bfb44672a252e97fe81cd0c18d1b2cf892108922f6818820df8c643" +checksum = "12b92608f679a6fa515dd1d15c1ff89443026e391200a2c840c7afcba482893d" dependencies = [ "data-encoding", "idna", @@ -3726,9 +3749,9 @@ dependencies = [ [[package]] name = "hickory-resolver" -version = "0.26.1" +version = "0.26.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0d58d28879ceecde6607729660c2667a081ccdc082e082675042793960f178c" +checksum = "3f3da5255c95d5a716857d54b5b8f4e8d67c3484d3beaaaae2ce25063b3ba981" dependencies = [ "cfg-if", "futures-util", @@ -3753,11 +3776,11 @@ dependencies = [ [[package]] name = "hkdf" -version = "0.12.4" +version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7" +checksum = "4aaa26c720c68b866f2c96ef5c1264b3e6f473fe5d4ce61cd44bbe913e553018" dependencies = [ - "hmac 0.12.1", + "hmac 0.13.0", ] [[package]] @@ -4195,6 +4218,15 @@ dependencies = [ "generic-array", ] +[[package]] +name = "inout" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a580c13f0ffc335ef42dd3f6b1a41b726051c5e1656d9a3aa6fddb3c5dfbbf9" +dependencies = [ + "hybrid-array", +] + [[package]] name = "instability" version = "0.3.12" @@ -4666,6 +4698,7 @@ dependencies = [ "primeorder", "serdect 0.4.3", "sha2 0.11.0", + "signature 3.0.0", "wnaf", ] @@ -4803,18 +4836,18 @@ checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" [[package]] name = "libp2p-identity" -version = "0.2.13" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0c7892c221730ba55f7196e98b0b8ba5e04b4155651736036628e9f73ed6fc3" +checksum = "4af6ad75465f6bf26a1001ddbf6f2b6b84a4673bf6de289f68cdbb1430098627" dependencies = [ "asn1_der", "bs58", "ed25519-dalek", "hkdf", - "k256 0.13.4", + "k256 0.14.0", "multihash", - "quick-protobuf", - "sha2 0.10.9", + "prost", + "sha2 0.11.0", "thiserror 2.0.21", "tracing", "zeroize", @@ -5706,12 +5739,12 @@ dependencies = [ [[package]] name = "multiaddr" -version = "0.18.2" +version = "0.19.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fe6351f60b488e04c1d21bc69e56b89cb3f5e8f5d22557d6e8031bdfd79b6961" +checksum = "fd707c05eadfb37577f01cbec206726feeecf0b9edea259aee6fc9bc541ee253" dependencies = [ - "arrayref", "byteorder", + "bytes", "data-encoding", "libp2p-identity", "multibase", @@ -5802,7 +5835,7 @@ version = "0.50.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -5986,12 +6019,6 @@ version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" -[[package]] -name = "opaque-debug" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" - [[package]] name = "openssl-probe" version = "0.2.1" @@ -6250,13 +6277,12 @@ dependencies = [ [[package]] name = "polyval" -version = "0.6.2" +version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d1fe60d06143b2430aa532c94cfe9e29783047f06c0d7fd359a9a51b729fa25" +checksum = "f0fa31d631f2b2cb2a544d0aa321ce847a94764d701ca2becc411138b93d49cd" dependencies = [ - "cfg-if", - "cpufeatures 0.2.17", - "opaque-debug", + "cpubits", + "cpufeatures 0.3.0", "universal-hash", ] @@ -6349,16 +6375,6 @@ dependencies = [ "num-traits", ] -[[package]] -name = "pretty_assertions" -version = "1.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ae130e2f271fbc2ac3a40fb1d07180839cdbbe443c7a27e1e3c13c5cac0116d" -dependencies = [ - "diff", - "yansi", -] - [[package]] name = "prettyplease" version = "0.2.37" @@ -6602,15 +6618,6 @@ version = "1.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0" -[[package]] -name = "quick-protobuf" -version = "0.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d6da84cc204722a989e01ba2f6e1e276e190f22263d0cb6ce8526fcdb0d2e1f" -dependencies = [ - "byteorder", -] - [[package]] name = "quinn" version = "0.11.9" @@ -7037,8 +7044,8 @@ checksum = "1e061d1b48cb8d38042de4ae0a7a6401009d6143dc80d2e2d6f31f0bdd6470c7" [[package]] name = "reth-basic-payload-builder" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-eips", @@ -7064,8 +7071,8 @@ dependencies = [ [[package]] name = "reth-chain-state" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-eips", @@ -7093,8 +7100,8 @@ dependencies = [ [[package]] name = "reth-chainspec" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-chains", "alloy-consensus", @@ -7112,8 +7119,8 @@ dependencies = [ [[package]] name = "reth-cli" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-genesis", "clap", @@ -7125,8 +7132,8 @@ dependencies = [ [[package]] name = "reth-cli-commands" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-chains", "alloy-consensus", @@ -7194,7 +7201,7 @@ dependencies = [ "reth-tasks", "reth-trie", "reth-trie-db", - "secp256k1 0.30.0", + "secp256k1 0.33.1", "serde", "serde_json", "socket2", @@ -7209,8 +7216,8 @@ dependencies = [ [[package]] name = "reth-cli-runner" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "reth-tasks", "tokio", @@ -7219,16 +7226,16 @@ dependencies = [ [[package]] name = "reth-cli-util" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-eips", "alloy-primitives", "eyre", "libc", - "rand 0.8.6", + "rand 0.9.4", "reth-fs-util", - "secp256k1 0.30.0", + "secp256k1 0.33.1", "serde", "thiserror 2.0.21", "tikv-jemalloc-sys", @@ -7267,8 +7274,8 @@ dependencies = [ [[package]] name = "reth-config" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "eyre", "humantime-serde", @@ -7284,8 +7291,8 @@ dependencies = [ [[package]] name = "reth-consensus" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-eip7928", @@ -7298,8 +7305,8 @@ dependencies = [ [[package]] name = "reth-consensus-common" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-eips", @@ -7311,8 +7318,8 @@ dependencies = [ [[package]] name = "reth-consensus-debug-client" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-eips", @@ -7336,8 +7343,8 @@ dependencies = [ [[package]] name = "reth-db" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-primitives", "derive_more", @@ -7364,8 +7371,8 @@ dependencies = [ [[package]] name = "reth-db-api" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-eips", @@ -7391,8 +7398,8 @@ dependencies = [ [[package]] name = "reth-db-common" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-genesis", @@ -7421,8 +7428,8 @@ dependencies = [ [[package]] name = "reth-db-models" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-eips", "alloy-primitives", @@ -7436,8 +7443,8 @@ dependencies = [ [[package]] name = "reth-discv4" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-primitives", "alloy-rlp", @@ -7445,13 +7452,13 @@ dependencies = [ "enr", "itertools 0.14.0", "parking_lot", - "rand 0.8.6", + "rand 0.9.4", "reth-ethereum-forks", + "reth-lru", "reth-net-banlist", "reth-net-nat", "reth-network-peers", - "schnellru", - "secp256k1 0.30.0", + "secp256k1 0.33.1", "serde", "thiserror 2.0.21", "tokio", @@ -7461,8 +7468,8 @@ dependencies = [ [[package]] name = "reth-discv5" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-primitives", "alloy-rlp", @@ -7471,13 +7478,15 @@ dependencies = [ "enr", "futures", "itertools 0.14.0", + "libp2p-identity", "metrics", + "multiaddr", "rand 0.9.4", "reth-chainspec", "reth-ethereum-forks", "reth-metrics", "reth-network-peers", - "secp256k1 0.30.0", + "secp256k1 0.33.1", "thiserror 2.0.21", "tokio", "tracing", @@ -7485,8 +7494,8 @@ dependencies = [ [[package]] name = "reth-dns-discovery" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-primitives", "dashmap", @@ -7495,10 +7504,10 @@ dependencies = [ "hickory-resolver", "linked_hash_set", "reth-ethereum-forks", + "reth-lru", "reth-network-peers", "reth-tokio-util", - "schnellru", - "secp256k1 0.30.0", + "secp256k1 0.33.1", "serde", "serde_with", "thiserror 2.0.21", @@ -7509,8 +7518,8 @@ dependencies = [ [[package]] name = "reth-downloaders" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-eips", @@ -7545,8 +7554,8 @@ dependencies = [ [[package]] name = "reth-e2e-test-utils" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-eips", @@ -7608,23 +7617,23 @@ dependencies = [ [[package]] name = "reth-ecies" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ - "aes", + "aes 0.8.4", "alloy-primitives", "alloy-rlp", "byteorder", - "cipher", + "cipher 0.4.4", "concat-kdf", - "ctr", + "ctr 0.9.2", "digest 0.10.7", "futures", "hmac 0.12.1", "pin-project", - "rand 0.8.6", + "rand 0.9.4", "reth-network-peers", - "secp256k1 0.30.0", + "secp256k1 0.33.1", "sha2 0.10.9", "thiserror 2.0.21", "tokio", @@ -7635,8 +7644,8 @@ dependencies = [ [[package]] name = "reth-engine-local" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-primitives", @@ -7658,8 +7667,8 @@ dependencies = [ [[package]] name = "reth-engine-primitives" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-eips", @@ -7686,8 +7695,8 @@ dependencies = [ [[package]] name = "reth-engine-tree" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-eip7928", @@ -7708,13 +7717,13 @@ dependencies = [ "reth-chain-state", "reth-chainspec", "reth-consensus", - "reth-db", "reth-engine-primitives", "reth-errors", "reth-ethereum-primitives", "reth-evm", "reth-execution-cache", "reth-execution-types", + "reth-lru", "reth-metrics", "reth-network-p2p", "reth-payload-builder", @@ -7733,7 +7742,6 @@ dependencies = [ "reth-trie-common", "reth-trie-parallel", "reth-trie-sparse", - "schnellru", "thiserror 2.0.21", "tokio", "tracing", @@ -7741,8 +7749,8 @@ dependencies = [ [[package]] name = "reth-engine-util" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-primitives", @@ -7769,8 +7777,8 @@ dependencies = [ [[package]] name = "reth-era" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-eips", @@ -7787,8 +7795,8 @@ dependencies = [ [[package]] name = "reth-era-downloader" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-primitives", "bytes", @@ -7803,8 +7811,8 @@ dependencies = [ [[package]] name = "reth-era-utils" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-primitives", @@ -7827,8 +7835,8 @@ dependencies = [ [[package]] name = "reth-errors" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "reth-consensus", "reth-execution-errors", @@ -7838,8 +7846,8 @@ dependencies = [ [[package]] name = "reth-eth-wire" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-chains", "alloy-primitives", @@ -7866,8 +7874,8 @@ dependencies = [ [[package]] name = "reth-eth-wire-types" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-chains", "alloy-consensus", @@ -7889,8 +7897,8 @@ dependencies = [ [[package]] name = "reth-ethereum-cli" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "clap", "eyre", @@ -7912,8 +7920,8 @@ dependencies = [ [[package]] name = "reth-ethereum-consensus" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-eips", @@ -7928,8 +7936,8 @@ dependencies = [ [[package]] name = "reth-ethereum-engine-primitives" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-eips", "alloy-primitives", @@ -7944,8 +7952,8 @@ dependencies = [ [[package]] name = "reth-ethereum-forks" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-eip2124", "alloy-hardforks", @@ -7957,8 +7965,8 @@ dependencies = [ [[package]] name = "reth-ethereum-payload-builder" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-eips", @@ -7986,8 +7994,8 @@ dependencies = [ [[package]] name = "reth-ethereum-primitives" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-eips", @@ -7999,8 +8007,8 @@ dependencies = [ [[package]] name = "reth-etl" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "rayon", "reth-db-api", @@ -8009,8 +8017,8 @@ dependencies = [ [[package]] name = "reth-evm" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-eip7928", @@ -8037,16 +8045,16 @@ dependencies = [ [[package]] name = "reth-evm-ethereum" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-eip7928", "alloy-eips", "alloy-primitives", "alloy-rpc-types-engine", - "alloy-sol-types", "evm2", + "rayon", "reth-chainspec", "reth-ethereum-forks", "reth-ethereum-primitives", @@ -8058,8 +8066,8 @@ dependencies = [ [[package]] name = "reth-execution-cache" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-primitives", "fixed-cache", @@ -8076,11 +8084,12 @@ dependencies = [ [[package]] name = "reth-execution-errors" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-primitives", "alloy-rlp", + "evm2", "nybbles", "reth-storage-errors", "thiserror 2.0.21", @@ -8088,8 +8097,8 @@ dependencies = [ [[package]] name = "reth-execution-types" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-eip7928", @@ -8107,8 +8116,8 @@ dependencies = [ [[package]] name = "reth-exex" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-eips", @@ -8143,8 +8152,8 @@ dependencies = [ [[package]] name = "reth-exex-test-utils" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-eips", "eyre", @@ -8175,8 +8184,8 @@ dependencies = [ [[package]] name = "reth-exex-types" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-eips", "alloy-primitives", @@ -8189,8 +8198,8 @@ dependencies = [ [[package]] name = "reth-fs-util" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "serde", "serde_json", @@ -8199,8 +8208,8 @@ dependencies = [ [[package]] name = "reth-invalid-block-hooks" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-primitives", @@ -8208,25 +8217,28 @@ dependencies = [ "alloy-rpc-types-debug", "evm2", "eyre", - "futures", "jsonrpsee", - "pretty_assertions", + "metrics", "reth-engine-primitives", "reth-evm", "reth-execution-types", + "reth-fs-util", "reth-primitives-traits", "reth-provider", "reth-rpc-api", + "reth-tasks", "reth-trie", "serde", "serde_json", + "similar", + "tokio", "tracing", ] [[package]] name = "reth-ipc" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "bytes", "futures", @@ -8245,8 +8257,8 @@ dependencies = [ [[package]] name = "reth-libmdbx" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "bitflags 2.13.2", "byteorder", @@ -8260,10 +8272,19 @@ dependencies = [ "tracing", ] +[[package]] +name = "reth-lru" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" +dependencies = [ + "alloy-primitives", + "hashbrown 0.17.0", +] + [[package]] name = "reth-mdbx-sys" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "bindgen", "cc", @@ -8271,8 +8292,8 @@ dependencies = [ [[package]] name = "reth-metrics" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "futures", "libc", @@ -8285,8 +8306,8 @@ dependencies = [ [[package]] name = "reth-net-banlist" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-primitives", "ipnet", @@ -8294,8 +8315,8 @@ dependencies = [ [[package]] name = "reth-net-nat" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "futures-util", "if-addrs", @@ -8308,8 +8329,8 @@ dependencies = [ [[package]] name = "reth-network" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-eips", @@ -8325,7 +8346,6 @@ dependencies = [ "metrics", "parking_lot", "pin-project", - "rand 0.8.6", "rand 0.9.4", "rayon", "reth-chainspec", @@ -8341,6 +8361,7 @@ dependencies = [ "reth-evm", "reth-evm-ethereum", "reth-fs-util", + "reth-lru", "reth-metrics", "reth-net-banlist", "reth-net-nat", @@ -8354,8 +8375,7 @@ dependencies = [ "reth-tokio-util", "reth-transaction-pool", "rustc-hash", - "schnellru", - "secp256k1 0.30.0", + "secp256k1 0.33.1", "serde", "smallvec", "socket2", @@ -8368,8 +8388,8 @@ dependencies = [ [[package]] name = "reth-network-api" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-primitives", @@ -8393,8 +8413,8 @@ dependencies = [ [[package]] name = "reth-network-p2p" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-eip7928", @@ -8417,13 +8437,13 @@ dependencies = [ [[package]] name = "reth-network-peers" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-primitives", "alloy-rlp", "enr", - "secp256k1 0.30.0", + "secp256k1 0.33.1", "serde_with", "thiserror 2.0.21", "tokio", @@ -8432,8 +8452,8 @@ dependencies = [ [[package]] name = "reth-network-types" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-eip2124", "humantime-serde", @@ -8446,8 +8466,8 @@ dependencies = [ [[package]] name = "reth-nippy-jar" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "anyhow", "bincode 1.3.3", @@ -8464,8 +8484,8 @@ dependencies = [ [[package]] name = "reth-node-api" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-rpc-types-engine", "eyre", @@ -8488,8 +8508,8 @@ dependencies = [ [[package]] name = "reth-node-builder" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-eips", @@ -8549,7 +8569,7 @@ dependencies = [ "reth-tokio-util", "reth-tracing", "reth-transaction-pool", - "secp256k1 0.30.0", + "secp256k1 0.33.1", "serde_json", "tokio", "tokio-stream", @@ -8558,8 +8578,8 @@ dependencies = [ [[package]] name = "reth-node-core" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-eips", @@ -8600,7 +8620,7 @@ dependencies = [ "reth-tracing", "reth-tracing-otlp", "reth-transaction-pool", - "secp256k1 0.30.0", + "secp256k1 0.33.1", "serde", "smolgen", "strum", @@ -8612,8 +8632,8 @@ dependencies = [ [[package]] name = "reth-node-ethereum" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-eips", @@ -8670,8 +8690,8 @@ dependencies = [ [[package]] name = "reth-node-ethstats" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-primitives", @@ -8694,8 +8714,8 @@ dependencies = [ [[package]] name = "reth-node-events" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-eips", @@ -8718,8 +8738,8 @@ dependencies = [ [[package]] name = "reth-node-metrics" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "bytes", "eyre", @@ -8749,8 +8769,8 @@ dependencies = [ [[package]] name = "reth-node-types" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "reth-chainspec", "reth-db-api", @@ -8761,8 +8781,8 @@ dependencies = [ [[package]] name = "reth-payload-builder" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-primitives", @@ -8785,8 +8805,8 @@ dependencies = [ [[package]] name = "reth-payload-builder-primitives" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "pin-project", "reth-payload-primitives", @@ -8797,8 +8817,8 @@ dependencies = [ [[package]] name = "reth-payload-primitives" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-eips", @@ -8820,8 +8840,8 @@ dependencies = [ [[package]] name = "reth-payload-util" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-primitives", @@ -8830,8 +8850,8 @@ dependencies = [ [[package]] name = "reth-payload-validator" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-rpc-types-engine", @@ -8871,8 +8891,8 @@ dependencies = [ [[package]] name = "reth-provider" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-eip7928", @@ -8920,8 +8940,8 @@ dependencies = [ [[package]] name = "reth-prune" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-primitives", @@ -8939,7 +8959,6 @@ dependencies = [ "reth-static-file-types", "reth-storage-api", "reth-tokio-util", - "rustc-hash", "thiserror 2.0.21", "tokio", "tracing", @@ -8947,8 +8966,8 @@ dependencies = [ [[package]] name = "reth-prune-types" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-primitives", "arbitrary", @@ -8963,8 +8982,8 @@ dependencies = [ [[package]] name = "reth-rpc" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-dyn-abi", @@ -9036,8 +9055,8 @@ dependencies = [ [[package]] name = "reth-rpc-api" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-eips", "alloy-genesis", @@ -9066,8 +9085,8 @@ dependencies = [ [[package]] name = "reth-rpc-builder" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-network", "alloy-provider", @@ -9109,8 +9128,8 @@ dependencies = [ [[package]] name = "reth-rpc-convert" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-json-rpc", @@ -9129,8 +9148,8 @@ dependencies = [ [[package]] name = "reth-rpc-engine-api" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-eips", "alloy-primitives", @@ -9160,8 +9179,8 @@ dependencies = [ [[package]] name = "reth-rpc-eth-api" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-dyn-abi", @@ -9205,8 +9224,8 @@ dependencies = [ [[package]] name = "reth-rpc-eth-types" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-chains", "alloy-consensus", @@ -9235,6 +9254,7 @@ dependencies = [ "reth-ethereum-primitives", "reth-evm", "reth-execution-types", + "reth-lru", "reth-metrics", "reth-primitives-traits", "reth-rpc-convert", @@ -9243,7 +9263,6 @@ dependencies = [ "reth-tasks", "reth-transaction-pool", "reth-trie-common", - "schnellru", "serde", "thiserror 2.0.21", "tokio", @@ -9254,8 +9273,8 @@ dependencies = [ [[package]] name = "reth-rpc-layer" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-rpc-types-engine", "http", @@ -9270,8 +9289,8 @@ dependencies = [ [[package]] name = "reth-rpc-server-types" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-primitives", "alloy-rpc-types-engine", @@ -9299,8 +9318,8 @@ dependencies = [ [[package]] name = "reth-snap-sync" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-eip7928", "alloy-eips", @@ -9330,8 +9349,8 @@ dependencies = [ [[package]] name = "reth-stages" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-eip7928", @@ -9381,8 +9400,8 @@ dependencies = [ [[package]] name = "reth-stages-api" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-eips", "alloy-primitives", @@ -9409,8 +9428,8 @@ dependencies = [ [[package]] name = "reth-stages-types" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-primitives", "arbitrary", @@ -9424,8 +9443,8 @@ dependencies = [ [[package]] name = "reth-static-file" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-primitives", "parking_lot", @@ -9444,8 +9463,8 @@ dependencies = [ [[package]] name = "reth-static-file-types" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-primitives", "clap", @@ -9459,8 +9478,8 @@ dependencies = [ [[package]] name = "reth-storage-api" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-eip7928", @@ -9485,8 +9504,8 @@ dependencies = [ [[package]] name = "reth-storage-errors" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-eips", "alloy-primitives", @@ -9501,8 +9520,8 @@ dependencies = [ [[package]] name = "reth-storage-overlay" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-eips", "alloy-primitives", @@ -9529,8 +9548,8 @@ dependencies = [ [[package]] name = "reth-tasks" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "crossbeam-utils", "dashmap", @@ -9550,24 +9569,23 @@ dependencies = [ [[package]] name = "reth-testing-utils" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-eips", "alloy-genesis", "alloy-primitives", - "rand 0.8.6", "rand 0.9.4", "reth-ethereum-primitives", "reth-primitives-traits", - "secp256k1 0.30.0", + "secp256k1 0.33.1", ] [[package]] name = "reth-tokio-util" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "tokio", "tokio-stream", @@ -9576,8 +9594,8 @@ dependencies = [ [[package]] name = "reth-tracing" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "clap", "eyre", @@ -9593,8 +9611,8 @@ dependencies = [ [[package]] name = "reth-tracing-otlp" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "clap", "eyre", @@ -9603,8 +9621,8 @@ dependencies = [ [[package]] name = "reth-transaction-pool" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-eips", @@ -9628,12 +9646,12 @@ dependencies = [ "reth-evm-ethereum", "reth-execution-types", "reth-fs-util", + "reth-lru", "reth-metrics", "reth-primitives-traits", "reth-storage-api", "reth-tasks", "rustc-hash", - "schnellru", "serde", "serde_json", "smallvec", @@ -9645,8 +9663,8 @@ dependencies = [ [[package]] name = "reth-trie" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-eips", @@ -9672,8 +9690,8 @@ dependencies = [ [[package]] name = "reth-trie-common" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-primitives", @@ -9700,8 +9718,8 @@ dependencies = [ [[package]] name = "reth-trie-db" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-primitives", "reth-db-api", @@ -9716,8 +9734,8 @@ dependencies = [ [[package]] name = "reth-trie-parallel" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-primitives", "crossbeam-channel", @@ -9736,8 +9754,8 @@ dependencies = [ [[package]] name = "reth-trie-sparse" -version = "2.10.1" -source = "git+https://github.com/paradigmxyz/reth?tag=v2.10.1#58ebce14ae63dab040beae301e1578cd0dc55e8a" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-primitives", "alloy-trie", @@ -9972,7 +9990,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -10052,7 +10070,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs 1.0.11", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -10148,17 +10166,6 @@ dependencies = [ "serde_json", ] -[[package]] -name = "schnellru" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "356285bbf17bea63d9e52e96bd18f039672ac92b55b8cb997d6162a2a37d1649" -dependencies = [ - "ahash", - "cfg-if", - "hashbrown 0.13.2", -] - [[package]] name = "scoped-tls" version = "1.0.1" @@ -10502,6 +10509,17 @@ dependencies = [ "keccak 0.2.0", ] +[[package]] +name = "sha3" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc9bad02c26382724b2d2692c6f179285e4b54eeecd7968f52a50059c3c11759" +dependencies = [ + "digest 0.11.3", + "keccak 0.2.0", + "sponge-cursor", +] + [[package]] name = "sha3-asm" version = "0.1.6" @@ -10600,6 +10618,12 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" +[[package]] +name = "similar" +version = "2.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbbb5d9659141646ae647b42fe094daf6c6192d1620870b449d9557f748b2daa" + [[package]] name = "simple_asn1" version = "0.6.4" @@ -10659,7 +10683,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3a766e1110788c36f4fa1c2b71b387a7815aa65f88ce0229841826633d93723e" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -10698,6 +10722,12 @@ dependencies = [ "der 0.8.3", ] +[[package]] +name = "sponge-cursor" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a0219bd7d979d58245a4f41f695e1ac9f8befdffadd7f61f1bae9e39abc6620" + [[package]] name = "stable_deref_trait" version = "1.2.1" @@ -10882,7 +10912,7 @@ dependencies = [ "getrandom 0.4.2", "once_cell", "rustix", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -11546,12 +11576,12 @@ checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" [[package]] name = "universal-hash" -version = "0.5.1" +version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" +checksum = "f4987bdc12753382e0bec4a65c50738ffaabc998b9cdd1f952fb5f39b0048a96" dependencies = [ - "crypto-common 0.1.7", - "subtle", + "crypto-common 0.2.2", + "ctutils", ] [[package]] @@ -11956,7 +11986,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -12599,12 +12629,6 @@ dependencies = [ "rustix", ] -[[package]] -name = "yansi" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049" - [[package]] name = "yoke" version = "0.8.2" @@ -12671,18 +12695,18 @@ dependencies = [ [[package]] name = "zeroize" -version = "1.8.2" +version = "1.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" dependencies = [ "zeroize_derive", ] [[package]] name = "zeroize_derive" -version = "1.4.3" +version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85a5b4158499876c763cb03bc4e49185d3cccbabb15b33c627f7884f43db852e" +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" dependencies = [ "proc-macro2", "quote", diff --git a/Cargo.toml b/Cargo.toml index 9fa1df08..2560633b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -110,75 +110,75 @@ morph-rpc = { path = "crates/rpc" } morph-revm = { path = "crates/revm", default-features = false } morph-txpool = { path = "crates/txpool", default-features = false } -reth-basic-payload-builder = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } -reth-chain-state = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } -reth-chainspec = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } -reth-cli = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } -reth-cli-commands = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } -reth-cli-runner = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } -reth-cli-util = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } +reth-basic-payload-builder = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } +reth-chain-state = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } +reth-chainspec = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } +reth-cli = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } +reth-cli-commands = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } +reth-cli-runner = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } +reth-cli-util = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } reth-codecs = { version = "0.8.2", default-features = false } reth-codecs-derive = "0.8.2" -reth-consensus = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } -reth-consensus-common = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } -reth-db = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } -reth-db-api = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } -reth-e2e-test-utils = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } -reth-engine-local = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } -reth-engine-primitives = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } -reth-engine-tree = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } -reth-errors = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } -reth-exex = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } -reth-exex-test-utils = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } -reth-execution-errors = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } -reth-eth-wire-types = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } -reth-ethereum = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } -reth-ethereum-cli = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } -reth-ethereum-consensus = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } -reth-ethereum-engine-primitives = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } -reth-ethereum-primitives = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1", default-features = false } -reth-evm = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } -reth-evm-ethereum = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } -reth-execution-types = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } -reth-metrics = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } -reth-network-peers = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } -reth-node-api = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } -reth-node-builder = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } -reth-node-core = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } -reth-node-ethereum = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } -reth-node-metrics = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } -reth-payload-builder = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } -reth-payload-primitives = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } -reth-payload-util = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } +reth-consensus = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } +reth-consensus-common = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } +reth-db = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } +reth-db-api = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } +reth-e2e-test-utils = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } +reth-engine-local = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } +reth-engine-primitives = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } +reth-engine-tree = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } +reth-errors = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } +reth-exex = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } +reth-exex-test-utils = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } +reth-execution-errors = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } +reth-eth-wire-types = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } +reth-ethereum = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } +reth-ethereum-cli = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } +reth-ethereum-consensus = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } +reth-ethereum-engine-primitives = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } +reth-ethereum-primitives = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0", default-features = false } +reth-evm = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } +reth-evm-ethereum = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } +reth-execution-types = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } +reth-metrics = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } +reth-network-peers = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } +reth-node-api = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } +reth-node-builder = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } +reth-node-core = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } +reth-node-ethereum = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } +reth-node-metrics = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } +reth-payload-builder = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } +reth-payload-primitives = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } +reth-payload-util = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } reth-primitives-traits = { version = "0.8.2", default-features = false } -reth-prune-types = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } -reth-provider = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } -reth-stages-types = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } -reth-rpc = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } -reth-rpc-api = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } -reth-rpc-builder = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } -reth-rpc-convert = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } -reth-rpc-eth-api = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } -reth-rpc-eth-types = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } -reth-rpc-server-types = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } -reth-storage-api = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } -reth-storage-errors = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1", default-features = false } -reth-storage-overlay = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } -reth-tasks = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } -reth-tracing = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } -reth-trie = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } -reth-trie-common = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } -reth-transaction-pool = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } +reth-prune-types = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } +reth-provider = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } +reth-stages-types = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } +reth-rpc = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } +reth-rpc-api = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } +reth-rpc-builder = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } +reth-rpc-convert = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } +reth-rpc-eth-api = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } +reth-rpc-eth-types = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } +reth-rpc-server-types = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } +reth-storage-api = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } +reth-storage-errors = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0", default-features = false } +reth-storage-overlay = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } +reth-tasks = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } +reth-tracing = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } +reth-trie = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } +reth-trie-common = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } +reth-transaction-pool = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } reth-zstd-compressors = { version = "0.8.2", default-features = false } -reth-execution-cache = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } -reth-trie-parallel = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1" } -reth-trie-sparse = { git = "https://github.com/paradigmxyz/reth", tag = "v2.10.1", default-features = false } +reth-execution-cache = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } +reth-trie-parallel = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } +reth-trie-sparse = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0", default-features = false } -# evm2 has no release yet; this is the rev reth v2.10.1 declares, overridden by the -# `[patch]` below to the rev it actually builds against. -evm2 = { git = "https://github.com/alloy-rs/evm2", rev = "592bf18c4e22fff54ac9b4db606c4ee276e345cb", default-features = false } -evm2-inspectors = { git = "https://github.com/alloy-rs/evm2", rev = "592bf18c4e22fff54ac9b4db606c4ee276e345cb", default-features = false } -evm2-macros = { git = "https://github.com/alloy-rs/evm2", rev = "592bf18c4e22fff54ac9b4db606c4ee276e345cb" } +# evm2 has no release yet; this is the rev reth v2.11.0 declares, overridden by the +# `[patch]` below to match reth's own `[patch]` section. +evm2 = { git = "https://github.com/alloy-rs/evm2", rev = "66687c18b34d3bdbb899f5eb7605070615c03475", default-features = false } +evm2-inspectors = { git = "https://github.com/alloy-rs/evm2", rev = "66687c18b34d3bdbb899f5eb7605070615c03475", default-features = false } +evm2-macros = { git = "https://github.com/alloy-rs/evm2", rev = "66687c18b34d3bdbb899f5eb7605070615c03475" } alloy = { version = "2.5.0", default-features = false } alloy-consensus = { version = "2.5.0", default-features = false } @@ -191,9 +191,7 @@ alloy-network = { version = "2.5.0", default-features = false } alloy-primitives = { version = "1.6.1", default-features = false } alloy-provider = { version = "2.5.0", default-features = false } alloy-rlp = "0.3.16" -# reth v2.10.1's `reth-trie-common` builds `HashBuilder` with a struct literal, which 0.9.9 -# breaks by adding a field. -alloy-trie = "=0.9.8" +alloy-trie = "0.9.9" alloy-rpc-types-debug = "2.5.0" alloy-rpc-types-engine = "2.5.0" alloy-rpc-types-eth = { version = "2.5.0" } @@ -255,15 +253,16 @@ test-case = "3" pyroscope = "0.5.8" pyroscope_pprofrs = "0.2.10" -# Patches only take effect at the root workspace, so reth v2.10.1's own overrides are +# Patches only take effect at the root workspace, so reth v2.11.0's own overrides are # repeated here. Keep both sections identical to the `[patch]` sections of the pinned reth # tag; a drifted rev compiles a second, incompatible copy of these crates. # -# Cargo requires a distinct patch source URL; www.github.com redirects to the public repository. +# Cargo requires a distinct patch source URL; DaniPopes/evm2 is the pre-transfer URL reth +# v2.11.0 uses and redirects to the public repository. [patch."https://github.com/alloy-rs/evm2"] -evm2 = { git = "https://www.github.com/alloy-rs/evm2", rev = "01df8f6a396d0250da286cb763faa6ec292d65b5" } -evm2-inspectors = { git = "https://www.github.com/alloy-rs/evm2", rev = "01df8f6a396d0250da286cb763faa6ec292d65b5" } -evm2-macros = { git = "https://www.github.com/alloy-rs/evm2", rev = "01df8f6a396d0250da286cb763faa6ec292d65b5" } +evm2 = { git = "https://github.com/DaniPopes/evm2", rev = "66687c18b34d3bdbb899f5eb7605070615c03475" } +evm2-inspectors = { git = "https://github.com/DaniPopes/evm2", rev = "66687c18b34d3bdbb899f5eb7605070615c03475" } +evm2-macros = { git = "https://github.com/DaniPopes/evm2", rev = "66687c18b34d3bdbb899f5eb7605070615c03475" } [patch.crates-io] reth-codecs = { git = "https://github.com/paradigmxyz/reth-core", rev = "275ce4cf5befeb9f1e8acd935ff2882d2d25fc61" } diff --git a/bin/morph-statetest/src/schema.rs b/bin/morph-statetest/src/schema.rs index 4033b995..c85b3b68 100644 --- a/bin/morph-statetest/src/schema.rs +++ b/bin/morph-statetest/src/schema.rs @@ -3,12 +3,11 @@ use alloy_primitives::{Address, B256, Bytes, TxKind, U256}; use alloy_signer_local::PrivateKeySigner; use evm2::{ bytecode::Bytecode, - ethereum::LazyAuthorization, evm::{AccountInfo, InMemoryDB}, }; use morph_chainspec::hardfork::MorphHardfork; use morph_primitives::transaction::morph_transaction::MORPH_TX_VERSION_2; -use morph_revm::{MorphBlockEnv, MorphTxEnv, MorphTxExt}; +use morph_revm::{MorphAuthorization, MorphBlockEnv, MorphTxEnv, MorphTxExt}; use serde::{Deserialize, Deserializer, de}; use std::collections::BTreeMap; use thiserror::Error; @@ -320,7 +319,7 @@ impl MorphTransactionParts { .map(|auth_list| { auth_list .into_iter() - .map(|auth| LazyAuthorization::Signed(auth.0)) + .map(|auth| MorphAuthorization::Signed(auth.0)) .collect() }) .unwrap_or_default(); diff --git a/crates/evm/src/block/mod.rs b/crates/evm/src/block/mod.rs index 2eba5d1b..1c2a384c 100644 --- a/crates/evm/src/block/mod.rs +++ b/crates/evm/src/block/mod.rs @@ -14,7 +14,7 @@ use crate::evm::MorphEvm; use alloy_consensus::{Transaction, transaction::TxHashRef}; use alloy_eip7928::{BlockAccessIndex, BlockAccessList}; use alloy_primitives::{Address, B256}; -use evm2::{TxResultWithState, evm::Bal, registry::HandlerError}; +use evm2::{AnyError, TxResultWithState, evm::Bal, registry::HandlerError}; use morph_primitives::{MorphReceipt, MorphTxEnvelope, MorphTxType}; use morph_revm::{ L1_GAS_PRICE_ORACLE_ADDRESS, MorphEvmTypes, MorphInvalidTransaction, TokenFeeInfo, @@ -49,11 +49,15 @@ impl InvalidTxError for MorphInvalidTxError { self.0, HandlerError::GasLimitMoreThanBlock { .. } | HandlerError::TxGasLimitGreaterThanCap { .. } + | HandlerError::IntrinsicGasGreaterThanCap { .. } ) } fn is_gas_limit_too_low(&self) -> bool { - matches!(self.0, HandlerError::IntrinsicGasTooLow { .. }) + matches!( + self.0, + HandlerError::IntrinsicGasTooLow { .. } | HandlerError::GasLimitBelowFloor { .. } + ) } /// Exposes the wrapped [`HandlerError`] so RPC layers can recover the structured error. @@ -72,7 +76,7 @@ fn map_transaction_error(error: HandlerError, hash: B256) -> BlockExecutionError HandlerError::Database(ref database_error) if !database_error.is_fatal() => { BlockValidationError::EVM { hash, - error: Box::new(error), + error: AnyError::new(error), } .into() } @@ -80,7 +84,7 @@ fn map_transaction_error(error: HandlerError, hash: B256) -> BlockExecutionError | HandlerError::Fatal(_) | HandlerError::WrongTransactionType { .. } => InternalBlockExecutionError::EVM { hash, - error: Box::new(error), + error: AnyError::new(error), } .into(), error => BlockValidationError::InvalidTx { @@ -93,14 +97,16 @@ fn map_transaction_error(error: HandlerError, hash: B256) -> BlockExecutionError /// Returns the Morph error carried by a block execution error, if there is one. pub fn morph_invalid_tx_error(error: &BlockExecutionError) -> Option<&MorphInvalidTransaction> { - let BlockExecutionError::Validation(BlockValidationError::InvalidTx { error, .. }) = error - else { - return None; + let handler_error = match error { + BlockExecutionError::Validation(BlockValidationError::InvalidTx { error, .. }) => { + error.as_any().downcast_ref::()? + } + BlockExecutionError::Validation(BlockValidationError::Other(error)) => { + error.downcast_ref::()? + } + _ => return None, }; - error - .as_any() - .downcast_ref::()? - .external_ref::() + handler_error.external_ref::() } /// The fields a receipt needs from the transaction itself. @@ -128,6 +134,10 @@ impl BlockTransactionResult for MorphTxResult { fn result(&self) -> &TxResultWithState { &self.result } + + fn into_result(self) -> TxResultWithState { + self.result + } } /// Block executor for Morph L2 blocks. @@ -475,7 +485,7 @@ mod tests { use morph_chainspec::{MorphChainSpec, hardfork::MorphHardfork}; use morph_primitives::TxL1Msg; use morph_revm::{MorphBlockEnv, MorphTxEnv, morph_evm_env}; - use reth_evm::{BlockExecutorFactory, ExecutableTxParts}; + use reth_evm::BlockExecutorFactory; use reth_primitives_traits::Recovered; const SENDER: Address = Address::with_last_byte(0xaa); @@ -519,7 +529,7 @@ mod tests { /// A signed transaction ready for the executor. fn executable( tx: MorphTxEnvelope, - ) -> impl ExecutableTxParts, MorphTxEnvelope> { + ) -> reth_evm::WithTxEnv, Recovered> { reth_evm::WithTxEnv { tx_env: Recovered::new_unchecked(MorphTxEnv::from_envelope(&tx), SENDER), tx: Arc::new(Recovered::new_unchecked(tx, SENDER)), @@ -673,6 +683,13 @@ mod tests { morph_invalid_tx_error(&error), Some(&MorphInvalidTransaction::TokenNotActive(3)) ); + + let direct_error = + evm2::block::map_handler_error(MorphInvalidTransaction::TokenNotActive(3).into()); + assert_eq!( + morph_invalid_tx_error(&direct_error), + Some(&MorphInvalidTransaction::TokenNotActive(3)) + ); } #[test] @@ -699,4 +716,162 @@ mod tests { let executor = config.create_executor(evm, ctx); assert!(executor.receipts().is_empty()); } + + #[test] + fn invalid_tx_error_classifies_gas_limit_bounds() { + for err in [ + HandlerError::IntrinsicGasTooLow { + required: 21_000, + got: 20_000, + }, + HandlerError::GasLimitBelowFloor { + required: 25_000, + got: 21_000, + }, + ] { + let wrapped = MorphInvalidTxError(err); + assert!(wrapped.is_gas_limit_too_low(), "{wrapped:?}"); + assert!(!wrapped.is_gas_limit_too_high(), "{wrapped:?}"); + } + + for err in [ + HandlerError::GasLimitMoreThanBlock { + gas_limit: 31_000_000, + block_gas_limit: U256::from(30_000_000), + }, + HandlerError::TxGasLimitGreaterThanCap { + gas_limit: 31_000_000, + cap: 30_000_000, + }, + HandlerError::IntrinsicGasGreaterThanCap { + required: 31_000_000, + cap: 30_000_000, + }, + ] { + let wrapped = MorphInvalidTxError(err); + assert!(wrapped.is_gas_limit_too_high(), "{wrapped:?}"); + assert!(!wrapped.is_gas_limit_too_low(), "{wrapped:?}"); + } + } + + #[test] + fn inspect_transaction_without_commit_returns_inspector_and_hides_fee_frames() { + use evm2::{ + Inspector, + bytecode::Bytecode, + interpreter::{Interpreter, Message, MessageResult}, + }; + use morph_primitives::TxMorph; + use morph_revm::{L2_TOKEN_REGISTRY_ADDRESS, compute_mapping_slot}; + + #[derive(Debug, Default)] + struct CallCounter(usize); + + impl Inspector for CallCounter { + fn call( + &mut self, + _interp: &mut Interpreter<'_, '_, MorphEvmTypes>, + _message: &mut Message, + ) -> Option> { + self.0 += 1; + None + } + } + + // Call-mode ERC20: `balanceOf` and `transfer` run real EVM frames during fee deduction + // and reimbursement, which `FeeFrameFilter` must hide from `inspect_transaction_without_commit`. + let token = Address::with_last_byte(0xcc); + let erc20_code = Bytes::from_static(&[ + 0x36, 0x60, 0x44, 0x14, 0x60, 0x13, 0x57, 0x60, 0x04, 0x35, 0x54, 0x60, 0x00, 0x52, + 0x60, 0x20, 0x60, 0x00, 0xf3, 0x5b, 0x60, 0x24, 0x35, 0x80, 0x33, 0x54, 0x03, 0x33, + 0x55, 0x60, 0x04, 0x35, 0x80, 0x54, 0x82, 0x01, 0x90, 0x55, 0x50, 0x60, 0x01, 0x60, + 0x00, 0x52, 0x60, 0x20, 0x60, 0x00, 0xf3, + ]); + + let mut db = InMemoryDB::default(); + db.insert_account_info(&SENDER, AccountInfo::default()); + db.insert_account_info( + &token, + AccountInfo::default().with_code(Bytecode::new_legacy(erc20_code)), + ); + db.insert_account_storage( + &token, + &U256::from_be_bytes(SENDER.into_word().0), + &U256::from(1_000_000u64), + ); + + let token_id = 1u16; + let mut token_id_bytes = [0u8; 32]; + token_id_bytes[30..32].copy_from_slice(&token_id.to_be_bytes()); + let base = compute_mapping_slot(U256::from(151), &token_id_bytes); + db.insert_account_storage( + &L2_TOKEN_REGISTRY_ADDRESS, + &base, + &U256::from_be_bytes(token.into_word().0), + ); + let mut status = [0u8; 32]; + status[30] = 18; + status[31] = 1; + db.insert_account_storage( + &L2_TOKEN_REGISTRY_ADDRESS, + &(base + U256::from(2)), + &U256::from_be_bytes(status), + ); + db.insert_account_storage( + &L2_TOKEN_REGISTRY_ADDRESS, + &(base + U256::from(3)), + &U256::from(1), + ); + db.insert_account_storage( + &L2_TOKEN_REGISTRY_ADDRESS, + &compute_mapping_slot(U256::from(153), &token_id_bytes), + &U256::from(1), + ); + + let evm = MorphEvm::new( + db, + morph_evm_env( + MorphHardfork::default(), + 1337, + 30_000_000, + MorphBlockEnv { + basefee: U256::from(1), + gas_limit: U256::from(30_000_000), + beneficiary: Address::with_last_byte(0xbe), + ..Default::default() + }, + ), + ); + let mut executor = MorphBlockExecutor::new(evm, DefaultMorphReceiptBuilder, None); + + let morph_tx = MorphTxEnvelope::Morph(Signed::new_unhashed( + TxMorph { + chain_id: 1337, + nonce: 0, + gas_limit: 50_000, + max_fee_per_gas: 2, + max_priority_fee_per_gas: 1, + to: TxKind::Call(TARGET), + value: U256::ZERO, + access_list: Default::default(), + version: 1, + fee_token_id: token_id, + fee_limit: U256::from(1_000_000u64), + reference: None, + memo: None, + input: Bytes::new(), + authorization_list: Vec::new(), + }, + Signature::test_signature(), + )); + + let (inspector, output) = executor + .inspect_transaction_without_commit(executable(morph_tx), CallCounter::default()) + .unwrap(); + assert!(output.result().result.status); + // Only the user's top-level call to `TARGET` is observed; the fee-token `balanceOf` and + // `transfer` frames stay hidden. + assert_eq!(inspector.0, 1); + assert!(reth_evm::Evm::take_inspector(executor.evm_mut()).is_none()); + } } diff --git a/crates/evm/src/evm.rs b/crates/evm/src/evm.rs index d6940d73..a32550ca 100644 --- a/crates/evm/src/evm.rs +++ b/crates/evm/src/evm.rs @@ -1,10 +1,12 @@ //! Morph EVM instance and factory. use alloy_consensus::transaction::Recovered; -use alloy_primitives::Address; +use alloy_primitives::{Address, Log, U256}; +use core::any::TypeId; use evm2::{ - ExecutedTx, Inspector, TxResult, TxResultWithState, - evm::{AccountInfo, Cache, DynDatabase, PendingState}, + ExecutedTx, Inspector, InspectorConfig, TxResult, TxResultWithState, + evm::{AccountInfo, Cache, DynDatabase, NonStaticAny, PendingState}, + interpreter::{Interpreter, Message, MessageResult}, precompiles::{MovePrecompileError, PrecompileId}, }; use morph_revm::{FeeFrameFilter, MorphEvmEnv, MorphEvmTypes, MorphTxEnv}; @@ -16,6 +18,103 @@ use std::ops::{Deref, DerefMut}; #[non_exhaustive] pub struct MorphEvmFactory; +/// Private wrapper installed only by [`MorphEvm::set_inspector`] around a `'static` inspector. +/// +/// Keeping construction private to this module (and gated on `I: 'static`) makes downcasting a +/// lifetime-erased `dyn Inspector + 'a` back to `InstalledInspector` unconditionally sound even +/// if callers replace the inner inspector via [`DerefMut`]. +#[derive(Debug)] +struct InstalledInspector(FeeFrameFilter); + +impl> Inspector for InstalledInspector { + #[inline] + fn inspector_config(&self) -> InspectorConfig { + self.0.inspector_config() + } + + fn initialize_interp(&mut self, interp: &mut Interpreter<'_, '_, MorphEvmTypes>) { + self.0.initialize_interp(interp); + } + + fn step(&mut self, interp: &mut Interpreter<'_, '_, MorphEvmTypes>) { + self.0.step(interp); + } + + fn step_end(&mut self, interp: &mut Interpreter<'_, '_, MorphEvmTypes>) { + self.0.step_end(interp); + } + + fn log(&mut self, log: &Log, host: &mut morph_revm::MorphEvm<'_>) { + self.0.log(log, host); + } + + fn call( + &mut self, + interp: &mut Interpreter<'_, '_, MorphEvmTypes>, + message: &mut Message, + ) -> Option> { + self.0.call(interp, message) + } + + fn call_end( + &mut self, + interp: &mut Interpreter<'_, '_, MorphEvmTypes>, + message: &Message, + result: &mut MessageResult, + ) { + self.0.call_end(interp, message, result); + } + + fn create( + &mut self, + interp: &mut Interpreter<'_, '_, MorphEvmTypes>, + message: &mut Message, + ) -> Option> { + self.0.create(interp, message) + } + + fn create_end( + &mut self, + interp: &mut Interpreter<'_, '_, MorphEvmTypes>, + message: &Message, + result: &mut MessageResult, + ) { + self.0.create_end(interp, message, result); + } + + fn selfdestruct( + &mut self, + contract: &Address, + target: &Address, + value: &U256, + host: &mut morph_revm::MorphEvm<'_>, + ) { + self.0.selfdestruct(contract, target, value, host); + } +} + +type UnwrapInspectorFn<'a> = + fn(&mut morph_revm::MorphEvm<'a>) -> Option + 'a>>; + +fn unwrap_installed_inspector<'a, I>( + evm: &mut morph_revm::MorphEvm<'a>, +) -> Option + 'a>> +where + I: Inspector + 'static, +{ + let inspector = evm.clear_inspector()?; + let erased: &dyn NonStaticAny = &*inspector; + if erased.type_id() != TypeId::of::>() { + return Some(inspector); + } + // SAFETY: `erased.type_id()` matches `InstalledInspector`, and only + // `MorphEvm::set_inspector` constructs `InstalledInspector`, always around a `'static` + // inspector `I`, so the boxed value is an `InstalledInspector` and no borrow is extended. + let installed = + unsafe { Box::from_raw(Box::into_raw(inspector).cast::>()) }; + Some(Box::new(installed.0.into_inner())) +} + /// A configured Morph EVM. /// /// Wraps the evm2 instance so that every inspector installed on it goes through @@ -23,6 +122,7 @@ pub struct MorphEvmFactory; #[expect(missing_debug_implementations)] pub struct MorphEvm<'a> { inner: morph_revm::MorphEvm<'a>, + unwrap_inspector: Option>, } impl<'a> MorphEvm<'a> { @@ -30,6 +130,7 @@ impl<'a> MorphEvm<'a> { pub fn new(database: impl DynDatabase + 'a, env: MorphEvmEnv) -> Self { Self { inner: morph_revm::morph_evm(database, env), + unwrap_inspector: None, } } } @@ -43,6 +144,9 @@ impl<'a> Deref for MorphEvm<'a> { } } +/// Install inspectors through [`reth_evm::Evm::set_inspector`] rather than calling +/// [`evm2::Evm::set_inspector`] on the dereferenced inner EVM directly so [`FeeFrameFilter`] hides +/// internal ERC-20 fee frames. impl DerefMut for MorphEvm<'_> { #[inline] fn deref_mut(&mut self) -> &mut Self::Target { @@ -83,6 +187,7 @@ impl<'a> Evm for MorphEvm<'a> { where I: Inspector + 'static, { + self.unwrap_inspector = None; let (filter, result) = Evm::transact_with_inspector( &mut self.inner, transaction, @@ -95,7 +200,43 @@ impl<'a> Evm for MorphEvm<'a> { where I: Inspector + 'static, { - Evm::set_inspector(&mut self.inner, FeeFrameFilter::new(inspector)); + Evm::set_inspector( + &mut self.inner, + InstalledInspector(FeeFrameFilter::new(inspector)), + ); + self.unwrap_inspector = Some(unwrap_installed_inspector::); + } + + unsafe fn with_inspector(&mut self, f: impl FnOnce(&mut I) -> R) -> Option + where + I: Inspector + 'static, + { + let inspector: &mut (dyn NonStaticAny + 'a) = &mut **self.inner.inspector_mut()?; + let type_id = NonStaticAny::type_id(inspector); + if type_id == TypeId::of::>() { + // SAFETY: `type_id` matches `InstalledInspector`, and only `MorphEvm::set_inspector` + // constructs `InstalledInspector`, always around `I: 'static`. + let installed = unsafe { inspector.downcast_mut_unchecked::>() }; + Some(f(installed.0.inner_mut())) + } else if type_id == TypeId::of::>() { + // SAFETY: `type_id` matches `FeeFrameFilter`, and the caller guarantees `I` has no + // lifetime parameters, so `FeeFrameFilter` has no lifetime parameters either. + let filter = unsafe { inspector.downcast_mut_unchecked::>() }; + Some(f(filter.inner_mut())) + } else if type_id == TypeId::of::() { + // SAFETY: `type_id` matches `I`, and the caller guarantees `I` has no lifetime + // parameters. + Some(f(unsafe { inspector.downcast_mut_unchecked::() })) + } else { + None + } + } + + fn take_inspector(&mut self) -> Option + '_>> { + match self.unwrap_inspector.take() { + Some(unwrap) => unwrap(&mut self.inner), + None => Evm::take_inspector(&mut self.inner), + } } fn state_db_mut(&mut self) -> &mut dyn DynDatabase { @@ -182,4 +323,94 @@ mod tests { assert!(result.result.status); } + + #[test] + fn set_inspector_supports_with_inspector_and_take_inspector() { + #[derive(Debug, Default)] + struct CallCounter(usize); + + impl Inspector for CallCounter { + fn call( + &mut self, + _interp: &mut Interpreter<'_, '_, MorphEvmTypes>, + _message: &mut Message, + ) -> Option> { + self.0 += 1; + None + } + } + + let mut db = InMemoryDB::default(); + db.insert_account_info( + &Address::ZERO, + AccountInfo::default().with_balance(U256::from(1_000_000)), + ); + let env = morph_evm_env( + MorphHardfork::default(), + 1, + 30_000_000, + MorphBlockEnv { + basefee: U256::from(1), + ..Default::default() + }, + ); + let mut evm = MorphEvm::new(db, env); + Evm::set_inspector(&mut evm, CallCounter(0)); + + let tx = Recovered::new_unchecked( + MorphTxEnv { + gas_price: 1, + gas_limit: 21_000, + kind: TxKind::Call(Address::with_last_byte(0xff)), + ..Default::default() + }, + Address::ZERO, + ); + Evm::transact(&mut evm, &tx).unwrap(); + + let count = unsafe { Evm::with_inspector::(&mut evm, |i| i.0) }; + assert_eq!(count, Some(1)); + assert_eq!( + unsafe { Evm::with_inspector::(&mut evm, |_| ()) }, + None + ); + + let taken = Evm::take_inspector(&mut evm).expect("inspector was installed"); + let erased: &dyn NonStaticAny = &*taken; + assert_eq!(erased.type_id(), TypeId::of::()); + drop(taken); + assert!(Evm::take_inspector(&mut evm).is_none()); + } + + #[test] + fn take_inspector_remains_sound_after_deref_mut_replacement() { + #[expect(dead_code)] + struct BorrowedInspector<'a>(&'a usize); + + impl Inspector for BorrowedInspector<'_> {} + + let static_val: &'static usize = &42; + let local_val = 7usize; + + let env = morph_evm_env( + MorphHardfork::default(), + 1, + 30_000_000, + MorphBlockEnv::default(), + ); + let mut evm = MorphEvm::new(InMemoryDB::default(), env); + + Evm::set_inspector(&mut evm, BorrowedInspector(static_val)); + // Replace the inner inspector via DerefMut with a non-'static FeeFrameFilter wrapping the + // same generic type with a shorter borrow. + evm.deref_mut() + .set_inspector(FeeFrameFilter::new(BorrowedInspector(&local_val))); + + let taken = Evm::take_inspector(&mut evm).expect("replacement inspector stays present"); + let erased: &dyn NonStaticAny = &*taken; + assert_eq!( + erased.type_id(), + TypeId::of::>>() + ); + } } diff --git a/crates/revm/src/evm.rs b/crates/revm/src/evm.rs index eb8c4dce..83688a8c 100644 --- a/crates/revm/src/evm.rs +++ b/crates/revm/src/evm.rs @@ -151,7 +151,7 @@ fn morph_blockhash_result(chain_id: u64, current_number: u64, requested_number: pub fn morph_blockhash(cx: _, [number]: [Word]) -> out { let requested_number = number.saturating_to::(); let current_number = cx.state.host().block().number.saturating_to::(); - let chain_id = cx.state.tx().chain_id.saturating_to::(); + let chain_id = cx.state.host().tx_env().chain_id.saturating_to::(); *out = morph_blockhash_result(chain_id, current_number, requested_number); } @@ -228,9 +228,23 @@ impl FeeFrameFilter { pub const fn inner(&self) -> &I { &self.inner } + + /// Returns a mutable reference to the wrapped inspector. + pub const fn inner_mut(&mut self) -> &mut I { + &mut self.inner + } } impl> Inspector for FeeFrameFilter { + #[inline] + fn inspector_config(&self) -> evm2::InspectorConfig { + if self.in_fee_frame { + evm2::InspectorConfig::without_steps() + } else { + self.inner.inspector_config() + } + } + fn initialize_interp(&mut self, interp: &mut Interpreter<'_, '_, MorphEvmTypes>) { if !self.in_fee_frame { self.inner.initialize_interp(interp); @@ -468,4 +482,33 @@ mod tests { ); } } + + #[test] + fn fee_frame_filter_forwards_inspector_config() { + struct NoSteps; + impl Inspector for NoSteps { + fn inspector_config(&self) -> evm2::InspectorConfig { + evm2::InspectorConfig::without_steps() + } + } + + assert_eq!( + Inspector::::inspector_config(&FeeFrameFilter::new(NoSteps)), + evm2::InspectorConfig::without_steps(), + ); + + struct AllSteps; + impl Inspector for AllSteps {} + + let mut all_steps = FeeFrameFilter::new(AllSteps); + assert_eq!( + Inspector::::inspector_config(&all_steps), + evm2::InspectorConfig::new(), + ); + all_steps.in_fee_frame = true; + assert_eq!( + Inspector::::inspector_config(&all_steps), + evm2::InspectorConfig::without_steps(), + ); + } } diff --git a/crates/revm/src/handler.rs b/crates/revm/src/handler.rs index 535196df..ed6fbfd1 100644 --- a/crates/revm/src/handler.rs +++ b/crates/revm/src/handler.rs @@ -17,7 +17,7 @@ use alloy_primitives::{Address, B256, Bytes, U256}; use evm2::{ EvmFeatures, SpecId, TxResult, bytecode::Bytecode, - env::{TxEnv, TxEnvExt}, + env::TxEnvExt, ethereum::{ access_list_counts, eip7702::{AuthRefunds, apply_auth_list, eip7702_authorization_gas}, @@ -133,7 +133,6 @@ pub struct PreparedMorphTx { floor_gas: u64, /// The sender's nonce before this transaction bumped it, which names a created contract. sender_nonce: u64, - tx_env: TxEnv, l1_data_fee: U256, token_fee: Option, } @@ -146,10 +145,11 @@ fn prepare(req: &mut MorphTxRequest<'_, '_>) -> HandlerResult { let basefee = host.block().basefee.saturating_to::(); let gas_price = U256::from(tx.effective_gas_price_at(basefee)); - let tx_env = TxEnvExt { + let chain_id = host.version().chain_id; + *host.tx_env_mut() = TxEnvExt { origin: caller, gas_price, - chain_id: U256::from(host.version().chain_id), + chain_id: U256::from(chain_id), ..TxEnvExt::default() }; @@ -165,7 +165,6 @@ fn prepare(req: &mut MorphTxRequest<'_, '_>) -> HandlerResult { intrinsic: intrinsic.min(tx.gas_limit), floor_gas: 0, sender_nonce, - tx_env, l1_data_fee: U256::ZERO, token_fee: None, }); @@ -178,7 +177,7 @@ fn prepare(req: &mut MorphTxRequest<'_, '_>) -> HandlerResult { let token_id = tx.fee_token_id.unwrap_or_default(); let charged = if tx.is_morph_tx() && token_id > 0 { - deduct_token_fee(host, tx, caller, &tx_env, token_id)? + deduct_token_fee(host, tx, caller, gas_price, token_id)? } else { deduct_eth_fee(host, tx, caller)? }; @@ -190,7 +189,6 @@ fn prepare(req: &mut MorphTxRequest<'_, '_>) -> HandlerResult { intrinsic, floor_gas, sender_nonce: charged.sender_nonce, - tx_env, l1_data_fee: charged.l1_data_fee, token_fee: charged.token_fee, }) @@ -207,7 +205,6 @@ fn execute( intrinsic, floor_gas, sender_nonce, - tx_env, l1_data_fee, token_fee, } = prepared; @@ -229,14 +226,8 @@ fn execute( tx.value, &mut tx_gas, )?; - let mut result = execute_initial_frame( - host, - &tx_env, - frame, - &mut tx_gas, - execution_gas_limit, - reservoir, - )?; + let mut result = + execute_initial_frame(host, frame, &mut tx_gas, execution_gas_limit, reservoir)?; if tx.is_l1_msg() { // L1 messages follow go-ethereum: no gas refund, so gas used is the gas consumed. @@ -253,7 +244,7 @@ fn execute( let unused_gas = tx.gas_limit.saturating_sub(output.tx_gas_used()); match token_fee { - Some(fee) => reimburse_token_fee(host, &tx_env, caller, gas_price, unused_gas, fee)?, + Some(fee) => reimburse_token_fee(host, caller, gas_price, unused_gas, fee)?, // A token-fee transaction that charged nothing (fee charging is disabled) has // nothing to reimburse or pay out, in either asset. None if tx.uses_token_fee() => {} @@ -525,7 +516,7 @@ fn deduct_token_fee( host: &mut MorphEvm<'_>, tx: &MorphTxEnv, caller: Address, - tx_env: &TxEnv, + gas_price: U256, token_id: u16, ) -> HandlerResult { // Token ID 0 means ETH — routed through deduct_eth_fee instead. @@ -568,7 +559,7 @@ fn deduct_token_fee( }); } - let token_fee_info = load_token_fee_info(host, tx_env, token_registry_entry, caller)?; + let token_fee_info = load_token_fee_info(host, token_registry_entry, caller)?; let beneficiary = host.block().beneficiary; let fee_limit_from_tx = tx.fee_limit.unwrap_or_default(); @@ -579,7 +570,7 @@ fn deduct_token_fee( // Calculate L2 gas fee using effective_gas_price (= min(gasTipCap + baseFee, gasFeeCap)), // matching go-ethereum's buyAltTokenGas() which uses st.gasPrice (effective gas price). // Using the max fee would overcharge when tip + basefee < feeCap. - let l2_gas_fee = U256::from(tx.gas_limit).saturating_mul(tx_env.gas_price); + let l2_gas_fee = U256::from(tx.gas_limit).saturating_mul(gas_price); // Total fee in ETH let total_eth_fee = l2_gas_fee.saturating_add(l1_data_fee); @@ -619,7 +610,6 @@ fn deduct_token_fee( // Transfer with evm call (from=caller, balance known from token registry). refund_counter = transfer_erc20_with_evm( host, - tx_env, caller, beneficiary, token_fee_info.token_address, @@ -675,7 +665,6 @@ fn cool_loaded_state(state: &mut State<'_>) { /// price_ratio/scale, matching go-ethereum's `st.feeRate`/`st.tokenScale`. fn reimburse_token_fee( host: &mut MorphEvm<'_>, - tx_env: &TxEnv, caller: Address, gas_price: U256, unused_gas: u64, @@ -728,7 +717,6 @@ fn reimburse_token_fee( } else { transfer_erc20_with_evm( host, - tx_env, beneficiary, caller, info.token_address, @@ -841,7 +829,6 @@ fn internal_call_code(host: &mut MorphEvm<'_>, address: Address) -> HandlerResul /// because the token's return value or balance delta fails a later business check. fn evm_call( host: &mut MorphEvm<'_>, - tx_env: &TxEnv, caller: Address, target: Address, calldata: Bytes, @@ -860,7 +847,7 @@ fn evm_call( } else { MessageKind::Call }, - depth: host.version().initial_call_depth, + depth: host.initial_call_depth(), gas_limit: EVM_CALL_GAS_LIMIT, reservoir: 0, destination: target, @@ -876,20 +863,18 @@ fn evm_call( ext: MorphMessageExt { fee_frame: true }, _non_exhaustive: (), }; - Ok(host.execute_message(tx_env, &mut message)?) + Ok(host.execute_message(&mut message)?) } /// Queries the token using a genuine static frame, as geth's StaticCall does. /// Successful reads retain access-list warming; writes and malformed results fail. pub(crate) fn evm_call_balance_of( host: &mut MorphEvm<'_>, - tx_env: &TxEnv, token: Address, account: Address, ) -> HandlerResult { let result = evm_call( host, - tx_env, account, token, encode_balance_of_calldata(account), @@ -908,7 +893,6 @@ pub(crate) fn evm_call_balance_of( /// `msg.sender`. fn load_token_fee_info( host: &mut MorphEvm<'_>, - tx_env: &TxEnv, entry: TokenRegistryEntry, caller: Address, ) -> HandlerResult { @@ -925,7 +909,7 @@ fn load_token_fee_info( slot, )? } - None => evm_call_balance_of(host, tx_env, entry.token_address(), caller)?, + None => evm_call_balance_of(host, entry.token_address(), caller)?, }; Ok(entry.into_fee_info(caller, balance)) } @@ -941,7 +925,6 @@ fn load_token_fee_info( /// carries it into transaction gas accounting, while reimbursement ignores it. fn transfer_erc20_with_evm( host: &mut MorphEvm<'_>, - tx_env: &TxEnv, from: Address, to: Address, token_address: Address, @@ -954,7 +937,7 @@ fn transfer_erc20_with_evm( // Read sender balance before transfer if not provided. let from_balance_before = match from_balance_before { Some(balance) => balance, - None => evm_call_balance_of(host, tx_env, token_address, from)?, + None => evm_call_balance_of(host, token_address, from)?, }; // Geth checks affordability before executing the token contract. @@ -967,7 +950,7 @@ fn transfer_erc20_with_evm( })?; let calldata = build_transfer_calldata(to, token_amount); - let result = evm_call(host, tx_env, from, token_address, calldata, false)?; + let result = evm_call(host, from, token_address, calldata, false)?; if !result.stop.is_success() { return Err(MorphInvalidTransaction::TokenTransferFailed { @@ -989,7 +972,7 @@ fn transfer_erc20_with_evm( } // Verify sender balance changed by the expected amount, matching go-ethereum. - let from_balance_after = evm_call_balance_of(host, tx_env, token_address, from)?; + let from_balance_after = evm_call_balance_of(host, token_address, from)?; // Verify sender balance decreased by exactly the transfer amount. // Matches go-ethereum's transferAltTokenByEVM which always checks this, @@ -1085,7 +1068,9 @@ mod tests { L2_TOKEN_REGISTRY_ADDRESS, compute_mapping_slot, tests::{UnreadableTokenDb, is_token_read_failure}, }; - use crate::{MorphBlockEnv, MorphEvmEnv, evm::morph_evm, evm::morph_evm_env}; + use crate::{ + MorphAuthorization, MorphBlockEnv, MorphEvmEnv, evm::morph_evm, evm::morph_evm_env, + }; use alloy_consensus::transaction::Recovered; use alloy_eips::eip7702::{ Authorization, RecoveredAuthority, RecoveredAuthorization, SignedAuthorization, @@ -1093,7 +1078,6 @@ mod tests { use alloy_primitives::{Log, TxKind, address, b256}; use evm2::{ Inspector, - ethereum::LazyAuthorization, evm::{AccountInfo, Database, Db, DynDatabase, InMemoryDB}, interpreter::Interpreter, version::GasId, @@ -1122,12 +1106,14 @@ mod tests { evm_on(InMemoryDB::default(), spec, MorphBlockEnv::default()) } - /// A transaction environment with `origin` and no gas price. - fn tx_env_of(origin: Address) -> TxEnv { - TxEnvExt { + /// Installs a transaction environment on `evm` with `origin` and zero gas price. + fn set_tx_env(evm: &mut MorphEvm<'_>, origin: Address) { + let chain_id = evm.version().chain_id; + *evm.tx_env_mut() = TxEnvExt { origin, + chain_id: U256::from(chain_id), ..TxEnvExt::default() - } + }; } fn insert_contract(db: &mut InMemoryDB, address: Address, code: Bytes) { @@ -1179,9 +1165,9 @@ mod tests { ..Default::default() }; let mut evm = evm_on(database, MorphHardfork::Emerald, block); + set_tx_env(&mut evm, caller); reimburse_token_fee( &mut evm, - &tx_env_of(caller), caller, U256::from(1), 1_000, @@ -1243,9 +1229,9 @@ mod tests { MorphHardfork::Emerald, MorphBlockEnv::default(), ); + set_tx_env(&mut evm, from); let error = transfer_erc20_with_evm( &mut evm, - &tx_env_of(from), from, to, token, @@ -1326,7 +1312,8 @@ mod tests { ) .unwrap() .unwrap(); - load_token_fee_info(&mut evm, &tx_env_of(caller), entry, caller) + set_tx_env(&mut evm, caller); + load_token_fee_info(&mut evm, entry, caller) .unwrap() .balance } @@ -1433,11 +1420,12 @@ mod tests { token_id: u16, ) -> HandlerResult { let mut evm = morph_evm(database, simulation_env()); + set_tx_env(&mut evm, caller); deduct_token_fee( &mut evm, &token_fee_simulation_tx(token_id), caller, - &tx_env_of(caller), + U256::ZERO, token_id, ) } @@ -1472,7 +1460,7 @@ mod tests { // MorphTx V2 (EIP-7702 authorization list) handler rules // ========================================================================= - fn sample_signed_authorization() -> LazyAuthorization { + fn sample_signed_authorization() -> MorphAuthorization { let signed: SignedAuthorization = Authorization { chain_id: U256::from(1), address: Address::with_last_byte(0x42), @@ -1483,7 +1471,7 @@ mod tests { U256::from(2), true, )); - LazyAuthorization::Signed(signed) + MorphAuthorization::Signed(signed) } fn recovered_authorization( @@ -1491,8 +1479,8 @@ mod tests { delegate: Address, chain_id: u64, auth_nonce: u64, - ) -> LazyAuthorization { - LazyAuthorization::Recovered(RecoveredAuthorization::new_unchecked( + ) -> MorphAuthorization { + MorphAuthorization::Recovered(RecoveredAuthorization::new_unchecked( Authorization { chain_id: U256::from(chain_id), address: delegate, @@ -1505,7 +1493,7 @@ mod tests { fn morph_tx_env_with_authorizations( version: Option, kind: TxKind, - authorization_list: Vec, + authorization_list: Vec, ) -> MorphTxEnv { MorphTxEnv { tx_type: MORPH_TX_TYPE_ID, @@ -1518,7 +1506,7 @@ mod tests { } } - fn v2_env_with(authorization_list: Vec) -> MorphTxEnv { + fn v2_env_with(authorization_list: Vec) -> MorphTxEnv { morph_tx_env_with_authorizations( Some(MORPH_TX_VERSION_2), TxKind::Call(Address::ZERO), @@ -1775,7 +1763,7 @@ mod tests { fn apply_authorizations_skips_tuple_with_invalid_authority() { let delegate = Address::with_last_byte(0x42); let mut evm = evm_with_spec(MorphHardfork::Celadon); - let tx = v2_env_with(vec![LazyAuthorization::Recovered( + let tx = v2_env_with(vec![MorphAuthorization::Recovered( RecoveredAuthorization::new_unchecked( Authorization { chain_id: U256::from(1), @@ -1924,10 +1912,10 @@ mod tests { insert_contract(&mut db, token, mutating_return_code(1, 0)); db.insert_account_storage(&token, &U256::ZERO, &original_balance); let mut evm = evm_on(db, MorphHardfork::default(), MorphBlockEnv::default()); + set_tx_env(&mut evm, from); let err = transfer_erc20_with_evm( &mut evm, - &tx_env_of(from), from, to, token, @@ -1957,17 +1945,11 @@ mod tests { insert_contract(&mut db, token, mutating_return_code(1, 1)); db.insert_account_storage(&token, &U256::ZERO, &U256::from(50)); let mut evm = evm_on(db, MorphHardfork::default(), MorphBlockEnv::default()); + set_tx_env(&mut evm, from); - let err = transfer_erc20_with_evm( - &mut evm, - &tx_env_of(from), - from, - to, - token, - U256::from(1), - Some(U256::ZERO), - ) - .unwrap_err(); + let err = + transfer_erc20_with_evm(&mut evm, from, to, token, U256::from(1), Some(U256::ZERO)) + .unwrap_err(); assert!(matches!( morph_error(&err), @@ -2014,8 +1996,9 @@ mod tests { insert_contract(&mut db, token, mutating_return_code(1, 42)); db.insert_account_storage(&token, &U256::ZERO, &original_balance); let mut evm = evm_on(db, MorphHardfork::default(), MorphBlockEnv::default()); + set_tx_env(&mut evm, account); - assert!(evm_call_balance_of(&mut evm, &tx_env_of(account), token, account).is_err()); + assert!(evm_call_balance_of(&mut evm, token, account).is_err()); assert_eq!(storage_of(&mut evm, token, U256::ZERO), original_balance); } @@ -2278,15 +2261,8 @@ mod tests { let mut db = fee_refund_db(U256::from(FEE_REFUND_TOKEN_FEE)); insert_contract(&mut db, FEE_REFUND_TOKEN, mutating_return_code(1, 1)); let mut evm = fee_refund_evm(db); - assert!( - evm_call_balance_of( - &mut evm, - &tx_env_of(FEE_REFUND_CALLER), - FEE_REFUND_TOKEN, - FEE_REFUND_CALLER - ) - .is_err() - ); + set_tx_env(&mut evm, FEE_REFUND_CALLER); + assert!(evm_call_balance_of(&mut evm, FEE_REFUND_TOKEN, FEE_REFUND_CALLER).is_err()); } /// Fee frames run under the environment the transaction's preparation built, so ORIGIN and @@ -2313,29 +2289,69 @@ mod tests { host: &mut evm, _non_exhaustive: (), }; - let prepared = prepare(&mut request).unwrap(); + prepare(&mut request).unwrap(); assert_eq!( - evm_call_balance_of( - &mut evm, - &prepared.tx_env, - FEE_REFUND_TOKEN, - FEE_REFUND_BENEFICIARY - ) - .unwrap(), + evm_call_balance_of(&mut evm, FEE_REFUND_TOKEN, FEE_REFUND_BENEFICIARY).unwrap(), expected ); } } + /// L1 messages return early from `prepare`, so `host.tx_env_mut()` must be populated before + /// that branch rather than inheriting a prior transaction's `ORIGIN` or `GASPRICE`. + #[test] + fn l1_message_updates_tx_env_after_prior_transaction() { + let prior_caller = address!("1000000000000000000000000000000000000001"); + let l1_sender = address!("2000000000000000000000000000000000000002"); + let target = address!("3000000000000000000000000000000000000003"); + + for (opcode, expected) in [ + (0x32, U256::from_be_slice(l1_sender.as_slice())), // ORIGIN + (0x3a, U256::ZERO), // GASPRICE + ] { + let mut db = InMemoryDB::default(); + fund(&mut db, prior_caller, 10_000_000); + insert_contract(&mut db, target, code_returning(opcode)); + let mut evm = evm_on( + db, + MorphHardfork::Celadon, + MorphBlockEnv { + basefee: U256::from(5), + ..Default::default() + }, + ); + + let prior_tx = MorphTxEnv { + tx_type: LEGACY_TX_TYPE, + gas_limit: 50_000, + gas_price: 99, + kind: TxKind::Call(target), + ..Default::default() + }; + assert!(transact(&mut evm, prior_tx, prior_caller).unwrap().status); + + let l1_tx = MorphTxEnv { + tx_type: L1_TX_TYPE_ID, + gas_limit: 50_000, + gas_price: 0, + kind: TxKind::Call(target), + ..Default::default() + }; + let result = transact(&mut evm, l1_tx, l1_sender).unwrap(); + assert!(result.status); + assert_eq!(U256::from_be_slice(&result.output[..32]), expected); + } + } + #[test] fn zero_token_transfer_does_not_call_the_contract() { let mut db = fee_refund_db(U256::ZERO); insert_contract(&mut db, FEE_REFUND_TOKEN, mutating_return_code(1, 0)); let mut evm = fee_refund_evm(db); + set_tx_env(&mut evm, FEE_REFUND_CALLER); transfer_erc20_with_evm( &mut evm, - &tx_env_of(FEE_REFUND_CALLER), FEE_REFUND_CALLER, FEE_REFUND_BENEFICIARY, FEE_REFUND_TOKEN, @@ -3226,12 +3242,14 @@ mod refund_rounding_tests { for (gas_limit, want_credit) in [(99_999u64, 0u64), (100_000, 2), (100_001, 1)] { let mut evm = slot_mode_evm(MorphHardfork::Celadon); let tx = fee_tx(gas_limit, 0); - let tx_env = TxEnvExt { + let chain_id = evm.version().chain_id; + *evm.tx_env_mut() = TxEnvExt { origin: CALLER, gas_price: U256::from(1), + chain_id: U256::from(chain_id), ..TxEnvExt::default() }; - let charged = deduct_token_fee(&mut evm, &tx, CALLER, &tx_env, FEE_TOKEN_ID) + let charged = deduct_token_fee(&mut evm, &tx, CALLER, U256::from(1), FEE_TOKEN_ID) .unwrap_or_else(|err| panic!("deduction must succeed: {err}")); // The prepaid fee is `gas_limit` at price 1, so the credit is what @@ -3322,14 +3340,15 @@ mod refund_rounding_tests { /// Refunds `gas_left` worth of gas at a gas price of 1, so the ETH to refund equals the /// gas left and the arithmetic reads directly. fn refund(evm: &mut MorphEvm<'_>, gas_left: u64, rounding_credit: U256) { - let tx_env = TxEnvExt { + let chain_id = evm.version().chain_id; + *evm.tx_env_mut() = TxEnvExt { origin: CALLER, gas_price: U256::from(1), + chain_id: U256::from(chain_id), ..TxEnvExt::default() }; reimburse_token_fee( evm, - &tx_env, CALLER, U256::from(1), gas_left, diff --git a/crates/revm/src/lib.rs b/crates/revm/src/lib.rs index f8884bad..cc30a653 100644 --- a/crates/revm/src/lib.rs +++ b/crates/revm/src/lib.rs @@ -67,4 +67,4 @@ pub use token_fee::{ L2_TOKEN_REGISTRY_ADDRESS, TokenFeeInfo, compute_mapping_slot, compute_mapping_slot_for_address, encode_balance_of_calldata, }; -pub use tx::{MorphTxEnv, MorphTxExt}; +pub use tx::{MorphAuthorization, MorphTxEnv, MorphTxExt}; diff --git a/crates/revm/src/precompiles.rs b/crates/revm/src/precompiles.rs index 4ef7c251..d002f9a4 100644 --- a/crates/revm/src/precompiles.rs +++ b/crates/revm/src/precompiles.rs @@ -181,11 +181,11 @@ fn modexp_len_exceeds_32(data: &[u8], offset: usize) -> bool { /// /// Ref: fn modexp_with_32byte_limit( - _evm: &mut MorphEvm<'_>, + evm: &mut MorphEvm<'_>, message: &Message, gas: &mut GasTracker, ) -> PrecompileResult { - let input = message.input.as_ref(); + let input = evm.message_input(message); // The first 96 bytes of modexp input are three 32-byte big-endian length fields: // [0..32] = base_len, [32..64] = exp_len, [64..96] = mod_len if modexp_len_exceeds_32(input, 0) @@ -208,11 +208,11 @@ fn modexp_with_32byte_limit( /// /// Ref: fn bn256_pairing_with_4pair_limit( - _evm: &mut MorphEvm<'_>, + evm: &mut MorphEvm<'_>, message: &Message, gas: &mut GasTracker, ) -> PrecompileResult { - let input = message.input.as_ref(); + let input = evm.message_input(message); if input.len() > 4 * 192 { return halt("bad elliptic curve pairing size"); } diff --git a/crates/revm/src/token_fee.rs b/crates/revm/src/token_fee.rs index 012a5269..3af5d5d0 100644 --- a/crates/revm/src/token_fee.rs +++ b/crates/revm/src/token_fee.rs @@ -417,12 +417,13 @@ fn read_token_balance_with_fallback( // rather than the other client's pool. GASPRICE is the one input this query still // cannot match: it stays at zero because the effective price depends on the next // block's base fee, which admission does not know. go-ethereum's pool has the same gap. - let tx_env = TxEnvExt { + let chain_id = evm.version().chain_id; + *evm.tx_env_mut() = TxEnvExt { origin: account, - chain_id: U256::from(evm.version().chain_id), + chain_id: U256::from(chain_id), ..TxEnvExt::default() }; - crate::handler::evm_call_balance_of(&mut evm, &tx_env, token, account) + crate::handler::evm_call_balance_of(&mut evm, token, account) } /// Read ERC20 balance directly from storage slot. diff --git a/crates/revm/src/tx.rs b/crates/revm/src/tx.rs index 529763ad..69fa402d 100644 --- a/crates/revm/src/tx.rs +++ b/crates/revm/src/tx.rs @@ -12,8 +12,8 @@ use alloy_eips::{ eip2930::AccessList, eip7702::{RecoveredAuthorization, SignedAuthorization}, }; -use alloy_primitives::{B256, Bytes, ChainId, Signature, TxKind, U256}; -use evm2::ethereum::LazyAuthorization; +use alloy_primitives::{Address, B256, Bytes, ChainId, Signature, TxKind, U256}; +use evm2::ethereum::{LazyAuthorization, eip7702::Eip7702Authorization}; use morph_primitives::{ L1_TX_TYPE_ID, MORPH_TX_TYPE_ID, MorphTxEnvelope, TxMorph, transaction::morph_transaction::{MORPH_TX_VERSION_1, MORPH_TX_VERSION_2}, @@ -25,6 +25,63 @@ const LEGACY_TX_TYPE: u8 = 0x00; /// EIP-2718 type byte of an EIP-2930 transaction. const EIP2930_TX_TYPE: u8 = 0x01; +/// Owned EIP-7702 authorization stored in [`MorphTxEnv`]. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub enum MorphAuthorization { + /// Signed authorization whose authority is recovered on demand. + Signed(SignedAuthorization), + /// Authorization with a cached authority recovery result. + Recovered(RecoveredAuthorization), +} + +impl Eip7702Authorization for MorphAuthorization { + fn chain_id(&self) -> U256 { + match self { + Self::Signed(signed) => *signed.chain_id(), + Self::Recovered(recovered) => *recovered.chain_id(), + } + } + + fn nonce(&self) -> u64 { + match self { + Self::Signed(signed) => signed.nonce(), + Self::Recovered(recovered) => recovered.nonce(), + } + } + + fn address(&self) -> Address { + match self { + Self::Signed(signed) => *signed.address(), + Self::Recovered(recovered) => *recovered.address(), + } + } + + fn authority(&self) -> Option

{ + match self { + Self::Signed(signed) => LazyAuthorization::Signed(signed).authority(), + Self::Recovered(recovered) => recovered.authority(), + } + } +} + +impl Eip7702Authorization for &MorphAuthorization { + fn chain_id(&self) -> U256 { + (*self).chain_id() + } + + fn nonce(&self) -> u64 { + (*self).nonce() + } + + fn address(&self) -> Address { + (*self).address() + } + + fn authority(&self) -> Option
{ + (*self).authority() + } +} + /// Morph transaction environment with token fee support. /// /// The fields follow the semantics of the consensus transaction they were built from: @@ -60,7 +117,7 @@ pub struct MorphTxEnv { /// EIP-2930 access list. pub access_list: AccessList, /// EIP-7702 authorizations, with their authorities recovered where possible. - pub authorization_list: Vec, + pub authorization_list: Vec, /// RLP encoded transaction bytes. /// Used only for L1 data fee calculation. pub rlp_bytes: Option, @@ -275,10 +332,10 @@ impl MorphTxEnv { self.authorization_list .iter() .map(|auth| match auth { - LazyAuthorization::Signed(signed) => signed.clone(), + MorphAuthorization::Signed(signed) => signed.clone(), // Recovered authorizations no longer carry their original // signature, so reuse the fee-sizing placeholder. - LazyAuthorization::Recovered(recovered) => { + MorphAuthorization::Recovered(recovered) => { recovered.clone().into_parts().0.into_signed(placeholder) } }) @@ -311,9 +368,9 @@ impl MorphTxEnv { .unwrap_or_default() .iter() .map(|auth| { - LazyAuthorization::Recovered(RecoveredAuthorization::new_unchecked( + MorphAuthorization::Recovered(RecoveredAuthorization::new_unchecked( auth.inner().clone(), - auth.recover_authority().map_or( + LazyAuthorization::Signed(auth).authority().map_or( alloy_eips::eip7702::RecoveredAuthority::Invalid, alloy_eips::eip7702::RecoveredAuthority::Valid, ), @@ -756,7 +813,7 @@ mod tests { gas_priority_fee: Some(1_000_000_000), nonce: 1, kind: TxKind::Create, - authorization_list: vec![LazyAuthorization::Signed(sample_signed_authorization())], + authorization_list: vec![MorphAuthorization::Signed(sample_signed_authorization())], ..Default::default() }; @@ -779,7 +836,7 @@ mod tests { gas_priority_fee: Some(1_000_000_000), nonce: 1, kind: TxKind::Call(Address::with_last_byte(0xf1)), - authorization_list: vec![LazyAuthorization::Signed(signed_authorization.clone())], + authorization_list: vec![MorphAuthorization::Signed(signed_authorization.clone())], ..Default::default() }; @@ -825,7 +882,7 @@ mod tests { .into_signed(Signature::new(U256::from(1), U256::from(2), true)) } - fn morph_v2_tx_env(version: Option, authorization: LazyAuthorization) -> MorphTxEnv { + fn morph_v2_tx_env(version: Option, authorization: MorphAuthorization) -> MorphTxEnv { MorphTxEnv { tx_type: MORPH_TX_TYPE_ID, chain_id: Some(53077), @@ -850,7 +907,7 @@ mod tests { let signed_authorization = sample_signed_authorization(); let tx = morph_v2_tx_env( Some(MORPH_TX_VERSION_2), - LazyAuthorization::Signed(signed_authorization.clone()), + MorphAuthorization::Signed(signed_authorization.clone()), ); let encoded = tx.encode_for_l1_fee(53077); @@ -878,7 +935,7 @@ mod tests { fn encode_for_l1_fee_morph_tx_version_fallback_picks_v2_with_authorizations() { let tx = morph_v2_tx_env( None, - LazyAuthorization::Signed(sample_signed_authorization()), + MorphAuthorization::Signed(sample_signed_authorization()), ); let encoded = tx.encode_for_l1_fee(53077); @@ -910,7 +967,7 @@ mod tests { ); let tx = morph_v2_tx_env( Some(MORPH_TX_VERSION_2), - LazyAuthorization::Recovered(recovered), + MorphAuthorization::Recovered(recovered), ); let encoded = tx.encode_for_l1_fee(53077); @@ -959,7 +1016,7 @@ mod tests { assert_eq!(env.tx_type, MORPH_TX_TYPE_ID); assert_eq!(env.authorization_list.len(), 1); match &env.authorization_list[0] { - LazyAuthorization::Recovered(recovered) => { + MorphAuthorization::Recovered(recovered) => { let (authorization, _authority) = recovered.clone().into_parts(); assert_eq!(&authorization, signed_authorization.inner()); } diff --git a/crates/rpc/src/eth/transaction.rs b/crates/rpc/src/eth/transaction.rs index 1e4d471f..b8624d4a 100644 --- a/crates/rpc/src/eth/transaction.rs +++ b/crates/rpc/src/eth/transaction.rs @@ -7,7 +7,6 @@ use alloy_consensus::{ use alloy_network::TxSigner; use alloy_primitives::{B256, Signature, TxKind, U64, U256}; use alloy_rpc_types_eth::AccessList; -use evm2::ethereum::LazyAuthorization; use reth_rpc_convert::{ EthTxEnvError, SignTxRequestError, SignableTxRequest, TryIntoSimTx, TryIntoTxEnv, normalize_transaction_request, @@ -15,7 +14,7 @@ use reth_rpc_convert::{ use reth_rpc_eth_types::EthApiError; use morph_primitives::{MorphTxEnvelope, TxMorph}; -use morph_revm::{MorphEvmEnv, MorphTxEnv}; +use morph_revm::{MorphAuthorization, MorphEvmEnv, MorphTxEnv}; use reth_evm::EvmEnv; /// Converts a [`MorphTransactionRequest`] into a simulated transaction envelope. @@ -154,7 +153,7 @@ impl TryIntoTxEnv, MorphEvmEnv> for MorphTransactionReques .authorization_list .unwrap_or_default() .into_iter() - .map(LazyAuthorization::Signed) + .map(MorphAuthorization::Signed) .collect(), ..Default::default() }; diff --git a/deny.toml b/deny.toml index b4a7c439..67162ea2 100644 --- a/deny.toml +++ b/deny.toml @@ -84,7 +84,6 @@ unknown-git = "deny" allow-git = [ "https://github.com/paradigmxyz/reth", "https://github.com/paradigmxyz/reth-core", - "https://github.com/sigp/discv5", - # evm2 has no crates.io release; reth requires this exact URL through a `[patch]`. - "https://www.github.com/alloy-rs/evm2", + # evm2 has no crates.io release; reth v2.11.0 requires this exact URL through a `[patch]`. + "https://github.com/DaniPopes/evm2", ] From b2be11731d706d43af3337c7a5dbba75fd959f9b Mon Sep 17 00:00:00 2001 From: panos-xyz Date: Tue, 24 Nov 2026 23:31:28 +0800 Subject: [PATCH 04/16] fix(alt-fee): simplify and harden alt-token fee handling on evm2 --- Cargo.lock | 1 + crates/revm/src/handler.rs | 237 ++++++++++- crates/revm/src/lib.rs | 2 +- crates/revm/src/token_fee.rs | 230 +++++++++- crates/rpc/src/eth/call.rs | 504 ++++++++++++---------- crates/txpool/Cargo.toml | 1 + crates/txpool/src/error.rs | 15 +- crates/txpool/src/lib.rs | 2 + crates/txpool/src/maintain.rs | 26 +- crates/txpool/src/morph_tx_validation.rs | 49 +-- crates/txpool/src/state_cache.rs | 520 +++++++++++++++++++++++ crates/txpool/src/validator.rs | 398 +++++++++++++++-- 12 files changed, 1640 insertions(+), 345 deletions(-) create mode 100644 crates/txpool/src/state_cache.rs diff --git a/Cargo.lock b/Cargo.lock index e25d3bfc..28c62dfb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5719,6 +5719,7 @@ dependencies = [ "alloy-eips", "alloy-primitives", "c-kzg", + "dashmap", "derive_more", "evm2", "futures", diff --git a/crates/revm/src/handler.rs b/crates/revm/src/handler.rs index ed6fbfd1..01996ce1 100644 --- a/crates/revm/src/handler.rs +++ b/crates/revm/src/handler.rs @@ -309,7 +309,7 @@ fn validate_env(host: &MorphEvm<'_>, tx: &MorphTxEnv) -> HandlerResult<()> { match tx.tx_type { LEGACY_TX_TYPE | EIP2930_TX_TYPE => validate_gas_price(version, max_fee, basefee)?, - EIP1559_TX_TYPE => { + EIP1559_TX_TYPE | MORPH_TX_TYPE_ID => { validate_priority_fee(version, max_fee, priority_fee)?; validate_gas_price(version, effective_gas_price, basefee)?; } @@ -328,18 +328,6 @@ fn validate_env(host: &MorphEvm<'_>, tx: &MorphTxEnv) -> HandlerResult<()> { validate_nonce_not_overflow(tx.nonce)?; if tx.is_morph_tx() { - // The EIP-1559 fee-cap rules hold whichever asset ends up paying the fee, matching - // Morph geth's preCheck. Unlike the standard types, a disabled base fee check does - // not relax them while fees are being charged. - if host.feature(EvmFeatures::FEE_CHARGE) { - validate_priority_fee(version, max_fee, priority_fee)?; - if effective_gas_price < basefee { - return Err(HandlerError::FeeCapLessThanBaseFee { - max_fee_per_gas: effective_gas_price, - base_fee: basefee, - }); - } - } validate_morph_tx_authorization_list(host, tx)?; } @@ -1456,6 +1444,45 @@ mod tests { )); } + #[test] + fn validate_env_respects_disabled_base_fee_check_for_morph_tx_even_when_charging_fees() { + let mut env = test_env( + MorphHardfork::default(), + MorphBlockEnv { + basefee: U256::from(100), + ..Default::default() + }, + ); + // `eth_simulateV1` with `validation: false` keeps `FEE_CHARGE` enabled while disabling + // `BASE_FEE_CHECK`. MorphTx must obey `BASE_FEE_CHECK` just like EIP-1559 transactions. + env.version.features.remove(EvmFeatures::BASE_FEE_CHECK); + assert!(env.version.feature(EvmFeatures::FEE_CHARGE)); + let evm = morph_evm(InMemoryDB::default(), env); + + let tx = MorphTxEnv { + tx_type: MORPH_TX_TYPE_ID, + gas_limit: 21_000, + gas_price: 99, + gas_priority_fee: Some(1), + kind: TxKind::Call(Address::ZERO), + fee_token_id: Some(1), + ..Default::default() + }; + assert_eq!(validate_env(&evm, &tx), Ok(())); + + // Priority-fee inversion (`max_priority_fee > max_fee`) still fails while + // `PRIORITY_FEE_CHECK` is active. + let inverted_tip_tx = MorphTxEnv { + gas_price: 10, + gas_priority_fee: Some(20), + ..tx + }; + assert!(matches!( + validate_env(&evm, &inverted_tip_tx).unwrap_err(), + HandlerError::PriorityFeeGreaterThanMaxFee + )); + } + // ========================================================================= // MorphTx V2 (EIP-7702 authorization list) handler rules // ========================================================================= @@ -2467,6 +2494,85 @@ mod tests { assert_eq!(fee_refund_run_fee_tx(db), fee_refund_run_token_fee_tx(fee)); } + /// Regression for M-M01: across sequential transactions on a single reused `MorphEvm`, + /// precompiles start cold during pre-tx call-mode fee deduction (matching `morph-geth` + /// resetting the access list per tx before `buyGas`), then become warm for the main frame + /// and reimbursement, and reset cleanly again before the next transaction. + #[test] + fn call_mode_precompile_gas_is_identical_across_sequential_txs_on_reused_evm() { + // Token contract whose `balanceOf` returns `GAS_BEFORE - GAS_AFTER` around a + // `STATICCALL` to identity precompile (0x04) with 0-byte input when caller's slot is + // non-zero, so any precompile warmth leak from tx #0 into tx #1 changes the reported + // balance by 2500 gas (2600 cold vs 100 warm)! + // Bytecode: + // GAS, PUSH0(retSize), PUSH0(retOff), PUSH0(argSize), PUSH0(argOff), PUSH1 4, PUSH2 5000, + // STATICCALL, POP, GAS, SWAP1, SUB, PUSH0, MSTORE, PUSH1 32, PUSH0, RETURN + let gas_delta_balance_code = Bytes::from_static(&[ + 0x5a, 0x5f, 0x5f, 0x5f, 0x5f, 0x60, 0x04, 0x61, 0x13, 0x88, 0xfa, 0x50, 0x5a, 0x90, + 0x03, 0x5f, 0x52, 0x60, 0x20, 0x5f, 0xf3, + ]); + + let mut db = InMemoryDB::default(); + insert_test_fee_token(&mut db, 1, FEE_REFUND_TOKEN, true); + insert_contract(&mut db, FEE_REFUND_TOKEN, gas_delta_balance_code); + // Main frame target calls identity precompile (0x04) and returns `GAS_BEFORE - GAS_AFTER` + // to verify precompiles ARE warmed for the main execution frame. + insert_contract( + &mut db, + FEE_REFUND_TARGET, + Bytes::from_static(&[ + 0x5a, 0x5f, 0x5f, 0x5f, 0x5f, 0x60, 0x04, 0x61, 0x13, 0x88, 0xfa, 0x50, 0x5a, 0x90, + 0x03, 0x5f, 0x52, 0x60, 0x20, 0x5f, 0xf3, + ]), + ); + + let env = test_env( + MorphHardfork::Celadon, + MorphBlockEnv { + basefee: U256::ZERO, + gas_limit: U256::from(30_000_000), + ..Default::default() + }, + ); + + let standalone_probe_balance = TokenFeeInfo::load_for_caller( + &mut crate::token_fee::tests::Plain(db.clone()), + 1, + FEE_REFUND_CALLER, + &env, + ) + .unwrap() + .unwrap() + .balance; + + let mut evm = morph_evm(db, env); + for nonce in [0u64, 1u64] { + let zero_price_tx = MorphTxEnv { + tx_type: MORPH_TX_TYPE_ID, + nonce, + gas_limit: 100_000, + gas_price: 0, + kind: TxKind::Call(FEE_REFUND_TARGET), + fee_token_id: Some(1), + ..Default::default() + }; + let result = transact(&mut evm, zero_price_tx, FEE_REFUND_CALLER) + .expect("zero-price call-mode tx must succeed"); + assert!(result.status); + let deducted_info = result.ext.token_fee_info.expect("token fee info recorded"); + assert_eq!( + deducted_info.balance, standalone_probe_balance, + "tx #{nonce} pre-tx balanceOf must see cold precompile matching load_for_caller" + ); + let main_frame_delta = U256::from_be_slice(&result.output[..32]); + assert!( + deducted_info.balance >= main_frame_delta + U256::from(2_500u64), + "pre-tx balanceOf ({}) must pay 2500 cold-access gas more than warm main frame ({main_frame_delta})", + deducted_info.balance, + ); + } + } + /// Mainnet's call-mode fee tokens are proxies, so a fee frame's nested /// `DELEGATECALL` reads its calldata back out of the frame's memory. #[test] @@ -3441,4 +3547,109 @@ mod refund_rounding_tests { "a zero refund must leave the vault balance alone" ); } + + /// Regression for M-C01: direct-slot pre-tx fee deduction clears `CALLER`'s balance slot + /// (`X -> 0`) without recording an SSTORE clear refund (`+4800`), and when the main frame + /// credits tokens back (`0 -> Y`), EIP-2200 records `-4800` against the original pre-tx + /// non-zero value. A net-negative signed refund counter must settle to `0` refund, never + /// wrap to the 20% refund cap. + #[test] + fn direct_slot_deduction_clearing_balance_plus_main_frame_credit_gives_zero_refund() { + let gas_limit = 100_000u64; + let exact_token_fee = ceil_to_token(gas_limit); + + let mut db = InMemoryDB::default(); + db.insert_account_info( + &TOKEN, + AccountInfo::default().with_code(evm2::bytecode::Bytecode::new_legacy({ + // Credit 1 token back to CALLER's balance slot (`0 -> 1` while original was `> 0`): + // PUSH1 1, PUSH32 slot_of(CALLER), SSTORE, STOP + let mut code = vec![0x60, 0x01, 0x7f]; + code.extend_from_slice(&slot_of(CALLER).to_be_bytes::<32>()); + code.push(0x55); + code.push(0x00); + Bytes::from(code) + })), + ); + db.insert_account_info(&CALLER, AccountInfo::default()); + register_slot_mode_token(&mut db); + db.insert_account_storage(&TOKEN, &slot_of(CALLER), &exact_token_fee); + db.insert_account_storage(&TOKEN, &slot_of(BENEFICIARY), &U256::ZERO); + + let mut evm = morph_evm( + db, + morph_evm_env(MorphHardfork::Celadon, 1, 30_000_000, block()), + ); + let tx = MorphTxEnv { + tx_type: MORPH_TX_TYPE_ID, + kind: TxKind::Call(TOKEN), + gas_limit, + gas_price: 1, + fee_token_id: Some(FEE_TOKEN_ID), + ..Default::default() + }; + + let result = evm + .transact(&Recovered::new_unchecked(tx, CALLER)) + .expect("tx must execute") + .commit(); + assert!(result.status); + assert_eq!( + result.refunded, 0, + "net-negative SSTORE refund counter must clamp to 0, never wrap into a refund" + ); + } + + /// Regression for M-H01: `reimburse_token_fee` multiplies `gas_price * unused_gas` in `U256` + /// without intermediate `u128` truncation when `gas_price * unused_gas > u128::MAX`. + #[test] + fn reimburse_token_fee_uses_u256_product_above_u128_max() { + let mut evm = evm_after_deduction(MorphHardfork::Celadon); + let gas_price = U256::from(u128::MAX); + let unused_gas = 2u64; + let expected_refund = TokenFeeInfo { + price_ratio: U256::from(PRICE_RATIO), + scale: U256::from(1u64), + ..Default::default() + } + .eth_to_token_amount_floor(gas_price * U256::from(unused_gas), U256::ZERO); + + // Ensure vault holds enough tokens to cover the huge refund. + let vault_slot = slot_of(BENEFICIARY); + evm.state_mut() + .storage_slot(&TOKEN, vault_slot) + .unwrap() + .set(expected_refund); + + let chain_id = evm.version().chain_id; + *evm.tx_env_mut() = TxEnvExt { + origin: CALLER, + gas_price, + chain_id: U256::from(chain_id), + ..TxEnvExt::default() + }; + reimburse_token_fee( + &mut evm, + CALLER, + gas_price, + unused_gas, + AppliedTokenFee { + info: TokenFeeInfo { + token_address: TOKEN, + is_active: true, + price_ratio: U256::from(PRICE_RATIO), + scale: U256::from(1u64), + caller: CALLER, + balance: U256::ZERO, + balance_slot: Some(BALANCE_SLOT), + ..Default::default() + }, + rounding_credit: U256::ZERO, + refund_counter: 0, + }, + ) + .expect("U256 refund must succeed"); + + assert_eq!(token_balance(&mut evm, CALLER), expected_refund); + } } diff --git a/crates/revm/src/lib.rs b/crates/revm/src/lib.rs index cc30a653..65444a9f 100644 --- a/crates/revm/src/lib.rs +++ b/crates/revm/src/lib.rs @@ -64,7 +64,7 @@ pub use l1block::{ }; pub use precompiles::morph_precompiles; pub use token_fee::{ - L2_TOKEN_REGISTRY_ADDRESS, TokenFeeInfo, compute_mapping_slot, + L2_TOKEN_REGISTRY_ADDRESS, TokenFeeInfo, TokenRegistryEntry, compute_mapping_slot, compute_mapping_slot_for_address, encode_balance_of_calldata, }; pub use tx::{MorphAuthorization, MorphTxEnv, MorphTxExt}; diff --git a/crates/revm/src/token_fee.rs b/crates/revm/src/token_fee.rs index 3af5d5d0..76b1d7ea 100644 --- a/crates/revm/src/token_fee.rs +++ b/crates/revm/src/token_fee.rs @@ -14,7 +14,7 @@ use evm2::{ use crate::{ MorphInvalidTransaction, - evm::{MorphEvmEnv, morph_evm}, + evm::{MorphEvm, MorphEvmEnv, morph_evm}, }; /// L2 Token Registry contract address on Morph L2. @@ -51,39 +51,55 @@ pub struct TokenFeeInfo { } /// Fee-token registry metadata without any caller-specific balance state. -#[derive(Clone, Copy, Debug)] -pub(crate) struct TokenRegistryEntry { - token_address: Address, - is_active: bool, - decimals: u8, - price_ratio: U256, - scale: U256, - balance_slot: Option, +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct TokenRegistryEntry { + /// The registered ERC20 contract address. + pub token_address: Address, + /// Whether the token is active for gas payment. + pub is_active: bool, + /// Token decimals. + pub decimals: u8, + /// The price ratio of the token (relative to ETH). + pub price_ratio: U256, + /// The scale of the token for price calculation. + pub scale: U256, + /// The user's ERC20 balance storage slot (`None` means call-mode `balanceOf`). + pub balance_slot: Option, } impl TokenRegistryEntry { /// The registered ERC20 contract. - pub(crate) const fn token_address(&self) -> Address { + pub const fn token_address(&self) -> Address { self.token_address } /// The caller's balance storage slot, when the registry declares one. /// /// `None` means call mode: the balance has to be read by calling `balanceOf`. - pub(crate) const fn balance_slot(&self) -> Option { + pub const fn balance_slot(&self) -> Option { self.balance_slot } /// Load fee-token metadata without reading a caller's token balance. - pub(crate) fn load( - db: &mut DB, - token_id: u16, - ) -> Result, DB::Error> { + pub fn load(db: &mut DB, token_id: u16) -> Result, DB::Error> { Self::load_with(|address, slot| db.get_storage(&address, &slot), token_id) } + /// Load fee-token metadata through an existing [`MorphEvm`]'s backing database without + /// warming or tracking the registry slots in transaction state. + pub fn load_from_evm( + evm: &mut MorphEvm<'_>, + token_id: u16, + ) -> Result, HandlerError> { + let state = evm.state_mut(); + Ok(Self::load_with( + |address, slot| state.storage_slot_untracked(&address, &slot), + token_id, + )?) + } + /// As [`Self::load`], reading storage through `read`. - pub(crate) fn load_with( + pub fn load_with( read: impl FnMut(Address, U256) -> Result, token_id: u16, ) -> Result, E> { @@ -91,7 +107,7 @@ impl TokenRegistryEntry { } /// Reject registry entries that cannot produce a valid token-denominated fee. - pub(crate) fn ensure_usable(self, token_id: u16) -> Result { + pub fn ensure_usable(self, token_id: u16) -> Result { if !self.is_active { return Err(MorphInvalidTransaction::TokenNotActive(token_id)); } @@ -101,8 +117,38 @@ impl TokenRegistryEntry { Ok(self) } + /// Read `caller`'s balance using an existing [`MorphEvm`], leaving its transaction-scoped + /// state completely clean so the same EVM instance can be reused across callers and tokens. + pub fn read_caller_balance_with_evm( + &self, + evm: &mut MorphEvm<'_>, + caller: Address, + ) -> Result { + if let Some(slot) = self.balance_slot { + let state = evm.state_mut(); + return Ok(read_balance_from_storage( + |address, slot| state.storage_slot_untracked(&address, &slot), + self.token_address, + caller, + slot, + )?); + } + + // Call mode: ORIGIN matches execution (`caller`); GASPRICE stays zero when admission + // does not know the next block's effective price. + let chain_id = evm.version().chain_id; + *evm.tx_env_mut() = TxEnvExt { + origin: caller, + chain_id: U256::from(chain_id), + ..TxEnvExt::default() + }; + let result = crate::handler::evm_call_balance_of(evm, self.token_address, caller); + evm.state_mut().clear_transaction_state(); + result + } + /// Resolve the caller's balance to produce complete fee information. - pub(crate) fn load_for_caller( + pub fn load_for_caller( self, db: &mut DB, caller: Address, @@ -136,7 +182,8 @@ impl TokenRegistryEntry { Ok(self.into_fee_info(caller, balance)) } - pub(crate) fn into_fee_info(self, caller: Address, balance: U256) -> TokenFeeInfo { + /// Combine registry metadata with a resolved caller balance. + pub const fn into_fee_info(self, caller: Address, balance: U256) -> TokenFeeInfo { TokenFeeInfo { token_address: self.token_address, is_active: self.is_active, @@ -163,9 +210,12 @@ impl TokenFeeInfo { /// Load token fee information with EVM call fallback. /// - /// Reads token parameters from L2 Token Registry storage. If the token's - /// balance slot is unknown, falls back to an EVM `balanceOf` call. - /// Returns `None` if the token is not registered. + /// Reads token parameters from L2 Token Registry storage and validates + /// usability (`is_active`, non-zero `price_ratio` and `scale`) before + /// resolving the caller's balance, so inactive or misconfigured call-mode + /// tokens never execute contract bytecode. If the token's balance slot is + /// unknown, falls back to an EVM `balanceOf` call. + /// Returns `Ok(None)` if the token is not registered. pub fn load_for_caller( db: &mut DB, token_id: u16, @@ -173,7 +223,7 @@ impl TokenFeeInfo { env: &MorphEvmEnv, ) -> Result, HandlerError> { let entry = match TokenRegistryEntry::load(db, token_id).map_err(database_error::)? { - Some(e) => e, + Some(e) => e.ensure_usable(token_id)?, None => return Ok(None), }; @@ -628,6 +678,140 @@ pub(crate) mod tests { assert!(is_token_read_failure(&error), "{error:?}"); } + #[test] + fn load_for_caller_rejects_unusable_call_mode_tokens_before_executing_bytecode() { + let token = address!("5300000000000000000000000000000000000042"); + let caller = address!("0000000000000000000000000000000000000001"); + let env = MorphEvmEnv::new(MorphHardfork::Emerald, MorphBlockEnv::default(), 1); + + let mut token_id_bytes = [0u8; 32]; + token_id_bytes[31] = 1; + let base = compute_mapping_slot(TOKEN_REGISTRY_SLOT, &token_id_bytes); + + // Inactive token: `UnreadableTokenDb` would fail with `TokenReadFailure` if `balanceOf` + // were ever invoked, proving usability is checked before entering call-mode bytecode. + let mut inactive_inner = call_mode_token_state(token, 10_000_000); + let mut inactive_packed = [0u8; 32]; + inactive_packed[30] = 18; + inactive_packed[31] = 0; + inactive_inner.insert_account_storage( + &L2_TOKEN_REGISTRY_ADDRESS, + &(base + U256::from(2)), + &U256::from_be_bytes(inactive_packed), + ); + let mut unreadable_inactive = UnreadableTokenDb { + inner: inactive_inner, + token, + }; + let err = + TokenFeeInfo::load_for_caller(&mut unreadable_inactive, 1, caller, &env).unwrap_err(); + assert_eq!( + err.external_ref::(), + Some(&MorphInvalidTransaction::TokenNotActive(1)) + ); + + // Zero scale token: rejected with `InvalidTokenConfig(1)` before `balanceOf`. + let mut zero_scale_inner = call_mode_token_state(token, 10_000_000); + zero_scale_inner.insert_account_storage( + &L2_TOKEN_REGISTRY_ADDRESS, + &(base + U256::from(3)), + &U256::ZERO, + ); + let mut unreadable_zero_scale = UnreadableTokenDb { + inner: zero_scale_inner, + token, + }; + let err = + TokenFeeInfo::load_for_caller(&mut unreadable_zero_scale, 1, caller, &env).unwrap_err(); + assert_eq!( + err.external_ref::(), + Some(&MorphInvalidTransaction::InvalidTokenConfig(1)) + ); + } + + #[test] + fn reused_evm_recovers_cleanly_after_proxy_delegatecall_db_failure() { + use std::sync::{ + Arc, + atomic::{AtomicBool, Ordering}, + }; + + struct FlakyImplDb { + inner: InMemoryDB, + fail_impl: Arc, + token: Address, + } + + impl Database for FlakyImplDb { + type Error = TokenReadFailure; + + fn get_account( + &mut self, + address: &Address, + ) -> Result, Self::Error> { + Ok(DynDatabase::get_account(&mut self.inner, address).unwrap()) + } + + fn get_code_by_hash(&mut self, code_hash: &B256) -> Result { + Ok(DynDatabase::get_code_by_hash(&mut self.inner, code_hash).unwrap()) + } + + fn get_storage(&mut self, address: &Address, key: &Word) -> Result { + if *address == self.token && self.fail_impl.load(Ordering::Relaxed) { + return Err(TokenReadFailure); + } + Ok(DynDatabase::get_storage(&mut self.inner, address, key).unwrap()) + } + + fn get_block_hash(&mut self, number: &Word) -> Result { + Ok(DynDatabase::get_block_hash(&mut self.inner, number).unwrap()) + } + } + + let proxy = address!("5300000000000000000000000000000000000042"); + let implementation = address!("5300000000000000000000000000000000000099"); + let caller = address!("0000000000000000000000000000000000000001"); + + // Minimal DELEGATECALL proxy -> implementation reading slot 0. + let mut proxy_code = vec![0x36, 0x5f, 0x5f, 0x37, 0x5f, 0x5f, 0x36, 0x5f, 0x73]; + proxy_code.extend_from_slice(implementation.as_slice()); + proxy_code.extend_from_slice(&[0x5a, 0xf4, 0x3d, 0x5f, 0x5f, 0x3e, 0x50, 0x3d, 0x5f, 0xf3]); + + let mut inner = call_mode_token_state_with_code(proxy, 777_000, Bytes::from(proxy_code)); + inner.insert_account_info( + &implementation, + AccountInfo::default().with_code(Bytecode::new_legacy(bytes!("6000545f5260205ff3"))), + ); + + let fail_impl = Arc::new(AtomicBool::new(true)); + let db = FlakyImplDb { + inner, + fail_impl: Arc::clone(&fail_impl), + token: proxy, + }; + let env = MorphEvmEnv::new(MorphHardfork::Emerald, MorphBlockEnv::default(), 2818); + let mut evm = morph_evm(Db::new(db), env); + + let entry = TokenRegistryEntry::load_from_evm(&mut evm, 1) + .unwrap() + .unwrap() + .ensure_usable(1) + .unwrap(); + + // First call fails mid-DELEGATECALL with DB read error. + let err = entry + .read_caller_balance_with_evm(&mut evm, caller) + .unwrap_err(); + assert!(is_token_read_failure(&err), "{err:?}"); + + // Flip DB healthy and reuse the exact same `MorphEvm` instance: must succeed cleanly. + fail_impl.store(false, Ordering::Relaxed); + let balance = entry + .read_caller_balance_with_evm(&mut evm, caller) + .expect("reused EVM must recover cleanly after nested frame DB error"); + assert_eq!(balance, U256::from(777_000u64)); + } + #[test] fn test_token_fee_info_default() { let info = TokenFeeInfo::default(); diff --git a/crates/rpc/src/eth/call.rs b/crates/rpc/src/eth/call.rs index 236edeeb..751d7868 100644 --- a/crates/rpc/src/eth/call.rs +++ b/crates/rpc/src/eth/call.rs @@ -8,10 +8,11 @@ use crate::MorphEthApiError; use crate::eth::{MorphEthApi, MorphNodeCore}; -use alloy_primitives::U256; -use evm2::EvmFeatures; +use alloy_primitives::{Address, U256, U512}; +use evm2::{EvmFeatures, registry::HandlerError}; use morph_chainspec::{MorphChainSpec, MorphHardforks}; -use morph_revm::{L1BlockInfo, MorphTxExt, TokenFeeInfo}; +use morph_revm::{L1BlockInfo, MorphEvmEnv, MorphTxExt, TokenFeeInfo}; +use reth_errors::ProviderError; use reth_evm::{Database, EvmEnv, EvmEnvFor, TxEnvFor}; use reth_provider::ChainSpecProvider; use reth_rpc_eth_api::{ @@ -97,6 +98,7 @@ where if let Some(fee_token_id) = tx_env.fee_token_id.filter(|id| *id > 0) { return self.caller_gas_allowance_with_token( &mut db, + evm_env, tx_env.signer(), tx_env.value, l1_fee, @@ -175,7 +177,8 @@ where fn caller_gas_allowance_with_token( &self, db: &mut DB, - caller: alloy_primitives::Address, + evm_env: &MorphEvmEnv, + caller: Address, value: U256, l1_fee: U256, fee_token_id: u16, @@ -186,9 +189,7 @@ where DB: Database, DB::Error: Into, { - let token_fee_info = TokenFeeInfo::load_storage_only(db, fee_token_id, caller) - .map_err(|_| MorphEthApiError::InvalidFeeToken)? - .ok_or(MorphEthApiError::InvalidFeeToken)?; + let token_fee_info = load_token_fee_info_for_allowance(db, fee_token_id, caller, evm_env)?; // ETH only needs to cover `value`; gas + L1 fee are paid in tokens. let eth_balance = db @@ -204,20 +205,38 @@ where l1_fee, fee_limit, gas_price, - self.eth_api().gas_cap(), ) } } +/// Resolves fee-token metadata and `caller`'s balance (both direct-slot and call-mode `balanceOf`) +/// for `eth_estimateGas`, preserving database/provider failures instead of masking them as +/// [`MorphEthApiError::InvalidFeeToken`]. +fn load_token_fee_info_for_allowance( + db: &mut DB, + fee_token_id: u16, + caller: Address, + evm_env: &MorphEvmEnv, +) -> Result { + match TokenFeeInfo::load_for_caller(db, fee_token_id, caller, evm_env) { + Ok(Some(info)) => Ok(info), + Ok(None) => Err(MorphEthApiError::InvalidFeeToken), + Err(HandlerError::Database(db_err)) => { + if let Some(provider_err) = db_err.downcast_ref::() { + return Err(MorphEthApiError::from(provider_err.clone())); + } + Err(MorphEthApiError::from(ProviderError::other(db_err))) + } + Err(HandlerError::Fatal(msg)) => Err(MorphEthApiError::Internal(msg.to_string())), + Err(_) => Err(MorphEthApiError::InvalidFeeToken), + } +} + /// Compute the gas allowance for a MorphTx fee-token caller. /// -/// Pure function over the inputs `caller_gas_allowance_with_token` would -/// load from the database, factored out so the affordability and bounding -/// logic can be unit-tested without an EVM/DB stack. -/// -/// The `gas_cap` argument is the per-call RPC ceiling (`EthApiNodeBackend::gas_cap()`), -/// only consumed by the EVM-call-mode + no-`fee_limit` fallback to avoid -/// returning `u64::MAX`. See the in-body comment for the security rationale. +/// Both slot-mode and call-mode balances are already resolved in `token_fee_info.balance`; +/// `--rpc.gascap` and `block_gas_limit` clamping are handled upstream by Reth's +/// `estimate_gas_with`. fn token_gas_allowance( eth_balance: U256, value: U256, @@ -225,7 +244,6 @@ fn token_gas_allowance( l1_fee: U256, fee_limit: Option, gas_price: u128, - gas_cap: u64, ) -> Result { if !token_fee_info.is_active || token_fee_info.price_ratio.is_zero() @@ -238,53 +256,38 @@ fn token_gas_allowance( return Err(MorphEthApiError::InsufficientFundsForTransfer); } - // Determine the token-denominated affordability cap. - // - // - Slot mode (`balance_slot.is_some()`): RPC reads balance directly - // from token storage; cap by `min(balance, fee_limit)`. The - // trusted balance is the natural ceiling. - // - EVM-call mode (`balance_slot.is_none()`): RPC cannot resolve the - // balance without spinning up an EVM (the handler does that at real - // execution via `load_for_caller`). On the estimateGas path - // fee charging is off, which short-circuits the handler's check, so - // there is no natural balance ceiling — we MUST enforce `gas_cap` - // here, matching `eth_call`'s effective ceiling. Trusting a - // user-supplied `fee_limit` alone would let `fee_limit = U256::MAX` - // bypass the operator-configured `--rpc.gascap`. - let (limit, clamp_to_gas_cap) = match (token_fee_info.balance_slot, fee_limit) { - (Some(_), Some(limit)) if !limit.is_zero() => (token_fee_info.balance.min(limit), false), - (Some(_), _) => (token_fee_info.balance, false), - (None, Some(limit)) if !limit.is_zero() => (limit, true), - (None, _) => return Ok(gas_cap), - }; - - let allowance = gas_allowance_from_token_limit(limit, l1_fee, token_fee_info, gas_price)?; - Ok(if clamp_to_gas_cap { - allowance.min(gas_cap) - } else { - allowance - }) + let limit = token_fee_info.effective_fee_limit(fee_limit.unwrap_or_default()); + gas_allowance_from_token_limit(limit, l1_fee, token_fee_info, gas_price) } -/// Convert a token-denominated affordability cap into a gas allowance. +/// Convert a token-denominated affordability cap into an exact gas allowance. +/// +/// Execution charges `ceil((l1_fee + gas * gas_price) * scale / price_ratio) <= limit_token`. +/// For integers `limit_token >= 0` and `price_ratio > 0`, `ceil(A / price_ratio) <= limit_token` +/// holds iff `A <= limit_token * price_ratio`, i.e.: /// -/// Subtracts the L1 fee (converted to tokens) from `limit_token`, then -/// converts the remaining token budget back to ETH and divides by -/// `gas_price`. Returns `InsufficientFundsForL1Fee` if the L1 fee swallows -/// the entire limit, matching the semantics surfaced for the ETH path. +/// `l1_fee + gas * gas_price <= floor((limit_token * price_ratio) / scale)` +/// +/// Evaluating `limit_token * price_ratio` in [`U512`] avoids both intermediate `U256` saturation +/// and the double-rounding loss of converting `l1_fee` to whole tokens first. fn gas_allowance_from_token_limit( limit_token: U256, l1_fee: U256, token_info: &TokenFeeInfo, gas_price: u128, ) -> Result { - let l1_fee_in_token = token_info.eth_to_token_amount(l1_fee); - if l1_fee_in_token >= limit_token { + if token_info.price_ratio.is_zero() || token_info.scale.is_zero() { + return Err(MorphEthApiError::InvalidFeeToken); + } + + let max_total_eth_u512 = (U512::from(limit_token) * U512::from(token_info.price_ratio)) + / U512::from(token_info.scale); + let max_total_eth = max_total_eth_u512.saturating_to::(); + + if l1_fee >= max_total_eth { return Err(MorphEthApiError::InsufficientFundsForL1Fee); } - let available_token = limit_token - l1_fee_in_token; - let available_eth = token_amount_to_eth(available_token, token_info) - .ok_or(MorphEthApiError::InvalidFeeToken)?; + let available_eth = max_total_eth - l1_fee; Ok(gas_allowance_from_balance(available_eth, gas_price)) } @@ -309,23 +312,6 @@ fn gas_allowance_from_balance(balance: U256, gas_price: u128) -> u64 { saturating_div_u128(balance, gas_price) } -/// `eth = floor(token_amount * price_ratio / scale)`. `None` if -/// `price_ratio` or `scale` is zero. -/// -/// Floor (not ceil) is deliberate: this is the inverse of the -/// protocol's `eth_to_token_amount`, which ceils to protect the -/// protocol (undercharging loses revenue). An affordability budget -/// must round in the opposite direction — the largest `eth` such -/// that the corresponding token charge still fits the user's -/// balance. With non-1:1 ratios, ceiling here would over-promise a -/// gas budget the user cannot actually settle at execution time. -fn token_amount_to_eth(token_amount: U256, info: &TokenFeeInfo) -> Option { - if info.price_ratio.is_zero() || info.scale.is_zero() { - return None; - } - Some(token_amount.saturating_mul(info.price_ratio) / info.scale) -} - #[cfg(test)] mod tests { use super::*; @@ -416,30 +402,58 @@ mod tests { } } - /// EVM-call mode with a user-supplied `fee_limit` that covers the L1 fee - /// must return the remaining-budget gas, never `u64::MAX`. + /// Both call-mode (`balance_slot == None`) and slot-mode (`balance_slot == Some(_)`) + /// resolve the caller's real token balance via `load_for_caller` and bound by + /// `effective_fee_limit(fee_limit)` = `min(balance, fee_limit)` (or `balance` when `fee_limit == 0`). #[test] - fn token_evm_call_mode_with_fee_limit_uses_user_budget() { - let token = token_1to1(None, U256::ZERO); - let allowance = token_gas_allowance( - /* eth_balance */ U256::from(1u64), - /* value */ U256::ZERO, - &token, - /* l1_fee */ U256::from(10u64), - /* fee_limit */ Some(U256::from(110u64)), - /* gas_price */ 1, - /* gas_cap */ 50_000_000, - ) - .expect("fee_limit covers L1 fee with 100 wei to spare"); - // (110 - 10) / 1 = 100 gas - assert_eq!(allowance, 100); + fn token_call_and_slot_modes_cap_by_min_of_resolved_balance_and_fee_limit() { + for balance_slot in [None, Some(U256::from(42u64))] { + let token = token_1to1(balance_slot, /* balance */ U256::from(1_000u64)); + + // fee_limit < balance → fee_limit binds. + let allowance = token_gas_allowance( + U256::ZERO, + U256::ZERO, + &token, + /* l1_fee */ U256::from(50u64), + /* fee_limit */ Some(U256::from(500u64)), + /* gas_price */ 1, + ) + .expect("balance covers L1 fee"); + assert_eq!(allowance, 450); + + // fee_limit > balance → balance binds. + let allowance = token_gas_allowance( + U256::ZERO, + U256::ZERO, + &token, + U256::from(50u64), + Some(U256::from(10_000u64)), + 1, + ) + .expect("balance covers L1 fee"); + assert_eq!(allowance, 950); + + // No fee_limit or explicit Some(0) → balance binds. + for unlimited in [None, Some(U256::ZERO)] { + let allowance = token_gas_allowance( + U256::ZERO, + U256::ZERO, + &token, + U256::from(50u64), + unlimited, + 1, + ) + .expect("balance covers L1 fee"); + assert_eq!(allowance, 950); + } + } } - /// EVM-call mode + `fee_limit` ≤ L1 fee: surface `InsufficientFundsForL1Fee` - /// rather than silently capping at zero. + /// L1 fee >= effective token budget surfaces `InsufficientFundsForL1Fee`. #[test] - fn token_evm_call_mode_l1_fee_swallows_limit_returns_clear_error() { - let token = token_1to1(None, U256::ZERO); + fn token_l1_fee_swallows_limit_returns_clear_error() { + let token = token_1to1(None, U256::from(1_000u64)); let err = token_gas_allowance( U256::ZERO, U256::ZERO, @@ -447,101 +461,16 @@ mod tests { /* l1_fee */ U256::from(100u64), /* fee_limit */ Some(U256::from(50u64)), 1, - 50_000_000, ) .expect_err("fee_limit cannot cover L1 fee"); assert!(matches!(err, MorphEthApiError::InsufficientFundsForL1Fee)); } - /// EVM-call mode without a `fee_limit` must cap at the per-call `gas_cap`, - /// never `u64::MAX` (which lets estimateGas binary-search 25× the - /// block_gas_limit of free EVM work). - #[test] - fn token_evm_call_mode_without_fee_limit_falls_back_to_gas_cap() { - let token = token_1to1(None, U256::ZERO); - let cap = 5_000_000u64; - let allowance = token_gas_allowance( - U256::ZERO, - U256::ZERO, - &token, - /* l1_fee */ U256::from(123u64), - /* fee_limit */ None, - 1, - cap, - ) - .expect("no fee_limit must fall back to gas_cap, not u64::MAX"); - assert_eq!(allowance, cap, "must equal gas_cap, not u64::MAX"); - - // Same with explicit Some(0), which the production code treats as - // "no usable cap" via the `if !limit.is_zero()` guard. - let allowance = token_gas_allowance( - U256::ZERO, - U256::ZERO, - &token, - U256::from(123u64), - Some(U256::ZERO), - 1, - cap, - ) - .expect("Some(0) fee_limit must fall back to gas_cap"); - assert_eq!(allowance, cap); - } - - /// Slot-mode regression: `min(balance, fee_limit)` budget; gas_cap unused. - #[test] - fn token_slot_mode_caps_by_min_of_balance_and_fee_limit() { - let token = token_1to1( - Some(U256::from(42u64)), - /* balance */ U256::from(1_000u64), - ); - - // fee_limit < balance → fee_limit binds. - let allowance = token_gas_allowance( - U256::ZERO, - U256::ZERO, - &token, - /* l1_fee */ U256::from(50u64), - /* fee_limit */ Some(U256::from(500u64)), - /* gas_price */ 1, - /* gas_cap (must NOT leak in) */ 9_999, - ) - .expect("balance covers L1 fee"); - // (500 - 50) / 1 = 450 - assert_eq!(allowance, 450); - - // fee_limit > balance → balance binds. - let allowance = token_gas_allowance( - U256::ZERO, - U256::ZERO, - &token, - U256::from(50u64), - Some(U256::from(10_000u64)), - 1, - 9_999, - ) - .expect("balance covers L1 fee"); - // (1000 - 50) / 1 = 950 - assert_eq!(allowance, 950); - - // No fee_limit → balance binds. - let allowance = token_gas_allowance( - U256::ZERO, - U256::ZERO, - &token, - U256::from(50u64), - None, - 1, - 9_999, - ) - .expect("balance covers L1 fee"); - assert_eq!(allowance, 950); - } - /// Inactive / misconfigured token returns InvalidFeeToken before any /// limit math runs (regardless of mode). #[test] fn token_inactive_or_misconfigured_returns_invalid_fee_token() { - let mut token = token_1to1(None, U256::ZERO); + let mut token = token_1to1(None, U256::from(1_000u64)); token.is_active = false; let err = token_gas_allowance( U256::ZERO, @@ -550,78 +479,201 @@ mod tests { U256::ZERO, Some(U256::from(1_000u64)), 1, - 50_000_000, ) .expect_err("inactive token must reject"); assert!(matches!(err, MorphEthApiError::InvalidFeeToken)); let mut token = token_1to1(Some(U256::from(1u64)), U256::from(1_000u64)); token.price_ratio = U256::ZERO; - let err = token_gas_allowance( - U256::ZERO, - U256::ZERO, - &token, - U256::ZERO, - None, - 1, - 50_000_000, - ) - .expect_err("zero price_ratio must reject"); + let err = token_gas_allowance(U256::ZERO, U256::ZERO, &token, U256::ZERO, None, 1) + .expect_err("zero price_ratio must reject"); + assert!(matches!(err, MorphEthApiError::InvalidFeeToken)); + + let mut token = token_1to1(Some(U256::from(1u64)), U256::from(1_000u64)); + token.scale = U256::ZERO; + let err = token_gas_allowance(U256::ZERO, U256::ZERO, &token, U256::ZERO, None, 1) + .expect_err("zero scale must reject"); assert!(matches!(err, MorphEthApiError::InvalidFeeToken)); } - /// EVM-call mode with an absurd user-supplied `fee_limit` (e.g. - /// `U256::MAX`) must clamp to `gas_cap`, never bypass the - /// operator-configured `--rpc.gascap < block_gas_limit`. + /// Exact ETH-space conversion avoids L1-fee double-rounding and `U256` overflow: + /// 1) When `scale=1, price_ratio=10`, 1 token buys up to 10 wei total (`ceil((6 + 4) / 10) == 1`), + /// so `l1_fee = 6` leaves 4 wei of execution gas rather than falsely failing `ceil(6/10) >= 1`. + /// 2) Non-unit `scale=10, price_ratio=3`: 1..=3 tokens afford 0 wei, 4 tokens afford 1 wei. + /// 3) Huge `limit_token * price_ratio > U256::MAX` uses `U512` instead of prematurely saturating. #[test] - fn token_evm_call_mode_huge_fee_limit_clamps_to_gas_cap() { - let token = token_1to1(None, U256::ZERO); - let cap = 5_000_000u64; - let allowance = token_gas_allowance( - U256::ZERO, - U256::ZERO, - &token, - /* l1_fee */ U256::ZERO, - /* fee_limit */ Some(U256::MAX), + fn gas_allowance_from_token_limit_uses_exact_u512_eth_budget() { + let coarse_token = TokenFeeInfo { + price_ratio: U256::from(10u64), + scale: U256::from(1u64), + ..token_1to1(None, U256::from(1u64)) + }; + let allowance = gas_allowance_from_token_limit( + /* limit_token */ U256::from(1u64), + /* l1_fee */ U256::from(6u64), + &coarse_token, /* gas_price */ 1, - /* gas_cap */ cap, ) - .expect("huge fee_limit must clamp, not error"); - assert_eq!(allowance, cap, "must clamp to gas_cap, not u64::MAX"); - } + .expect("1 token worth 10 wei covers 6 wei L1 fee + 4 gas"); + assert_eq!(allowance, 4); + assert_eq!( + coarse_token.eth_to_token_amount(U256::from(6u64 + 4u64)), + U256::from(1u64) + ); - /// `token_amount_to_eth` must floor, not ceil. Inverse of - /// `eth_to_token_amount` (which ceils for protocol safety): an - /// affordability budget must round toward the user so the returned - /// wei budget is settleable at execution time. - #[test] - fn token_amount_to_eth_floors_non_unit_ratio() { - // scale=10, price_ratio=3. eth_to_token_amount(1 wei) = ceil(10/3) = 4 - // tokens. So 1 token cannot afford even 1 wei of gas — budget = 0. - let info = TokenFeeInfo { + let fractional_token = TokenFeeInfo { price_ratio: U256::from(3u64), scale: U256::from(10u64), - ..token_1to1(None, U256::ZERO) + ..token_1to1(None, U256::from(10u64)) }; + for insufficient in [1u64, 3u64] { + let err = gas_allowance_from_token_limit( + U256::from(insufficient), + U256::ZERO, + &fractional_token, + 1, + ) + .expect_err("cannot afford 1 wei"); + assert!(matches!(err, MorphEthApiError::InsufficientFundsForL1Fee)); + } assert_eq!( - token_amount_to_eth(U256::from(1u64), &info), - Some(U256::ZERO) + gas_allowance_from_token_limit(U256::from(4u64), U256::ZERO, &fractional_token, 1) + .unwrap(), + 1 ); assert_eq!( - token_amount_to_eth(U256::from(3u64), &info), - Some(U256::ZERO) + gas_allowance_from_token_limit(U256::from(10u64), U256::ZERO, &fractional_token, 1) + .unwrap(), + 3 ); - // 4 tokens → floor(12/10) = 1 wei. Roundtrip check: - // eth_to_token_amount(1) = ceil(10/3) = 4, so 4 tokens → 1 wei is - // exactly settleable. - assert_eq!( - token_amount_to_eth(U256::from(4u64), &info), - Some(U256::from(1u64)) + + // `limit_token * price_ratio > U256::MAX` with `scale = 1e18` still computes exact quotient. + let scale = U256::from(10u128.pow(18)); + let high_ratio_token = TokenFeeInfo { + price_ratio: scale, + scale, + ..token_1to1(None, U256::MAX) + }; + let huge_limit = U256::MAX / U256::from(2u64); + let allowance = gas_allowance_from_token_limit( + huge_limit, + U256::from(1_000u64), + &high_ratio_token, + 1_000_000_000, + ) + .expect("U512 product/quotient must not overflow"); + assert_eq!(allowance, u64::MAX); + } + + #[test] + fn load_token_fee_info_for_allowance_resolves_call_mode_and_propagates_db_errors() { + use alloy_primitives::{B256, address, bytes}; + use evm2::{ + bytecode::Bytecode, + evm::{AccountInfo, CacheDB, DynDatabase, EmptyDB, InMemoryDB}, + }; + use morph_chainspec::hardfork::MorphHardfork; + use morph_revm::{L2_TOKEN_REGISTRY_ADDRESS, MorphBlockEnv, compute_mapping_slot}; + + struct TestDb { + inner: InMemoryDB, + fail_reads: bool, + } + + impl Database for TestDb { + type Error = ProviderError; + + fn get_account(&mut self, addr: &Address) -> Result, Self::Error> { + if self.fail_reads { + return Err(ProviderError::BestBlockNotFound); + } + Ok(DynDatabase::get_account(&mut self.inner, addr).unwrap()) + } + + fn get_code_by_hash(&mut self, hash: &B256) -> Result { + if self.fail_reads { + return Err(ProviderError::BestBlockNotFound); + } + Ok(DynDatabase::get_code_by_hash(&mut self.inner, hash).unwrap()) + } + + fn get_storage(&mut self, addr: &Address, slot: &U256) -> Result { + if self.fail_reads { + return Err(ProviderError::BestBlockNotFound); + } + Ok(DynDatabase::get_storage(&mut self.inner, addr, slot).unwrap()) + } + + fn get_block_hash(&mut self, num: &U256) -> Result { + Ok(DynDatabase::get_block_hash(&mut self.inner, num).unwrap()) + } + } + + let token = address!("5300000000000000000000000000000000000042"); + let caller = address!("1000000000000000000000000000000000000001"); + let mut inner: InMemoryDB = CacheDB::new(EmptyDB::default()); + let mut key = [0u8; 32]; + key[31] = 1; + let base = compute_mapping_slot(U256::from(151), &key); + let mut packed = [0u8; 32]; + packed[30] = 18; + packed[31] = 1; + inner.insert_account_storage( + &L2_TOKEN_REGISTRY_ADDRESS, + &base, + &U256::from_be_bytes(token.into_word().0), ); - // Exact multiple: 10 tokens → 3 wei (floor and ceil agree). - assert_eq!( - token_amount_to_eth(U256::from(10u64), &info), - Some(U256::from(3u64)) + inner.insert_account_storage( + &L2_TOKEN_REGISTRY_ADDRESS, + &(base + U256::from(1)), + &U256::ZERO, + ); + inner.insert_account_storage( + &L2_TOKEN_REGISTRY_ADDRESS, + &(base + U256::from(2)), + &U256::from_be_bytes(packed), + ); + inner.insert_account_storage( + &L2_TOKEN_REGISTRY_ADDRESS, + &(base + U256::from(3)), + &U256::ONE, + ); + inner.insert_account_storage( + &L2_TOKEN_REGISTRY_ADDRESS, + &compute_mapping_slot(U256::from(153), &key), + &U256::ONE, + ); + inner.insert_account_info( + &token, + AccountInfo::default().with_code(Bytecode::new_legacy(bytes!("6000545f5260205ff3"))), + ); + inner.insert_account_storage(&token, &U256::ZERO, &U256::from(420_000u64)); + + let env = MorphEvmEnv::new(MorphHardfork::Celadon, MorphBlockEnv::default(), 2818); + + // 1. Call-mode resolves real `balanceOf`. + let mut ok_db = TestDb { + inner: inner.clone(), + fail_reads: false, + }; + let info = load_token_fee_info_for_allowance(&mut ok_db, 1, caller, &env).unwrap(); + assert_eq!(info.balance, U256::from(420_000u64)); + + // 2. Unregistered token -> `InvalidFeeToken`. + assert!(matches!( + load_token_fee_info_for_allowance(&mut ok_db, 99, caller, &env).unwrap_err(), + MorphEthApiError::InvalidFeeToken + )); + + // 3. Database failure -> `MorphEthApiError::Eth(...)`, NOT `InvalidFeeToken`. + let mut err_db = TestDb { + inner, + fail_reads: true, + }; + let err = load_token_fee_info_for_allowance(&mut err_db, 1, caller, &env).unwrap_err(); + assert!( + matches!(err, MorphEthApiError::Eth(_)), + "DB failure must propagate as Eth error, got {err:?}" ); } } diff --git a/crates/txpool/Cargo.toml b/crates/txpool/Cargo.toml index e164d3b6..3d5c4ca2 100644 --- a/crates/txpool/Cargo.toml +++ b/crates/txpool/Cargo.toml @@ -35,6 +35,7 @@ alloy-primitives.workspace = true # Misc c-kzg = "2.1.5" +dashmap.workspace = true derive_more.workspace = true futures.workspace = true parking_lot.workspace = true diff --git a/crates/txpool/src/error.rs b/crates/txpool/src/error.rs index d676b0bb..24418c99 100644 --- a/crates/txpool/src/error.rs +++ b/crates/txpool/src/error.rs @@ -33,6 +33,12 @@ pub enum MorphTxError { token_id: u16, }, + /// Token scale is zero or invalid. + InvalidTokenScale { + /// The token ID with invalid scale. + token_id: u16, + }, + /// Insufficient ERC20 token balance to pay for gas. InsufficientTokenBalance { /// The token ID. @@ -87,6 +93,9 @@ impl fmt::Display for MorphTxError { Self::InvalidPriceRatio { token_id } => { write!(f, "token ID {token_id} has invalid price ratio (zero)") } + Self::InvalidTokenScale { token_id } => { + write!(f, "token ID {token_id} has invalid scale (zero)") + } Self::InsufficientTokenBalance { token_id, token_address, @@ -128,8 +137,8 @@ impl PoolTransactionError for MorphTxError { Self::InvalidFormat { .. } => true, // Token not found or not active - could be due to temporary state, not penalizable Self::TokenNotFound { .. } | Self::TokenNotActive { .. } => false, - // Invalid price ratio - configuration issue, not penalizable - Self::InvalidPriceRatio { .. } => false, + // Invalid price ratio or scale - configuration issue, not penalizable + Self::InvalidPriceRatio { .. } | Self::InvalidTokenScale { .. } => false, // Insufficient balance or fee limit - normal validation failure Self::InsufficientTokenBalance { .. } | Self::InsufficientEthForValue { .. } => false, // Fetch failures - infrastructure issue, not penalizable @@ -258,6 +267,7 @@ mod tests { assert!(!MorphTxError::TokenNotFound { token_id: 1 }.is_bad_transaction()); assert!(!MorphTxError::TokenNotActive { token_id: 1 }.is_bad_transaction()); assert!(!MorphTxError::InvalidPriceRatio { token_id: 1 }.is_bad_transaction()); + assert!(!MorphTxError::InvalidTokenScale { token_id: 1 }.is_bad_transaction()); assert!( !MorphTxError::TokenInfoFetchFailed { token_id: 1, @@ -275,6 +285,7 @@ mod tests { MorphTxError::TokenNotFound { token_id: 1 }, MorphTxError::TokenNotActive { token_id: 2 }, MorphTxError::InvalidPriceRatio { token_id: 3 }, + MorphTxError::InvalidTokenScale { token_id: 3 }, MorphTxError::InsufficientTokenBalance { token_id: 4, token_address: Address::ZERO, diff --git a/crates/txpool/src/lib.rs b/crates/txpool/src/lib.rs index 52ca426b..2368198b 100644 --- a/crates/txpool/src/lib.rs +++ b/crates/txpool/src/lib.rs @@ -35,6 +35,8 @@ mod error; pub use error::MorphTxError; +pub(crate) mod state_cache; + mod transaction; pub use transaction::MorphPooledTransaction; diff --git a/crates/txpool/src/maintain.rs b/crates/txpool/src/maintain.rs index a51d8e0c..ac3d38f2 100644 --- a/crates/txpool/src/maintain.rs +++ b/crates/txpool/src/maintain.rs @@ -21,14 +21,18 @@ //! and `demoteUnexecutables` (tx_pool.go), but implemented as a separate //! maintenance task since we cannot modify reth's internal pool logic. -use crate::MorphPooledTransaction; +use crate::{ + MorphPooledTransaction, + morph_tx_validation::validate_morph_tx_with, + state_cache::{StateCache, StateCacheDb, TokenFeeValidator, morph_evm_env_from_header}, +}; use alloy_consensus::Transaction; use alloy_consensus::Typed2718; use alloy_primitives::{Address, TxHash, U256}; use futures::StreamExt; use morph_chainspec::hardfork::MorphHardforks; use morph_revm::L1BlockInfo; -use reth_chainspec::ChainSpecProvider; +use reth_chainspec::{ChainSpecProvider, EthChainSpec}; use reth_evm::{Database, database::StateProviderDatabase}; use reth_primitives_traits::AlloyBlockHeader; use reth_provider::CanonStateSubscriptions; @@ -117,7 +121,7 @@ fn exceeds_block_gas_limit(tx_gas_limit: u64, block_gas_limit: u64) -> bool { pub async fn maintain_morph_pool(pool: Pool, client: Client) where Pool: TransactionPool + Clone, - Client: ChainSpecProvider + Client: ChainSpecProvider + StateProviderFactory + CanonStateSubscriptions + Clone @@ -176,7 +180,9 @@ where } }; - let mut db = StateProviderDatabase::new((&state_provider).into_evm_state_provider()); + let evm_state_provider = (&state_provider).into_evm_state_provider(); + let cache = StateCache::default(); + let mut db = StateCacheDb::new(&cache, StateProviderDatabase::new(&evm_state_provider)); // Fetch L1 block info for fee calculation let l1_block_info = match L1BlockInfo::try_fetch(&mut db, hardfork) { @@ -191,6 +197,14 @@ where } }; + let evm_env = + morph_evm_env_from_header(hardfork, client.chain_spec().chain().id(), new_tip.header()); + let mut token_validator = TokenFeeValidator::new( + &cache, + StateProviderDatabase::new(&evm_state_provider), + evm_env, + ); + tracing::trace!( target: "morph::txpool::maintain", count = morph_txs.len(), @@ -260,7 +274,9 @@ where hardfork, }; - let validation = match crate::validate_morph_tx(&mut db, &input) { + let validation = match validate_morph_tx_with(&input, |token_id, caller| { + token_validator.resolve_token_fee_info(token_id, caller) + }) { Ok(v) => v, Err(err) => { tracing::debug!( diff --git a/crates/txpool/src/morph_tx_validation.rs b/crates/txpool/src/morph_tx_validation.rs index 4da1ae75..f524dd66 100644 --- a/crates/txpool/src/morph_tx_validation.rs +++ b/crates/txpool/src/morph_tx_validation.rs @@ -13,7 +13,10 @@ use morph_primitives::{ use morph_revm::{MorphEvmEnv, TokenFeeInfo}; use reth_evm::Database; -use crate::MorphTxError; +use crate::{ + MorphTxError, + state_cache::{StateCache, TokenFeeValidator}, +}; /// High-level input for MorphTx validation. /// @@ -56,6 +59,22 @@ pub struct MorphTxValidationResult { pub fn validate_morph_tx( db: &mut DB, input: &MorphTxValidationInput<'_>, +) -> Result { + let cache = StateCache::default(); + let env = MorphEvmEnv::new(input.hardfork, morph_revm::MorphBlockEnv::default(), 1); + let mut validator = TokenFeeValidator::new(&cache, db, env); + validate_morph_tx_with(input, |token_id, sender| { + validator.resolve_token_fee_info(token_id, sender) + }) +} + +/// Validates a MorphTx transaction using a caller-supplied fee-token resolver. +/// +/// Structural rules, ETH `value` coverage, and `fee_token_id == 0` ETH-fee checks run before +/// `resolve_token`, so invalid or ETH-paid MorphTxs never touch token registry state. +pub(crate) fn validate_morph_tx_with( + input: &MorphTxValidationInput<'_>, + resolve_token: impl FnOnce(u16, Address) -> Result, ) -> Result { // Keep MorphTx structural validation in the shared path so both initial // admission and background revalidation enforce the same invariants. @@ -121,33 +140,7 @@ pub fn validate_morph_tx( }); } - // Pool admission has no block environment, so a call-mode token's `balanceOf` - // is evaluated under the hardfork's defaults. That matches the pool's previous - // behaviour; threading the real head environment through admission is txpool - // work and does not belong in this change. - let env = MorphEvmEnv::new(input.hardfork, morph_revm::MorphBlockEnv::default(), 1); - let token_info = TokenFeeInfo::load_for_caller(db, fee_token_id, input.sender, &env) - .map_err(|err| MorphTxError::TokenInfoFetchFailed { - token_id: fee_token_id, - message: format!("{err:?}"), - })? - .ok_or(MorphTxError::TokenNotFound { - token_id: fee_token_id, - })?; - - // Check token is active - if !token_info.is_active { - return Err(MorphTxError::TokenNotActive { - token_id: fee_token_id, - }); - } - - // Check price ratio is valid - if token_info.price_ratio.is_zero() { - return Err(MorphTxError::InvalidPriceRatio { - token_id: fee_token_id, - }); - } + let token_info = resolve_token(fee_token_id, input.sender)?; // Txpool admission follows geth's conservative budget check and requires // enough tokens for the max fee cap. Execution still charges the effective price. diff --git a/crates/txpool/src/state_cache.rs b/crates/txpool/src/state_cache.rs new file mode 100644 index 00000000..da947e9d --- /dev/null +++ b/crates/txpool/src/state_cache.rs @@ -0,0 +1,520 @@ +//! Tip-scoped concurrent state cache and reusable `evm2` token-fee validator for Morph txpool. + +use crate::MorphTxError; +use alloy_consensus::BlockHeader; +use alloy_primitives::{Address, B256, U256, map::DefaultHashBuilder}; +use dashmap::DashMap; +use evm2::{ + bytecode::Bytecode, + evm::{AccountInfo, Database, Db}, + registry::HandlerError, +}; +use morph_chainspec::hardfork::MorphHardfork; +use morph_revm::{ + MorphBlockEnv, MorphEvm, MorphEvmEnv, TokenFeeInfo, TokenRegistryEntry, morph_evm, + morph_evm_env, +}; +use std::sync::atomic::{AtomicUsize, Ordering}; + +/// Concurrent cache of raw state reads and resolved token-fee queries anchored to a single tip. +/// +/// Transaction admission and pool maintenance repeatedly read the same L2 token registry slots, +/// token contract bytecode, and sender balances across transactions. Anchoring this cache to a +/// canonical tip hash lets all concurrent validations at that tip share reads in memory while +/// replacing the cache atomically whenever the head block advances. +#[derive(Debug, Default)] +pub(crate) struct StateCache { + /// Cached basic account info, including non-existent accounts (`None`). + accounts: DashMap, DefaultHashBuilder>, + /// Cached storage values keyed by `(account, slot)`. + storage: DashMap<(Address, U256), U256, DefaultHashBuilder>, + /// Cached contract bytecode keyed by `code_hash`. + contracts: DashMap, + /// Cached L2 token registry metadata keyed by `token_id`. + registry_entries: DashMap, DefaultHashBuilder>, + /// Cached call-mode `balanceOf` outcomes keyed by `(caller, token_id)`. + /// + /// Stores `Ok(balance)` on success and `Err(reason)` on deterministic EVM query failures + /// (`TokenBalanceQueryFailed`). Transient database read errors (`HandlerError::Database`) are + /// never inserted here so a retry against healthy storage can succeed. + call_balances: DashMap<(Address, u16), Result, DefaultHashBuilder>, + account_count: AtomicUsize, + storage_count: AtomicUsize, + contract_count: AtomicUsize, + registry_count: AtomicUsize, + call_balance_count: AtomicUsize, +} + +impl StateCache { + const MAX_ACCOUNTS: usize = 1 << 17; + const MAX_STORAGE_SLOTS: usize = 1 << 18; + const MAX_CONTRACTS: usize = 1 << 12; + const MAX_REGISTRY_ENTRIES: usize = 1 << 12; + const MAX_CALL_BALANCES: usize = 1 << 16; + + fn insert_registry_entry(&self, token_id: u16, entry: Option) { + if self.registry_count.load(Ordering::Relaxed) < Self::MAX_REGISTRY_ENTRIES + && self.registry_entries.insert(token_id, entry).is_none() + { + self.registry_count.fetch_add(1, Ordering::Relaxed); + } + } + + fn insert_call_balance(&self, key: (Address, u16), outcome: Result) { + if self.call_balance_count.load(Ordering::Relaxed) < Self::MAX_CALL_BALANCES + && self.call_balances.insert(key, outcome).is_none() + { + self.call_balance_count.fetch_add(1, Ordering::Relaxed); + } + } +} + +/// [`Database`] adapter that serves reads from a shared [`StateCache`] and populates it on miss. +#[derive(Debug)] +pub(crate) struct StateCacheDb<'a, DB> { + cache: &'a StateCache, + db: DB, +} + +impl<'a, DB> StateCacheDb<'a, DB> { + pub(crate) const fn new(cache: &'a StateCache, db: DB) -> Self { + Self { cache, db } + } +} + +impl Database for StateCacheDb<'_, DB> { + type Error = DB::Error; + + fn is_fatal(error: &Self::Error) -> bool { + DB::is_fatal(error) + } + + fn get_account(&mut self, address: &Address) -> Result, Self::Error> { + if let Some(account) = self.cache.accounts.get(address) { + return Ok(account.clone()); + } + let account = self.db.get_account(address)?; + if self.cache.account_count.load(Ordering::Relaxed) < StateCache::MAX_ACCOUNTS + && self + .cache + .accounts + .insert(*address, account.clone()) + .is_none() + { + self.cache.account_count.fetch_add(1, Ordering::Relaxed); + } + Ok(account) + } + + fn get_code_by_hash(&mut self, code_hash: &B256) -> Result { + if let Some(code) = self.cache.contracts.get(code_hash) { + return Ok(code.clone()); + } + let code = self.db.get_code_by_hash(code_hash)?; + if self.cache.contract_count.load(Ordering::Relaxed) < StateCache::MAX_CONTRACTS + && self + .cache + .contracts + .insert(*code_hash, code.clone()) + .is_none() + { + self.cache.contract_count.fetch_add(1, Ordering::Relaxed); + } + Ok(code) + } + + fn get_storage(&mut self, address: &Address, index: &U256) -> Result { + if let Some(value) = self.cache.storage.get(&(*address, *index)) { + return Ok(*value); + } + let value = self.db.get_storage(address, index)?; + if self.cache.storage_count.load(Ordering::Relaxed) < StateCache::MAX_STORAGE_SLOTS + && self + .cache + .storage + .insert((*address, *index), value) + .is_none() + { + self.cache.storage_count.fetch_add(1, Ordering::Relaxed); + } + Ok(value) + } + + fn get_block_hash(&mut self, number: &U256) -> Result { + self.db.get_block_hash(number) + } +} + +/// Reusable `evm2`-backed token-fee resolver for a batch of transactions or maintenance pass. +/// +/// Constructing [`MorphEvm`] once per batch is essentially free (`InterpreterPool` and `State` +/// allocate nothing until a call-mode `balanceOf` actually runs), and when call-mode tokens are +/// queried, the pooled interpreter frame and backing [`StateCache`] are reused across every +/// transaction without any manual frame-stack teardown. +pub(crate) struct TokenFeeValidator<'a> { + cache: &'a StateCache, + evm: MorphEvm<'a>, +} + +impl<'a> TokenFeeValidator<'a> { + /// Creates a reusable validator backed by `cache` and `db` under `env`. + pub(crate) fn new(cache: &'a StateCache, db: DB, env: MorphEvmEnv) -> Self { + let cached_db = StateCacheDb::new(cache, db); + Self { + cache, + evm: morph_evm(Db::new(cached_db), env), + } + } + + /// Resolves and validates `token_id` metadata and `caller`'s token balance. + /// + /// Enforces registry usability (`is_active`, non-zero `price_ratio`, non-zero `scale`) + /// strictly before any call-mode `balanceOf` execution. + pub(crate) fn resolve_token_fee_info( + &mut self, + token_id: u16, + caller: Address, + ) -> Result { + let entry = + match self.cache.registry_entries.get(&token_id) { + Some(cached) => *cached, + None => { + let loaded = TokenRegistryEntry::load_from_evm(&mut self.evm, token_id) + .map_err(|err| MorphTxError::TokenInfoFetchFailed { + token_id, + message: err.to_string(), + })?; + self.cache.insert_registry_entry(token_id, loaded); + loaded + } + }; + + let entry = entry.ok_or(MorphTxError::TokenNotFound { token_id })?; + + if !entry.is_active { + return Err(MorphTxError::TokenNotActive { token_id }); + } + if entry.price_ratio.is_zero() { + return Err(MorphTxError::InvalidPriceRatio { token_id }); + } + if entry.scale.is_zero() { + return Err(MorphTxError::InvalidTokenScale { token_id }); + } + + if entry.balance_slot.is_some() { + let balance = entry + .read_caller_balance_with_evm(&mut self.evm, caller) + .map_err(|err| MorphTxError::TokenInfoFetchFailed { + token_id, + message: err.to_string(), + })?; + return Ok(entry.into_fee_info(caller, balance)); + } + + // Call mode (`balance_slot == None`): deduplicate `balanceOf` per `(caller, token_id)`. + if let Some(cached) = self.cache.call_balances.get(&(caller, token_id)) { + return match cached.value() { + Ok(balance) => Ok(entry.into_fee_info(caller, *balance)), + Err(message) => Err(MorphTxError::TokenInfoFetchFailed { + token_id, + message: message.clone(), + }), + }; + } + + match entry.read_caller_balance_with_evm(&mut self.evm, caller) { + Ok(balance) => { + self.cache + .insert_call_balance((caller, token_id), Ok(balance)); + Ok(entry.into_fee_info(caller, balance)) + } + // Never cache transient state/database read errors as zero or failed balances. + Err(HandlerError::Database(err)) => Err(MorphTxError::TokenInfoFetchFailed { + token_id, + message: err.to_string(), + }), + Err(err) => { + let message = err.to_string(); + self.cache + .insert_call_balance((caller, token_id), Err(message.clone())); + Err(MorphTxError::TokenInfoFetchFailed { token_id, message }) + } + } + } +} + +/// Builds the [`MorphEvmEnv`] matching a canonical block header so call-mode `balanceOf` queries +/// in admission and maintenance observe the real chain ID and block context. +pub(crate) fn morph_evm_env_from_header( + hardfork: MorphHardfork, + chain_id: u64, + header: &H, +) -> MorphEvmEnv { + let block_env = MorphBlockEnv { + number: U256::from(header.number()), + beneficiary: header.beneficiary(), + timestamp: U256::from(header.timestamp()), + difficulty: header.difficulty(), + prevrandao: header + .mix_hash() + .map(|hash| U256::from_be_bytes(hash.0)) + .unwrap_or_default(), + gas_limit: U256::from(header.gas_limit()), + basefee: U256::from(header.base_fee_per_gas().unwrap_or_default()), + blob_basefee: U256::ONE, + ..Default::default() + }; + morph_evm_env(hardfork, chain_id, header.gas_limit(), block_env) +} + +#[cfg(test)] +mod tests { + use super::*; + use alloy_primitives::{Bytes, address, bytes}; + use evm2::evm::{CacheDB, DynDatabase, EmptyDB, InMemoryDB}; + use morph_revm::{L2_TOKEN_REGISTRY_ADDRESS, compute_mapping_slot}; + use std::sync::Arc; + + #[derive(Debug, Clone, Copy)] + struct TransientDbError; + + impl core::fmt::Display for TransientDbError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.write_str("transient storage failure") + } + } + + impl core::error::Error for TransientDbError {} + + struct CountingTokenDb { + inner: InMemoryDB, + token: Address, + fail_token_storage: bool, + token_storage_reads: Arc, + } + + impl Database for CountingTokenDb { + type Error = TransientDbError; + + fn get_account(&mut self, address: &Address) -> Result, Self::Error> { + Ok(DynDatabase::get_account(&mut self.inner, address).unwrap()) + } + + fn get_code_by_hash(&mut self, code_hash: &B256) -> Result { + Ok(DynDatabase::get_code_by_hash(&mut self.inner, code_hash).unwrap()) + } + + fn get_storage(&mut self, address: &Address, index: &U256) -> Result { + if *address == self.token { + self.token_storage_reads.fetch_add(1, Ordering::Relaxed); + if self.fail_token_storage { + return Err(TransientDbError); + } + } + Ok(DynDatabase::get_storage(&mut self.inner, address, index).unwrap()) + } + + fn get_block_hash(&mut self, number: &U256) -> Result { + Ok(DynDatabase::get_block_hash(&mut self.inner, number).unwrap()) + } + } + + fn setup_call_mode_registry( + token_id: u16, + token: Address, + is_active: bool, + price_ratio: U256, + scale: U256, + code: Bytes, + slot0_balance: U256, + ) -> InMemoryDB { + let mut db = CacheDB::new(EmptyDB::default()); + let mut key = [0u8; 32]; + key[30..32].copy_from_slice(&token_id.to_be_bytes()); + let base = compute_mapping_slot(U256::from(151), &key); + + let mut packed = [0u8; 32]; + packed[30] = 18; + packed[31] = u8::from(is_active); + + db.insert_account_storage( + &L2_TOKEN_REGISTRY_ADDRESS, + &base, + &U256::from_be_bytes(token.into_word().0), + ); + db.insert_account_storage( + &L2_TOKEN_REGISTRY_ADDRESS, + &(base + U256::from(1)), + &U256::ZERO, + ); + db.insert_account_storage( + &L2_TOKEN_REGISTRY_ADDRESS, + &(base + U256::from(2)), + &U256::from_be_bytes(packed), + ); + db.insert_account_storage(&L2_TOKEN_REGISTRY_ADDRESS, &(base + U256::from(3)), &scale); + db.insert_account_storage( + &L2_TOKEN_REGISTRY_ADDRESS, + &compute_mapping_slot(U256::from(153), &key), + &price_ratio, + ); + + db.insert_account_info( + &token, + AccountInfo::default().with_code(Bytecode::new_legacy(code)), + ); + db.insert_account_storage(&token, &U256::ZERO, &slot0_balance); + db + } + + #[test] + fn deduplicates_call_mode_balance_and_skips_bytecode_for_unusable_tokens() { + let token = address!("5300000000000000000000000000000000000042"); + let caller = address!("1000000000000000000000000000000000000001"); + let env = MorphEvmEnv::new(MorphHardfork::Celadon, MorphBlockEnv::default(), 2818); + + // 1. Inactive / zero-scale / zero-price tokens never touch `token` storage. + for (is_active, price, scale, expected) in [ + ( + false, + U256::ONE, + U256::ONE, + MorphTxError::TokenNotActive { token_id: 1 }, + ), + ( + true, + U256::ZERO, + U256::ONE, + MorphTxError::InvalidPriceRatio { token_id: 1 }, + ), + ( + true, + U256::ONE, + U256::ZERO, + MorphTxError::InvalidTokenScale { token_id: 1 }, + ), + ] { + let reads = Arc::new(AtomicUsize::new(0)); + let db = CountingTokenDb { + inner: setup_call_mode_registry( + 1, + token, + is_active, + price, + scale, + bytes!("6000545f5260205ff3"), + U256::from(500u64), + ), + token, + fail_token_storage: true, + token_storage_reads: Arc::clone(&reads), + }; + let cache = StateCache::default(); + let mut validator = TokenFeeValidator::new(&cache, db, env.clone()); + assert_eq!( + validator.resolve_token_fee_info(1, caller).unwrap_err(), + expected + ); + assert_eq!(reads.load(Ordering::Relaxed), 0); + } + + // 2. Active call-mode token runs `balanceOf` once and serves subsequent lookups from cache. + let reads = Arc::new(AtomicUsize::new(0)); + let db = CountingTokenDb { + inner: setup_call_mode_registry( + 1, + token, + true, + U256::ONE, + U256::ONE, + bytes!("6000545f5260205ff3"), + U256::from(999_000u64), + ), + token, + fail_token_storage: false, + token_storage_reads: Arc::clone(&reads), + }; + let cache = StateCache::default(); + let mut validator = TokenFeeValidator::new(&cache, db, env); + for _ in 0..5 { + let info = validator.resolve_token_fee_info(1, caller).unwrap(); + assert_eq!(info.balance, U256::from(999_000u64)); + } + assert_eq!(reads.load(Ordering::Relaxed), 1); + } + + #[test] + fn transient_db_errors_are_not_cached_while_deterministic_reverts_are() { + let token = address!("5300000000000000000000000000000000000042"); + let caller = address!("1000000000000000000000000000000000000001"); + let env = MorphEvmEnv::new(MorphHardfork::Celadon, MorphBlockEnv::default(), 2818); + let cache = StateCache::default(); + + // First validator hits a transient DB error during `balanceOf` SLOAD -> must NOT poison `cache`. + let reads = Arc::new(AtomicUsize::new(0)); + let failing_db = CountingTokenDb { + inner: setup_call_mode_registry( + 1, + token, + true, + U256::ONE, + U256::ONE, + bytes!("6000545f5260205ff3"), + U256::from(123_456u64), + ), + token, + fail_token_storage: true, + token_storage_reads: Arc::clone(&reads), + }; + let mut v1 = TokenFeeValidator::new(&cache, failing_db, env.clone()); + assert!(matches!( + v1.resolve_token_fee_info(1, caller).unwrap_err(), + MorphTxError::TokenInfoFetchFailed { token_id: 1, .. } + )); + + // Second validator sharing the same tip `cache` over healthy DB succeeds! + let healthy_db = CountingTokenDb { + inner: setup_call_mode_registry( + 1, + token, + true, + U256::ONE, + U256::ONE, + bytes!("6000545f5260205ff3"), + U256::from(123_456u64), + ), + token, + fail_token_storage: false, + token_storage_reads: Arc::clone(&reads), + }; + let mut v2 = TokenFeeValidator::new(&cache, healthy_db, env.clone()); + let info = v2.resolve_token_fee_info(1, caller).unwrap(); + assert_eq!(info.balance, U256::from(123_456u64)); + + // Deterministic contract revert (`SLOAD(0); PUSH0; PUSH0; REVERT`) IS cached. + let revert_cache = StateCache::default(); + let revert_reads = Arc::new(AtomicUsize::new(0)); + let revert_db = CountingTokenDb { + inner: setup_call_mode_registry( + 1, + token, + true, + U256::ONE, + U256::ONE, + bytes!("600054505f5ffd"), + U256::ZERO, + ), + token, + fail_token_storage: false, + token_storage_reads: Arc::clone(&revert_reads), + }; + let mut v3 = TokenFeeValidator::new(&revert_cache, revert_db, env); + for _ in 0..4 { + assert!(matches!( + v3.resolve_token_fee_info(1, caller).unwrap_err(), + MorphTxError::TokenInfoFetchFailed { token_id: 1, .. } + )); + } + assert_eq!(revert_reads.load(Ordering::Relaxed), 1); + } +} diff --git a/crates/txpool/src/validator.rs b/crates/txpool/src/validator.rs index b85e072e..f0693eb7 100644 --- a/crates/txpool/src/validator.rs +++ b/crates/txpool/src/validator.rs @@ -8,20 +8,27 @@ //! - L1 data fee validation //! - MorphTx (0x7F) ERC20 token balance validation -use crate::MorphTxError; +use crate::{ + MorphTxError, + morph_tx_validation::validate_morph_tx_with, + state_cache::{StateCache, TokenFeeValidator}, +}; use alloy_consensus::{BlockHeader, Transaction}; use alloy_eips::{Encodable2718, Typed2718}; -use alloy_primitives::{Address, U256}; -use morph_chainspec::hardfork::MorphHardforks; +use alloy_primitives::{Address, B256, U256}; +use morph_chainspec::hardfork::{MorphHardfork, MorphHardforks}; use morph_primitives::MorphTxEnvelope; -use morph_revm::L1BlockInfo; +use morph_revm::{L1BlockInfo, MorphBlockEnv, MorphEvmEnv, morph_evm_env}; use parking_lot::RwLock; use reth_chainspec::ChainSpecProvider; use reth_evm::{ConfigureEvm, database::StateProviderDatabase}; use reth_primitives_traits::{ Block, BlockTy, GotExpected, SealedBlock, transaction::error::InvalidTransactionError, }; -use reth_storage_api::{BlockReaderIdExt, StateProvider as _, StateProviderFactory}; +use reth_storage_api::{ + BlockReaderIdExt, StateProvider as _, StateProviderBox, StateProviderFactory, + errors::ProviderResult, +}; use reth_transaction_pool::{ EthPoolTransaction, EthTransactionValidator, PoolTransaction, TransactionOrigin, TransactionValidationOutcome, TransactionValidator, @@ -40,10 +47,11 @@ use std::sync::{ /// `validate_one_with_state` for why we can't rely on reth's Shanghai-gated check. const MAX_INITCODE_SIZE: usize = evm2::constants::MAX_INITCODE_SIZE; -/// Tracks L1 block info for the current chain head. +/// Tracks L1 block info and head header context for the current chain head. /// -/// This is used to cache L1 fee parameters and update them when the chain head changes. -#[derive(Debug, Default)] +/// This is used to cache L1 fee parameters and construct the matching [`MorphEvmEnv`] +/// when the chain head changes. +#[derive(Debug)] pub struct MorphL1BlockInfo { /// The current L1 block info. l1_block_info: RwLock, @@ -53,6 +61,29 @@ pub struct MorphL1BlockInfo { timestamp: AtomicU64, /// Current block number. number: AtomicU64, + /// Current block gas limit. + gas_limit: AtomicU64, + /// Current block beneficiary. + beneficiary: RwLock
, + /// Current block prevrandao / mix_hash. + prevrandao: RwLock, + /// Current block difficulty. + difficulty: RwLock, +} + +impl Default for MorphL1BlockInfo { + fn default() -> Self { + Self { + l1_block_info: RwLock::default(), + base_fee_per_gas: RwLock::default(), + timestamp: AtomicU64::new(0), + number: AtomicU64::new(0), + gas_limit: AtomicU64::new(u64::MAX), + beneficiary: RwLock::default(), + prevrandao: RwLock::default(), + difficulty: RwLock::default(), + } + } } impl MorphL1BlockInfo { @@ -80,6 +111,34 @@ impl MorphL1BlockInfo { self.number.store(number, Ordering::Relaxed); } + /// Records the execution-visible header fields from `header`. + fn update_header(&self, header: &H) { + self.timestamp.store(header.timestamp(), Ordering::Relaxed); + self.number.store(header.number(), Ordering::Relaxed); + self.gas_limit.store(header.gas_limit(), Ordering::Relaxed); + *self.base_fee_per_gas.write() = header.base_fee_per_gas(); + *self.beneficiary.write() = header.beneficiary(); + *self.prevrandao.write() = header.mix_hash().unwrap_or_default(); + *self.difficulty.write() = header.difficulty(); + } + + /// Builds a [`MorphEvmEnv`] from the tracked head header fields. + fn evm_env(&self, hardfork: MorphHardfork, chain_id: u64) -> MorphEvmEnv { + let gas_limit = self.gas_limit.load(Ordering::Relaxed); + let block_env = MorphBlockEnv { + number: U256::from(self.number()), + beneficiary: *self.beneficiary.read(), + timestamp: U256::from(self.timestamp()), + difficulty: *self.difficulty.read(), + prevrandao: U256::from_be_bytes(self.prevrandao.read().0), + gas_limit: U256::from(gas_limit), + basefee: U256::from(self.base_fee_per_gas().unwrap_or_default()), + blob_basefee: U256::ONE, + ..Default::default() + }; + morph_evm_env(hardfork, chain_id, gas_limit, block_env) + } + /// Returns the current block timestamp. pub fn timestamp(&self) -> u64 { self.timestamp.load(Ordering::Relaxed) @@ -123,6 +182,8 @@ pub struct MorphTransactionValidator, /// Additional block info required for validation. block_info: Arc, + /// Tip hash and shared state read cache across validations at the same canonical tip. + cached_state: RwLock<(B256, Arc)>, } impl MorphTransactionValidator { @@ -201,6 +262,7 @@ where Self { inner, block_info: Arc::new(block_info), + cached_state: RwLock::new((B256::ZERO, Arc::new(StateCache::default()))), } } @@ -209,18 +271,27 @@ where where H: BlockHeader, { - self.block_info - .timestamp - .store(header.timestamp(), Ordering::Relaxed); - self.block_info - .number - .store(header.number(), Ordering::Relaxed); - *self.block_info.base_fee_per_gas.write() = header.base_fee_per_gas(); - - let provider = match self - .client() - .state_by_block_number_or_tag(header.number().into()) - { + *self.cached_state.write() = (B256::ZERO, Arc::new(StateCache::default())); + self.update_l1_block_info_with_hash(header, None); + } + + fn update_l1_block_info_with_hash(&self, header: &H, tip_hash: Option) + where + H: BlockHeader, + { + self.block_info.update_header(header); + + let provider_res = match tip_hash { + Some(hash) => self.client().state_by_block_hash(hash).or_else(|_| { + self.client() + .state_by_block_number_or_tag(header.number().into()) + }), + None => self + .client() + .state_by_block_number_or_tag(header.number().into()), + }; + + let provider = match provider_res { Ok(provider) => provider, Err(err) => { tracing::warn!(target: "morph::txpool", %err, "Failed to get state provider for L1 block info update"); @@ -243,6 +314,38 @@ where } } + /// Returns the state provider for the current canonical tip together with its tip-scoped cache. + fn latest_state_provider_and_cache( + &self, + ) -> ProviderResult<(StateProviderBox, Arc)> { + if let Ok(info) = self.client().chain_info() + && !info.best_hash.is_zero() + && let Ok(provider) = self.client().state_by_block_hash(info.best_hash) + { + return Ok((provider, self.state_cache_for_tip(info.best_hash))); + } + + let provider = self + .client() + .state_by_block_number_or_tag(self.block_number().into()) + .or_else(|_| self.client().latest())?; + Ok((provider, Arc::new(StateCache::default()))) + } + + fn state_cache_for_tip(&self, tip_hash: B256) -> Arc { + { + let cached = self.cached_state.read(); + if cached.0 == tip_hash { + return Arc::clone(&cached.1); + } + } + let mut cached = self.cached_state.write(); + if cached.0 != tip_hash { + *cached = (tip_hash, Arc::new(StateCache::default())); + } + Arc::clone(&cached.1) + } + /// Validates a single transaction. /// /// See also [`TransactionValidator::validate_transaction`] @@ -257,7 +360,10 @@ where origin: TransactionOrigin, transaction: Tx, ) -> TransactionValidationOutcome { - self.validate_one_with_state(origin, transaction, &mut None) + let mut outcomes = self.validate_all(vec![(origin, transaction)]); + outcomes + .pop() + .expect("single input produces single outcome") } /// Validates a single transaction, reusing an optional state provider. @@ -272,6 +378,16 @@ where origin: TransactionOrigin, transaction: Tx, state: &mut Option>, + ) -> TransactionValidationOutcome { + self.validate_one_with_context(origin, transaction, state, None) + } + + fn validate_one_with_context( + &self, + origin: TransactionOrigin, + transaction: Tx, + state: &mut Option>, + mut token_validator: Option, &str>>, ) -> TransactionValidationOutcome { // Reject EIP-4844 blob transactions - not supported on L2 if transaction.is_eip4844() { @@ -375,13 +491,32 @@ where // the shared helper used by both admission and maintenance. // Pass &MorphTxEnvelope directly to avoid a second clone_into_consensus(). let sender = valid_tx.transaction().sender(); - if let Err(err) = self.validate_morph_tx_balance( - &consensus_tx, - sender, - balance, - l1_data_fee, - hardfork, - ) { + let validation_res = match token_validator.take() { + Some(Ok(validator)) => self.validate_morph_tx_balance_with_validator( + &consensus_tx, + sender, + balance, + l1_data_fee, + hardfork, + Ok(validator), + ), + Some(Err(err_msg)) => self.validate_morph_tx_balance_with_validator( + &consensus_tx, + sender, + balance, + l1_data_fee, + hardfork, + Err(err_msg), + ), + None => self.validate_morph_tx_balance( + &consensus_tx, + sender, + balance, + l1_data_fee, + hardfork, + ), + }; + if let Err(err) = validation_res { return TransactionValidationOutcome::Invalid( valid_tx.into_transaction(), err.into(), @@ -425,20 +560,45 @@ where sender: Address, eth_balance: U256, l1_data_fee: U256, - hardfork: morph_chainspec::hardfork::MorphHardfork, + hardfork: MorphHardfork, ) -> Result { - // Get state provider for token info lookup - let provider = self - .client() - .state_by_block_number_or_tag(self.block_number().into()) - .map_err(|err| MorphTxError::TokenInfoFetchFailed { - token_id: 0, // token_id not yet extracted - message: err.to_string(), - })?; - - let mut db = StateProviderDatabase::new((&provider).into_evm_state_provider()); + let (provider, cache) = match self.latest_state_provider_and_cache() { + Ok(pair) => pair, + Err(err) => { + let err_msg = err.to_string(); + return self.validate_morph_tx_balance_with_validator( + consensus_tx, + sender, + eth_balance, + l1_data_fee, + hardfork, + Err(&err_msg), + ); + } + }; + let evm_state_provider = (&provider).into_evm_state_provider(); + let env = self.block_info.evm_env(hardfork, self.inner.chain_id()); + let mut validator = + TokenFeeValidator::new(&cache, StateProviderDatabase::new(&evm_state_provider), env); + self.validate_morph_tx_balance_with_validator( + consensus_tx, + sender, + eth_balance, + l1_data_fee, + hardfork, + Ok(&mut validator), + ) + } - // Use shared validation logic with unified API (includes ETH balance check) + fn validate_morph_tx_balance_with_validator( + &self, + consensus_tx: &reth_primitives_traits::Recovered, + sender: Address, + eth_balance: U256, + l1_data_fee: U256, + hardfork: MorphHardfork, + token_validator: Result<&mut TokenFeeValidator<'_>, &str>, + ) -> Result { let input = crate::MorphTxValidationInput { consensus_tx, sender, @@ -447,7 +607,13 @@ where hardfork, }; - let result = crate::validate_morph_tx(&mut db, &input)?; + let result = validate_morph_tx_with(&input, |token_id, caller| match token_validator { + Ok(validator) => validator.resolve_token_fee_info(token_id, caller), + Err(message) => Err(MorphTxError::TokenInfoFetchFailed { + token_id, + message: message.to_string(), + }), + })?; let token_balance = result .token_info .as_ref() @@ -470,7 +636,9 @@ where Ok(result) } - /// Validates all given transactions, reusing a single state provider across the batch. + /// Validates all given transactions, reusing a single state provider and `MorphEvm` + /// across the batch while sharing [`StateCache`] reads across concurrent validations at the + /// same canonical tip. /// /// Returns all outcomes for the given transactions in the same order. /// @@ -480,10 +648,52 @@ where transactions: Vec<(TransactionOrigin, Tx)>, ) -> Vec> { let mut state = None; - transactions - .into_iter() - .map(|(origin, tx)| self.validate_one_with_state(origin, tx, &mut state)) - .collect() + if !transactions.iter().any(|(_, tx)| is_morph_tx(tx)) { + return transactions + .into_iter() + .map(|(origin, tx)| self.validate_one_with_context(origin, tx, &mut state, None)) + .collect(); + } + + match self.latest_state_provider_and_cache() { + Ok((provider, cache)) => { + let evm_state_provider = (&provider).into_evm_state_provider(); + let hardfork = self + .chain_spec() + .morph_hardfork_at(self.block_number(), self.block_timestamp()); + let env = self.block_info.evm_env(hardfork, self.inner.chain_id()); + let mut token_validator = TokenFeeValidator::new( + &cache, + StateProviderDatabase::new(&evm_state_provider), + env, + ); + transactions + .into_iter() + .map(|(origin, tx)| { + self.validate_one_with_context( + origin, + tx, + &mut state, + Some(Ok(&mut token_validator)), + ) + }) + .collect() + } + Err(err) => { + let err_msg = err.to_string(); + transactions + .into_iter() + .map(|(origin, tx)| { + self.validate_one_with_context( + origin, + tx, + &mut state, + Some(Err(err_msg.as_str())), + ) + }) + .collect() + } + } } } @@ -514,7 +724,8 @@ where fn on_new_head_block(&self, new_tip_block: &SealedBlock) { self.inner.on_new_head_block(new_tip_block); - self.update_l1_block_info(new_tip_block.header()); + *self.cached_state.write() = (new_tip_block.hash(), Arc::new(StateCache::default())); + self.update_l1_block_info_with_hash(new_tip_block.header(), Some(new_tip_block.hash())); } } @@ -962,4 +1173,97 @@ mod tests { } if required == U256::from(2_100_000u64) && balance == U256::from(300_000u64) )); } + + #[test] + fn validate_morph_tx_call_mode_uses_real_head_chain_id_and_timestamp() { + let client = new_mock_provider(); + let signer = address!("0000000000000000000000000000000000000001"); + let token = address!("5300000000000000000000000000000000000042"); + let token_key = token_id_key(1); + let base = compute_mapping_slot(U256::from(151), &token_key); + let mut slot_2 = [0u8; 32]; + slot_2[30] = 18; + slot_2[31] = 1; + + client.add_account(signer, ExtendedAccount::new(0, U256::ZERO)); + client.add_account( + L2_TOKEN_REGISTRY_ADDRESS, + ExtendedAccount::new(0, U256::ZERO).extend_storage([ + (storage_key(base), U256::from_be_bytes(token.into_word().0)), + // `0` -> call-mode (`balanceOf`) + (storage_key(base + U256::from(1)), U256::ZERO), + ( + storage_key(base + U256::from(2)), + U256::from_be_bytes(slot_2), + ), + (storage_key(base + U256::from(3)), U256::ONE), + ( + storage_key(compute_mapping_slot(U256::from(153), &token_key)), + U256::ONE, + ), + ]), + ); + // `balanceOf` returns `CHAINID + TIMESTAMP`: + // CHAINID (0x46), TIMESTAMP (0x42), ADD (0x01), PUSH0 (0x5f), MSTORE (0x52), + // PUSH1 0x20, PUSH0, RETURN (0xf3) + client.add_account( + token, + ExtendedAccount::new(0, U256::ZERO) + .with_bytecode(alloy_primitives::bytes!("4642015f5260205ff3")), + ); + + let morph_evm_config = MorphEvmConfig::new_with_default_factory(MORPH_MAINNET.clone()); + let eth_validator: EthTransactionValidator< + _, + crate::MorphPooledTransaction, + MorphEvmConfig, + > = EthTransactionValidatorBuilder::new(client, morph_evm_config) + .no_shanghai() + .no_cancun() + .disable_balance_check() + .build::(InMemoryBlobStore::default()); + let validator = MorphTransactionValidator::new(eth_validator); + const HEAD_TIMESTAMP: u64 = 1_767_765_600; + validator + .block_info + .update(L1BlockInfo::default(), HEAD_TIMESTAMP, 100, Some(1)); + + let tx = TxMorph { + chain_id: 2818, + nonce: 0, + gas_limit: 21_000, + max_fee_per_gas: 1, + max_priority_fee_per_gas: 1, + to: TxKind::Call(address!("0000000000000000000000000000000000000002")), + value: U256::ZERO, + access_list: Default::default(), + version: 0, + fee_token_id: 1, + fee_limit: U256::ZERO, + reference: None, + memo: None, + authorization_list: Vec::new(), + input: Default::default(), + }; + let envelope = MorphTxEnvelope::Morph(Signed::new_unchecked( + tx, + Signature::test_signature(), + B256::ZERO, + )); + let recovered = Recovered::new_unchecked(envelope, signer); + let res = validator + .validate_morph_tx_balance( + &recovered, + signer, + U256::ZERO, + U256::ZERO, + MorphHardfork::Emerald, + ) + .expect("call-mode MorphTx must succeed under real head env"); + + assert_eq!( + res.token_info.unwrap().balance, + U256::from(2818 + HEAD_TIMESTAMP) + ); + } } From 2e49909550450665b352be492cab092a1357c7eb Mon Sep 17 00:00:00 2001 From: panos-xyz Date: Thu, 26 Nov 2026 21:21:02 +0800 Subject: [PATCH 05/16] fix(txpool): reject zero-tip replacement of positive-tip transactions --- crates/txpool/src/transaction.rs | 177 ++++++++++++++++++++++++++++++- 1 file changed, 176 insertions(+), 1 deletion(-) diff --git a/crates/txpool/src/transaction.rs b/crates/txpool/src/transaction.rs index 08690a73..73f035f4 100644 --- a/crates/txpool/src/transaction.rs +++ b/crates/txpool/src/transaction.rs @@ -1,7 +1,8 @@ //! Pool transaction type for Morph L2. use alloy_consensus::{ - BlobTransactionValidationError, Typed2718, transaction::Recovered, transaction::TxHashRef, + BlobTransactionValidationError, Transaction as _, Typed2718, transaction::Recovered, + transaction::TxHashRef, }; use alloy_eips::{ eip2930::AccessList, eip7594::BlobTransactionSidecarVariant, eip7702::SignedAuthorization, @@ -13,6 +14,7 @@ use morph_primitives::{MorphTxEnvelope, MorphTxType}; use reth_primitives_traits::InMemorySize; use reth_transaction_pool::{ EthBlobTransactionSidecar, EthPoolTransaction, EthPooledTransaction, PoolTransaction, + PriceBumpConfig, }; use std::sync::{Arc, OnceLock}; @@ -101,6 +103,25 @@ impl PoolTransaction for MorphPooledTransaction { fn encoded_length(&self) -> usize { self.inner.encoded_length } + + fn is_replacement_underpriced( + &self, + replacement: &Self, + price_bumps: &PriceBumpConfig, + ) -> bool { + // Upstream `PriceBumpConfig::is_replacement_underpriced` skips the priority-fee bump + // whenever `replacement_max_priority_fee_per_gas == 0`, allowing a dynamic-fee tx + // (EIP-1559 / EIP-7702 / MorphTx) with `tip == 0` to replace a `tip > 0` tx by only + // inflating `max_fee_per_gas`. On Morph's fixed low base fee, that downgrades the + // effective tip to zero, so reject it explicitly while preserving Legacy replacements + // (`max_priority_fee_per_gas() == None`) and `0 -> 0` tip replacements. + if self.max_priority_fee_per_gas().is_some_and(|tip| tip > 0) + && replacement.max_priority_fee_per_gas() == Some(0) + { + return true; + } + price_bumps.is_replacement_underpriced(self, replacement) + } } impl Typed2718 for MorphPooledTransaction { @@ -386,4 +407,158 @@ mod tests { // encoded_length is set during construction assert!(tx.encoded_length() > 0); } + + fn create_eip1559_pooled_tx( + max_fee_per_gas: u128, + max_priority_fee_per_gas: u128, + ) -> MorphPooledTransaction { + use alloy_consensus::TxEip1559; + let tx = TxEip1559 { + chain_id: 1337, + nonce: 0, + gas_limit: 21_000, + max_fee_per_gas, + max_priority_fee_per_gas, + to: TxKind::Call(Address::repeat_byte(0x02)), + value: U256::ZERO, + access_list: Default::default(), + input: Bytes::new(), + }; + let sig = Signature::test_signature(); + let envelope = MorphTxEnvelope::Eip1559(Signed::new_unhashed(tx, sig)); + let recovered = Recovered::new_unchecked(envelope, Address::repeat_byte(0xaa)); + let len = recovered.encode_2718_len(); + MorphPooledTransaction::new(recovered, len) + } + + fn create_morph_pooled_tx_with_fees( + max_fee_per_gas: u128, + max_priority_fee_per_gas: u128, + ) -> MorphPooledTransaction { + use morph_primitives::TxMorph; + let tx = TxMorph { + chain_id: 1337, + nonce: 0, + gas_limit: 21_000, + max_fee_per_gas, + max_priority_fee_per_gas, + to: TxKind::Call(Address::repeat_byte(0x02)), + value: U256::ZERO, + access_list: Default::default(), + version: 0, + fee_token_id: 1, + fee_limit: U256::from(1000u64), + reference: None, + memo: None, + authorization_list: Vec::new(), + input: Bytes::new(), + }; + let sig = Signature::test_signature(); + let envelope = MorphTxEnvelope::Morph(Signed::new_unhashed(tx, sig)); + let recovered = Recovered::new_unchecked(envelope, Address::repeat_byte(0xaa)); + let len = recovered.encode_2718_len(); + MorphPooledTransaction::new(recovered, len) + } + + fn create_eip7702_pooled_tx( + max_fee_per_gas: u128, + max_priority_fee_per_gas: u128, + ) -> MorphPooledTransaction { + use alloy_consensus::TxEip7702; + let tx = TxEip7702 { + chain_id: 1337, + nonce: 0, + gas_limit: 21_000, + max_fee_per_gas, + max_priority_fee_per_gas, + to: Address::repeat_byte(0x02), + value: U256::ZERO, + access_list: Default::default(), + authorization_list: Vec::new(), + input: Bytes::new(), + }; + let sig = Signature::test_signature(); + let envelope = MorphTxEnvelope::Eip7702(Signed::new_unhashed(tx, sig)); + let recovered = Recovered::new_unchecked(envelope, Address::repeat_byte(0xaa)); + let len = recovered.encode_2718_len(); + MorphPooledTransaction::new(recovered, len) + } + + fn create_legacy_pooled_tx_with_gas_price(gas_price: u128) -> MorphPooledTransaction { + let tx = TxLegacy { + chain_id: Some(1337), + nonce: 0, + gas_price, + gas_limit: 21_000, + to: TxKind::Call(Address::repeat_byte(0x02)), + value: U256::ZERO, + input: Bytes::new(), + }; + let sig = Signature::test_signature(); + let envelope = MorphTxEnvelope::Legacy(Signed::new_unhashed(tx, sig)); + let recovered = Recovered::new_unchecked(envelope, Address::repeat_byte(0xaa)); + let len = recovered.encode_2718_len(); + MorphPooledTransaction::new(recovered, len) + } + + #[test] + fn test_replacement_rejects_zero_tip_downgrade_from_positive_tip() { + let bumps = PriceBumpConfig::default(); + + // EIP-1559 (tip > 0) -> EIP-1559 / MorphTx / EIP-7702 (tip == 0) with bumped maxFee + let existing_1559 = create_eip1559_pooled_tx(10_000_000_000, 5_000_000_000); + let zero_tip_1559 = create_eip1559_pooled_tx(20_000_000_000, 0); + let zero_tip_morph = create_morph_pooled_tx_with_fees(20_000_000_000, 0); + let zero_tip_7702 = create_eip7702_pooled_tx(20_000_000_000, 0); + + assert!(existing_1559.is_replacement_underpriced(&zero_tip_1559, &bumps)); + assert!(existing_1559.is_replacement_underpriced(&zero_tip_morph, &bumps)); + assert!(existing_1559.is_replacement_underpriced(&zero_tip_7702, &bumps)); + + // MorphTx (tip > 0) -> MorphTx / EIP-1559 (tip == 0) + let existing_morph = create_morph_pooled_tx_with_fees(10_000_000_000, 5_000_000_000); + assert!(existing_morph.is_replacement_underpriced(&zero_tip_morph, &bumps)); + assert!(existing_morph.is_replacement_underpriced(&zero_tip_1559, &bumps)); + + // EIP-7702 (tip > 0) -> EIP-7702 / EIP-1559 (tip == 0) + let existing_7702 = create_eip7702_pooled_tx(10_000_000_000, 5_000_000_000); + assert!(existing_7702.is_replacement_underpriced(&zero_tip_7702, &bumps)); + assert!(existing_7702.is_replacement_underpriced(&zero_tip_1559, &bumps)); + } + + #[test] + fn test_replacement_preserves_valid_bumps_zero_to_zero_and_legacy() { + let bumps = PriceBumpConfig::default(); + + // 0-tip -> 0-tip with >= 10% maxFee bump is still allowed + let zero_1559 = create_eip1559_pooled_tx(1_000_000, 0); + let zero_1559_bumped = create_eip1559_pooled_tx(1_100_000, 0); + let zero_1559_low = create_eip1559_pooled_tx(1_099_999, 0); + assert!(!zero_1559.is_replacement_underpriced(&zero_1559_bumped, &bumps)); + assert!(zero_1559.is_replacement_underpriced(&zero_1559_low, &bumps)); + + let zero_morph = create_morph_pooled_tx_with_fees(1_000_000, 0); + let zero_morph_bumped = create_morph_pooled_tx_with_fees(1_100_000, 0); + assert!(!zero_morph.is_replacement_underpriced(&zero_morph_bumped, &bumps)); + + // 0-tip -> positive-tip with >= 10% maxFee bump is allowed + let pos_1559_bumped = create_eip1559_pooled_tx(1_100_000, 100_000); + assert!(!zero_1559.is_replacement_underpriced(&pos_1559_bumped, &bumps)); + + // positive-tip -> positive-tip requires >= 10% bump on both maxFee and tip + let existing = create_eip1559_pooled_tx(10_000_000, 2_000_000); + let good_bump = create_eip1559_pooled_tx(11_000_000, 2_200_000); + let low_tip_bump = create_eip1559_pooled_tx(11_000_000, 2_199_999); + assert!(!existing.is_replacement_underpriced(&good_bump, &bumps)); + assert!(existing.is_replacement_underpriced(&low_tip_bump, &bumps)); + + // EIP-1559 (tip > 0) -> Legacy (gasPrice >= 1.1x maxFee) is allowed + let legacy_bumped = create_legacy_pooled_tx_with_gas_price(11_000_000); + assert!(!existing.is_replacement_underpriced(&legacy_bumped, &bumps)); + + // Legacy -> EIP-1559 with >= 1.1x maxFee preserves upstream reth behavior + let legacy = create_legacy_pooled_tx_with_gas_price(10_000_000); + let eip1559_from_legacy = create_eip1559_pooled_tx(11_000_000, 2_000_000); + assert!(!legacy.is_replacement_underpriced(&eip1559_from_legacy, &bumps)); + } } From d6514f5f9416556b1bdc3f7e18ec1493b971fe49 Mon Sep 17 00:00:00 2001 From: panos-xyz Date: Thu, 26 Nov 2026 22:58:33 +0800 Subject: [PATCH 06/16] fix(rpc): fix eth_estimateGas maxFeePerGas cap, 21k bypass, and EIP-1559 OOG revert --- crates/node/tests/it/rpc.rs | 249 +++++++++++++++++++++++++++++ crates/rpc/src/eth/call.rs | 254 +++++++++++++++++++++++++++++- crates/rpc/src/eth/transaction.rs | 71 ++++++++- 3 files changed, 566 insertions(+), 8 deletions(-) diff --git a/crates/node/tests/it/rpc.rs b/crates/node/tests/it/rpc.rs index 42f701c4..8be9a3e9 100644 --- a/crates/node/tests/it/rpc.rs +++ b/crates/node/tests/it/rpc.rs @@ -1310,3 +1310,252 @@ async fn native_get_proof_and_get_multi_proof_succeed_on_latest() -> eyre::Resul Ok(()) } + +/// `eth_estimateGas` caps caller gas allowance using `maxFeePerGas` (not `effective_gas_price`). +/// +/// With Morph's 0.001 Gwei `baseFee`, a request with `maxFeePerGas = 100 Gwei` and +/// `maxPriorityFeePerGas = 0` has `effective_gas_price = 0.001 Gwei` (100,000x smaller). +/// A sender holding 0.0001 ETH can only afford <= 1,000 gas at 100 Gwei (< 21,000), so +/// estimation must reject instead of returning 21,000. +#[tokio::test(flavor = "multi_thread")] +async fn estimate_gas_caps_eip1559_allowance_by_max_fee_per_gas() -> eyre::Result<()> { + reth_tracing::init_test_tracing(); + + let (mut nodes, wallet) = TestNodeBuilder::new().build().await?; + let mut node = nodes.pop().unwrap(); + advance_chain(1, &mut node, wallet_to_arc(wallet)).await?; + + let client = node + .rpc_client() + .ok_or_else(|| eyre::eyre!("HTTP RPC client not available"))?; + + let sender = Address::random(); + let recipient = Address::random(); + // 0.0001 ETH = 100_000_000_000_000 wei: + // - at 100 Gwei maxFeePerGas: affords <= 1,000 gas (< 21,000) -> must fail + // - at 1 Gwei maxFeePerGas: affords ~100,000 gas (>= 21,000) -> must succeed + let state_overrides = serde_json::json!({ + sender.to_string(): { "balance": "0x5af3107a4000" } + }); + + let high_max_fee_req = serde_json::json!({ + "from": sender, + "to": recipient, + "value": "0x0", + "maxFeePerGas": "0x174876e800", // 100 Gwei + "maxPriorityFeePerGas": "0x0", // 0 tip -> effective = baseFee (0.001 Gwei) + }); + let err = client + .request::( + "eth_estimateGas", + (high_max_fee_req, "latest", state_overrides.clone()), + ) + .await + .expect_err("allowance must use maxFeePerGas, not effective_gas_price") + .to_string(); + assert!( + err.contains("gas required exceeds allowance"), + "expected gas allowance error, got: {err}" + ); + + let affordable_req = serde_json::json!({ + "from": sender, + "to": recipient, + "value": "0x0", + "maxFeePerGas": "0x3b9aca00", // 1 Gwei + "maxPriorityFeePerGas": "0x0", + }); + let gas: U256 = client + .request( + "eth_estimateGas", + (affordable_req, "latest", state_overrides), + ) + .await?; + assert_eq!(gas, U256::from(21_000u64)); + + Ok(()) +} + +/// `eth_estimateGas` must not short-circuit basic transfers to 21,000 gas when either +/// an explicit `gas` limit or the caller's balance allowance is below 21,000. +#[tokio::test(flavor = "multi_thread")] +async fn estimate_gas_basic_transfer_respects_cap_below_21k() -> eyre::Result<()> { + reth_tracing::init_test_tracing(); + + let (mut nodes, wallet) = TestNodeBuilder::new().build().await?; + let mut node = nodes.pop().unwrap(); + let rich_sender = wallet.inner.address(); + advance_chain(1, &mut node, wallet_to_arc(wallet)).await?; + + let client = node + .rpc_client() + .ok_or_else(|| eyre::eyre!("HTTP RPC client not available"))?; + + let recipient = Address::random(); + + // 1. Explicit gas < 21_000 must fail instead of returning 21_000. + let explicit_low_gas = serde_json::json!({ + "from": rich_sender, + "to": recipient, + "value": "0x0", + "gas": "0x2710", // 10,000 < 21,000 + }); + let err = client + .request::("eth_estimateGas", (explicit_low_gas,)) + .await + .expect_err("explicit gas < 21,000 must not short-circuit to 21,000") + .to_string(); + assert!( + err.contains("gas required exceeds allowance (10000)"), + "expected allowance error for gas 10000, got: {err}" + ); + + // 2. Balance allowance in (0, 21_000) must also fail instead of returning 21,000. + let limited_sender = Address::random(); + let state_overrides = serde_json::json!({ + limited_sender.to_string(): { "balance": "0x5af3107a4000" } // 0.0001 ETH + }); + let low_allowance_req = serde_json::json!({ + "from": limited_sender, + "to": recipient, + "value": "0x0", + "gasPrice": "0x2540be400", // 10 Gwei -> allowance <= 10,000 < 21,000 + }); + let err = client + .request::( + "eth_estimateGas", + (low_allowance_req, "latest", state_overrides), + ) + .await + .expect_err("balance allowance < 21,000 must not short-circuit to 21,000") + .to_string(); + assert!( + err.contains("gas required exceeds allowance"), + "expected allowance error, got: {err}" + ); + + Ok(()) +} + +/// EIP-1559 `eth_estimateGas` requests whose execution reverts because balance capping +/// starves the call of gas must report an out-of-gas error rather than `execution reverted`, +/// while genuine unconditional reverts still report `execution reverted`. +#[tokio::test(flavor = "multi_thread")] +async fn estimate_gas_eip1559_inner_oog_revert_reports_out_of_gas() -> eyre::Result<()> { + reth_tracing::init_test_tracing(); + use super::helpers::init_code_for; + use morph_node::test_utils::make_deploy_tx; + + let (mut nodes, wallet) = TestNodeBuilder::new().build().await?; + let mut node = nodes.pop().unwrap(); + let chain_id = wallet.chain_id; + let rich_sender = wallet.inner.address(); + + // Runtime 1: reverts if remaining `GAS < 65,536`, otherwise `STOP`. + // 0x00: PUSH3 0x010000 (65536) + // 0x04: GAS + // 0x05: LT (remaining < 65536) + // 0x06: PUSH1 0x0a + // 0x08: JUMPI + // 0x09: STOP + // 0x0a: JUMPDEST + // 0x0b: PUSH0 PUSH0 REVERT + const GAS_GATED_REVERT_RUNTIME: &[u8] = &[ + 0x62, 0x01, 0x00, 0x00, 0x5a, 0x10, 0x60, 0x0a, 0x57, 0x00, 0x5b, 0x5f, 0x5f, 0xfd, + ]; + // Runtime 2: always reverts (`PUSH0 PUSH0 REVERT`). + const ALWAYS_REVERT_RUNTIME: &[u8] = &[0x5f, 0x5f, 0xfd]; + + let deploy_gated = make_deploy_tx( + chain_id, + wallet.inner.clone(), + 0, + init_code_for(GAS_GATED_REVERT_RUNTIME), + )?; + let deploy_always = make_deploy_tx( + chain_id, + wallet.inner.clone(), + 1, + init_code_for(ALWAYS_REVERT_RUNTIME), + )?; + node.rpc.inject_tx(deploy_gated).await?; + node.rpc.inject_tx(deploy_always).await?; + node.advance_block().await?; + + let gas_gated_contract = Address::create(&rich_sender, 0); + let always_revert_contract = Address::create(&rich_sender, 1); + + let client = node + .rpc_client() + .ok_or_else(|| eyre::eyre!("HTTP RPC client not available"))?; + + // Sender with 0.005 ETH (5e15 wei) at maxFeePerGas = 100 Gwei (1e11 wei) -> + // allowance is ~50,000 gas (>= 21,000 intrinsic, < 86,536 required to pass GAS check). + let limited_sender = Address::random(); + let state_overrides = serde_json::json!({ + limited_sender.to_string(): { "balance": "0x11c37937e08000" } // 0.005 ETH + }); + + // 1. EIP-1559 request (no legacy `gasPrice`, no explicit `gas`) starved by balance cap + // must retry at `max_gas_limit` and report out-of-gas, NOT `execution reverted`. + let starved_req = serde_json::json!({ + "from": limited_sender, + "to": gas_gated_contract, + "data": "0x", + "maxFeePerGas": "0x174876e800", // 100 Gwei + "maxPriorityFeePerGas": "0x0", + }); + let err = client + .request::( + "eth_estimateGas", + (starved_req, "latest", state_overrides.clone()), + ) + .await + .expect_err("balance-starved EIP-1559 call must fail") + .to_string(); + assert!( + err.contains("out of gas") || err.contains("gas required exceeds"), + "expected out-of-gas diagnostic instead of execution reverted, got: {err}" + ); + assert!( + !err.contains("execution reverted"), + "gas-starved EIP-1559 call must not be misreported as execution reverted: {err}" + ); + + // 2. Same contract with a well-funded sender succeeds. + let funded_req = serde_json::json!({ + "from": rich_sender, + "to": gas_gated_contract, + "data": "0x", + "maxFeePerGas": "0x174876e800", + "maxPriorityFeePerGas": "0x0", + }); + let gas: U256 = client.request("eth_estimateGas", (funded_req,)).await?; + assert!( + gas >= U256::from(86_536u64), + "funded call must estimate enough gas to clear the 65,536 threshold, got {gas}" + ); + + // 3. Genuine unconditional revert still reports `execution reverted` even when gas-constrained. + let always_revert_req = serde_json::json!({ + "from": limited_sender, + "to": always_revert_contract, + "data": "0x", + "maxFeePerGas": "0x174876e800", + "maxPriorityFeePerGas": "0x0", + }); + let err = client + .request::( + "eth_estimateGas", + (always_revert_req, "latest", state_overrides), + ) + .await + .expect_err("unconditional revert must fail") + .to_string(); + assert!( + err.contains("execution reverted"), + "genuine contract revert must still report execution reverted, got: {err}" + ); + + Ok(()) +} diff --git a/crates/rpc/src/eth/call.rs b/crates/rpc/src/eth/call.rs index 751d7868..0fd9307a 100644 --- a/crates/rpc/src/eth/call.rs +++ b/crates/rpc/src/eth/call.rs @@ -5,21 +5,55 @@ //! (MorphTx `fee_token_id > 0`). `eth_call` and `eth_createAccessList` //! are detected by the block gas limit check being disabled and keep the //! plain ETH allowance, without the L1-fee extension. +//! +//! [`EstimateCall::estimate_gas_with`] is also overridden to fix three +//! upstream estimation defects: +//! 1. Cap balance allowance using `tx_env.gas_price` (`maxFeePerGas` for +//! dynamic-fee requests) instead of `effective_gas_price`. +//! 2. Guard the `is_basic_transfer` 21,000-gas shortcut with +//! `highest_gas_limit >= MIN_TRANSACTION_GAS` so sub-21k allowances or +//! explicit `gas < 21_000` cannot bypass the cap. +//! 3. Retry at `max_gas_limit` on revert / gas-too-high whenever +//! `highest_gas_limit < max_gas_limit`, covering EIP-1559 and MorphTx +//! requests whose legacy `gasPrice` field is absent. use crate::MorphEthApiError; use crate::eth::{MorphEthApi, MorphNodeCore}; -use alloy_primitives::{Address, U256, U512}; -use evm2::{EvmFeatures, registry::HandlerError}; +use alloy_network::TransactionBuilder; +use alloy_primitives::{Address, TxKind, U256, U512}; +use alloy_rpc_types_eth::state::EvmOverrides; +use evm2::{ + EvmFeatures, TxResult, + evm::{CacheDB, Db}, + interpreter::InstrStop, + registry::HandlerError, +}; use morph_chainspec::{MorphChainSpec, MorphHardforks}; use morph_revm::{L1BlockInfo, MorphEvmEnv, MorphTxExt, TokenFeeInfo}; +use reth_chainspec::MIN_TRANSACTION_GAS; use reth_errors::ProviderError; -use reth_evm::{Database, EvmEnv, EvmEnvFor, TxEnvFor}; +use reth_evm::{ + ConfigureEvm, Database, Evm, EvmEnv, EvmEnvFor, EvmTypesFor, TransactionEnvMut, TxEnvFor, + database::StateProviderDatabase, +}; use reth_provider::ChainSpecProvider; +use reth_rpc_convert::{RpcConvert, RpcTxReq}; use reth_rpc_eth_api::{ - EthApiTypes, RpcNodeCore, - helpers::{Call, EthCall, estimate::EstimateCall}, + AsEthApiError, EthApiTypes, FromEthApiError, FromEvmError, IntoEthApiError, RpcNodeCore, + helpers::{ + Call, EthCall, + estimate::{EstimateCall, update_estimated_gas_range}, + }, }; -use reth_rpc_eth_types::EthApiError; +use reth_rpc_eth_types::{ + EthApiError, RpcInvalidTransactionError, + cache::db::{apply_block_overrides, apply_state_overrides}, + error::api::{FromEvmHalt, FromRevert}, +}; +use reth_rpc_server_types::constants::gas_oracle::{CALL_STIPEND_GAS, ESTIMATE_GAS_ERROR_RATIO}; +use reth_storage_api::EvmStateProvider; +use reth_tasks::cancel::is_cancelled; +use tracing::trace; impl EthCall for MorphEthApi where @@ -39,6 +73,214 @@ where reth_rpc_convert::RpcConvert, MorphEthApiError: reth_rpc_eth_types::error::FromEvmError, { + fn estimate_gas_with( + &self, + mut evm_env: EvmEnvFor, + mut request: RpcTxReq<::Network>, + state: S, + overrides: EvmOverrides, + ) -> Result + where + S: EvmStateProvider, + { + evm_env.version_mut().features.remove(EvmFeatures::EIP3607); + evm_env + .version_mut() + .features + .remove(EvmFeatures::BASE_FEE_CHECK); + evm_env.version_mut().features.remove( + EvmFeatures::FEE_CHARGE | EvmFeatures::BALANCE_CHECK | EvmFeatures::BALANCE_TOP_UP, + ); + + request.as_mut().take_nonce(); + + let tx_request_gas_limit = request.as_ref().gas_limit(); + + let mut db = CacheDB::new(Db::new(StateProviderDatabase::new(state))); + + if let Some(block_overrides) = overrides.block { + apply_block_overrides(*block_overrides, &mut db, &mut evm_env); + } + + if let Some(state_override) = overrides.state { + apply_state_overrides(state_override, &mut db).map_err(Self::Error::from_eth_err)?; + } + + let block_gas_limit = evm_env.block_env().gas_limit.to::(); + let mut max_gas_limit = evm_env.version().tx_gas_caps().0.min(block_gas_limit); + + let gas_cap = self.call_gas_limit(); + if gas_cap != 0 { + max_gas_limit = max_gas_limit.min(gas_cap); + } + + let mut highest_gas_limit = tx_request_gas_limit + .unwrap_or(max_gas_limit) + .min(max_gas_limit); + + let is_basic_transfer = if request + .as_ref() + .input() + .is_none_or(|input| input.is_empty()) + && let Some(TxKind::Call(to)) = request.as_ref().kind() + { + match db.get_account(&to) { + Ok(Some(account)) => account.is_empty_code_hash(), + Ok(None) => true, + Err(_) => false, + } + } else { + false + }; + + let mut tx_env = self.create_txn_env(&evm_env, request, &mut db)?; + + // Cap by caller balance whenever the worst-case fee cap (`gas_price` for legacy, + // `maxFeePerGas` for EIP-1559/EIP-7702/MorphTx) is non-zero. + if tx_env.gas_price > 0 { + let allowance = self.caller_gas_allowance(&mut db, &evm_env, &tx_env)?; + highest_gas_limit = highest_gas_limit.min(allowance); + } + + let gas_constrained = highest_gas_limit < max_gas_limit; + + trace!( + target: "rpc::eth::estimate", + ?tx_env, + gas_limit = highest_gas_limit, + is_basic_transfer, + "Starting gas estimation" + ); + + let mut evm = self.evm_config().evm_with_env(&mut db, evm_env); + let mut execute = move |gas_limit| { + tx_env.inner_mut().set_gas_limit(gas_limit); + evm.transact_result(&tx_env) + .map_err(>::from_evm_err) + }; + + // Only short-circuit basic transfers when the capped gas budget actually + // covers MIN_TRANSACTION_GAS (21,000); otherwise fall through so the cap + // reports `GasRequiredExceedsAllowance`. + if is_basic_transfer + && highest_gas_limit >= MIN_TRANSACTION_GAS + && let Ok(res) = execute(MIN_TRANSACTION_GAS) + && res.status + { + return Ok(U256::from(res.tx_gas_used())); + } + + let mut res = match execute(highest_gas_limit) { + Err(err) if err.is_gas_too_high() && gas_constrained => { + let retry = execute(max_gas_limit)?; + return map_out_of_gas_result::<_, EvmTypesFor>( + retry, + highest_gas_limit, + ); + } + Err(err) if err.is_gas_too_low() => { + return Err(RpcInvalidTransactionError::GasRequiredExceedsAllowance { + gas_limit: highest_gas_limit, + } + .into_eth_err()); + } + ethres => ethres?, + }; + + let gas_refund = if res.status { + res.final_refunded() + } else if res.stop == InstrStop::Revert { + // Whenever `highest_gas_limit` was constrained below `max_gas_limit` + // (whether by explicit `gas`, Legacy `gasPrice`, or EIP-1559/MorphTx + // `maxFeePerGas` balance capping), retry with `max_gas_limit` to + // distinguish inner-call out-of-gas reverts from genuine contract reverts. + return if gas_constrained { + let retry = execute(max_gas_limit)?; + map_out_of_gas_result::<_, EvmTypesFor>(retry, highest_gas_limit) + } else { + Err(Self::Error::from_revert(res.output)) + }; + } else { + return Err(Self::Error::from_evm_halt(res.stop, highest_gas_limit)); + }; + + let mut gas_used = res.tx_gas_used(); + let mut lowest_gas_limit = gas_used.saturating_sub(1); + + let optimistic_gas_limit = (gas_used + gas_refund + CALL_STIPEND_GAS) * 64 / 63; + if optimistic_gas_limit < highest_gas_limit { + res = execute(optimistic_gas_limit)?; + gas_used = res.tx_gas_used(); + update_estimated_gas_range::>( + res, + optimistic_gas_limit, + &mut highest_gas_limit, + &mut lowest_gas_limit, + )?; + } + + let mut mid_gas_limit = std::cmp::min( + gas_used * 3, + ((highest_gas_limit as u128 + lowest_gas_limit as u128) / 2) as u64, + ); + + trace!( + target: "rpc::eth::estimate", + ?highest_gas_limit, + ?lowest_gas_limit, + ?mid_gas_limit, + "Starting binary search for gas" + ); + + while lowest_gas_limit + 1 < highest_gas_limit { + let ratio = (highest_gas_limit - lowest_gas_limit) as f64 / (highest_gas_limit as f64); + if ratio < ESTIMATE_GAS_ERROR_RATIO { + break; + } + + if is_cancelled() { + return Err(EthApiError::InternalEthError.into()); + } + + match execute(mid_gas_limit) { + Err(err) if err.is_gas_too_high() => { + highest_gas_limit = mid_gas_limit; + } + Err(err) if err.is_gas_too_low() => { + lowest_gas_limit = mid_gas_limit; + } + ethres => { + update_estimated_gas_range::>( + ethres?, + mid_gas_limit, + &mut highest_gas_limit, + &mut lowest_gas_limit, + )?; + } + } + + mid_gas_limit = ((highest_gas_limit as u128 + lowest_gas_limit as u128) / 2) as u64; + } + + Ok(U256::from(highest_gas_limit)) + } +} + +fn map_out_of_gas_result( + result: TxResult, + requested_gas_limit: u64, +) -> Result +where + Error: FromEvmHalt + FromRevert + FromEthApiError, + EvmTypes: evm2::EvmTypes, +{ + if result.status { + Err(RpcInvalidTransactionError::BasicOutOfGas(requested_gas_limit).into_eth_err()) + } else if result.stop == InstrStop::Revert { + Err(Error::from_revert(result.output)) + } else { + Err(Error::from_evm_halt(result.stop, requested_gas_limit)) + } } impl Call for MorphEthApi diff --git a/crates/rpc/src/eth/transaction.rs b/crates/rpc/src/eth/transaction.rs index b8624d4a..7b4cb277 100644 --- a/crates/rpc/src/eth/transaction.rs +++ b/crates/rpc/src/eth/transaction.rs @@ -138,11 +138,31 @@ impl TryIntoTxEnv, MorphEvmEnv> for MorphTransactionReques } let caller = inner.from.unwrap_or_default(); + // Keep `max_fee_per_gas` in `MorphTxEnv::gas_price` for dynamic-fee requests so + // `caller_gas_allowance`, `encode_for_l1_fee`, and balance checks enforce the + // worst-case fee cap, while `MorphTxEnv::effective_gas_price_at(base_fee)` still + // derives the effective gas price for the GASPRICE opcode and fee settlement. + let (gas_price, gas_priority_fee) = if matches!(tx_type, TxType::Legacy | TxType::Eip2930) { + ( + fees.gas_price.saturating_to(), + fees.max_priority_fee_per_gas.map(|fee| fee.saturating_to()), + ) + } else { + ( + inner + .max_fee_per_gas + .unwrap_or_else(|| fees.gas_price.saturating_to()), + inner + .max_priority_fee_per_gas + .or_else(|| fees.max_priority_fee_per_gas.map(|fee| fee.saturating_to())), + ) + }; + let mut tx_env = MorphTxEnv { tx_type: tx_type.into(), gas_limit: inner.gas.unwrap_or_default(), - gas_price: fees.gas_price.saturating_to(), - gas_priority_fee: fees.max_priority_fee_per_gas.map(|fee| fee.saturating_to()), + gas_price, + gas_priority_fee, kind, value: inner.value.unwrap_or_default(), data: inner.input.into_input().unwrap_or_default(), @@ -666,6 +686,53 @@ mod tests { assert_eq!(signed.tx().max_priority_fee_per_gas, 1_000_000_000); } + #[test] + fn eip1559_and_morph_tx_env_preserve_max_fee_per_gas() { + let block_env = MorphBlockEnv { + number: U256::from(1), + timestamp: U256::from(1234567890), + gas_limit: U256::from(30_000_000u64), + basefee: U256::from(1_000_000u64), // 0.001 Gwei + ..Default::default() + }; + let evm_env = morph_evm_env(MorphHardfork::default(), 2818, 30_000_000, block_env); + + for (priority_fee, fee_token_id) in [ + (Some(0u128), None), + (None, None), + (Some(5_000_000u128), None), + (Some(0u128), Some(U64::from(1))), + ] { + let req = MorphTransactionRequest { + inner: TransactionRequest { + gas_price: None, + max_fee_per_gas: Some(100_000_000_000), // 100 Gwei >> baseFee + max_priority_fee_per_gas: priority_fee, + ..create_basic_transaction_request() + }, + fee_token_id, + ..Default::default() + }; + + let recovered = req.try_into_tx_env(&evm_env).unwrap(); + let tx_env = recovered.inner(); + assert_eq!( + tx_env.gas_price, 100_000_000_000, + "MorphTxEnv::gas_price must preserve max_fee_per_gas" + ); + assert_eq!( + tx_env.gas_priority_fee, + Some(priority_fee.unwrap_or(0)), + "dynamic-fee priority fee must be preserved (or default to 0)" + ); + assert_eq!( + tx_env.effective_gas_price_at(1_000_000), + 1_000_000 + priority_fee.unwrap_or(0), + "effective_gas_price_at must still compute min(max_fee, base_fee + tip)" + ); + } + } + #[test] fn test_morph_tx_env_defaults_missing_chain_id_from_evm_env() { let mut inner = create_morph_transaction_request(); From ed0cfcf0d1b1f90ea4d66ed1172816971c174b4e Mon Sep 17 00:00:00 2001 From: panos-xyz Date: Thu, 26 Nov 2026 23:27:30 +0800 Subject: [PATCH 07/16] fix(evm,txpool,rpc,node): harden pending block env, txpool fork gating, and EIP-7966 sync receipts --- Cargo.lock | 2 + crates/evm/src/context.rs | 49 +++++- crates/node/src/components/pool.rs | 19 ++- crates/node/tests/it/rpc.rs | 77 +++++++++ crates/rpc/Cargo.toml | 2 + crates/rpc/src/error.rs | 25 +++ crates/rpc/src/eth/mod.rs | 72 ++++++++ crates/txpool/src/error.rs | 50 ++++-- crates/txpool/src/morph_tx_validation.rs | 56 ++++--- crates/txpool/src/validator.rs | 199 ++++++++++++++++++++++- 10 files changed, 513 insertions(+), 38 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 28c62dfb..028a3457 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5655,6 +5655,7 @@ dependencies = [ "derive_more", "evm2", "eyre", + "futures", "jsonrpsee", "metrics", "morph-chainspec", @@ -5663,6 +5664,7 @@ dependencies = [ "morph-proofs", "morph-reference-index", "morph-revm", + "reth-chain-state", "reth-chainspec", "reth-errors", "reth-evm", diff --git a/crates/evm/src/context.rs b/crates/evm/src/context.rs index de01f683..2476ce6f 100644 --- a/crates/evm/src/context.rs +++ b/crates/evm/src/context.rs @@ -1,5 +1,16 @@ +use alloy_consensus::BlockHeader; use reth_evm::NextBlockEnvAttributes; +/// Default timestamp increment (in seconds) when building a synthetic pending +/// block environment on Morph L2. +/// +/// Upstream reth defaults to L1's 12-second slot (`parent.timestamp + 12`), +/// which would prematurely activate timestamp-gated hardforks up to 12 seconds +/// early on Morph's 2-second block cadence. Using `+2s` matches Morph's block +/// time while avoiding premature fork activation. +#[cfg(feature = "rpc")] +const MORPH_PENDING_BLOCK_TIMESTAMP_INCREMENT: u64 = 2; + /// Context required for next block environment. #[derive(Debug, Clone, derive_more::Deref)] pub struct MorphNextBlockEnvAttributes { @@ -19,9 +30,45 @@ impl reth_rpc_eth_api::helpers::pending_block::BuildPendingEnv, block_overrides: Option<&alloy_rpc_types_eth::BlockOverrides>, ) -> Self { + let mut inner = NextBlockEnvAttributes::build_pending_env(parent, block_overrides); + if block_overrides + .and_then(|overrides| overrides.time) + .is_none() + { + inner.timestamp = parent + .timestamp() + .saturating_add(MORPH_PENDING_BLOCK_TIMESTAMP_INCREMENT); + } Self { - inner: NextBlockEnvAttributes::build_pending_env(parent, block_overrides), + inner, base_fee_per_gas: None, } } } + +#[cfg(all(test, feature = "rpc"))] +mod tests { + use super::*; + use alloy_rpc_types_eth::BlockOverrides; + use morph_primitives::MorphHeader; + use reth_primitives_traits::SealedHeader; + use reth_rpc_eth_api::helpers::pending_block::BuildPendingEnv; + + #[test] + fn build_pending_env_uses_morph_timestamp_increment_unless_overridden() { + let mut header = MorphHeader::default(); + header.inner.timestamp = 1_000; + let parent = SealedHeader::seal_slow(header); + + let default_env = MorphNextBlockEnvAttributes::build_pending_env(&parent, None); + assert_eq!(default_env.inner.timestamp, 1_002); + + let overrides = BlockOverrides { + time: Some(5_000), + ..Default::default() + }; + let overridden_env = + MorphNextBlockEnvAttributes::build_pending_env(&parent, Some(&overrides)); + assert_eq!(overridden_env.inner.timestamp, 5_000); + } +} diff --git a/crates/node/src/components/pool.rs b/crates/node/src/components/pool.rs index d3ec9799..185cd0de 100644 --- a/crates/node/src/components/pool.rs +++ b/crates/node/src/components/pool.rs @@ -1,12 +1,14 @@ //! Morph transaction pool builder. use crate::MorphNode; +use alloy_consensus::BlockHeader; use morph_evm::MorphEvmConfig; use morph_primitives; use morph_txpool::MorphTransactionValidator; use reth_node_api::FullNodeTypes; use reth_node_builder::components::{TxPoolBuilder, spawn_maintenance_tasks}; use reth_node_builder::{BuilderContext, components::PoolBuilder}; +use reth_provider::{BlockNumReader, HeaderProvider}; use reth_tracing::tracing::{debug, info}; use reth_transaction_pool::{TransactionValidationTaskExecutor, blobstore::InMemoryBlobStore}; @@ -36,7 +38,20 @@ where ctx: &BuilderContext, _evm_config: Evm, ) -> eyre::Result { - let pool_config = ctx.pool_config(); + let mut pool_config = ctx.pool_config(); + + // Initialize both the pool's and validator's block gas limit from the current + // canonical tip (falling back to genesis on a fresh DB) so transactions with gas + // above Ethereum's default 30M are not rejected during the startup window before + // the first `set_block_info` update. + let tip_gas_limit = ctx + .provider() + .best_block_number() + .ok() + .and_then(|num| ctx.provider().header_by_number(num).ok().flatten()) + .map(|header| header.gas_limit()) + .unwrap_or_else(|| ctx.chain_spec().inner.genesis().gas_limit); + pool_config.gas_limit = tip_gas_limit; // Use in-memory blob store (Morph doesn't support EIP-4844 blobs) let blob_store = InMemoryBlobStore::default(); @@ -54,7 +69,7 @@ where .with_local_transactions_config(pool_config.local_transactions_config.clone()) .set_tx_fee_cap(ctx.config().rpc.rpc_tx_fee_cap) .with_max_tx_gas_limit(ctx.config().txpool.max_tx_gas_limit) - .set_block_gas_limit(ctx.chain_spec().inner.genesis().gas_limit) + .set_block_gas_limit(tip_gas_limit) .with_minimum_priority_fee(ctx.config().txpool.minimum_priority_fee) .with_additional_tasks(ctx.config().txpool.additional_validation_tasks) // Register MorphTx (0x7F) type for ERC20 gas payment diff --git a/crates/node/tests/it/rpc.rs b/crates/node/tests/it/rpc.rs index 8be9a3e9..3be3155e 100644 --- a/crates/node/tests/it/rpc.rs +++ b/crates/node/tests/it/rpc.rs @@ -1559,3 +1559,80 @@ async fn estimate_gas_eip1559_inner_oog_revert_reports_out_of_gas() -> eyre::Res Ok(()) } + +/// `eth_sendRawTransactionSync` (EIP-7966) returns error code `4` with `data: "0x"` +/// on timeout, and returns the transaction receipt once a block includes the transaction. +#[tokio::test(flavor = "multi_thread")] +async fn send_raw_transaction_sync_timeout_includes_tx_hash_data_and_returns_receipt() +-> eyre::Result<()> { + use alloy_primitives::TxHash; + use jsonrpsee::core::ClientError; + use morph_node::test_utils::make_transfer_tx; + use reth_transaction_pool::TransactionPool; + + reth_tracing::init_test_tracing(); + + let (mut nodes, wallet) = TestNodeBuilder::new().build().await?; + let mut node = nodes.pop().unwrap(); + + let client = node + .rpc_client() + .ok_or_else(|| eyre::eyre!("HTTP RPC client not available"))?; + + // 1. Submit nonce=0 with a short timeout and no block produced -> EIP-7966 timeout + // with error code 4 and `error.data == "0x"`. + let raw_tx0 = make_transfer_tx(wallet.chain_id, wallet.inner.clone(), 0).await; + let timeout_res: Result = client + .request("eth_sendRawTransactionSync", (raw_tx0, 100u64)) + .await; + let err = timeout_res.expect_err("sync submit without a block must time out"); + let ClientError::Call(err_obj) = err else { + panic!("expected JSON-RPC Call error, got: {err:?}"); + }; + assert_eq!( + err_obj.code(), + 4, + "EIP-7966 timeout must return JSON-RPC error code 4, got: {err_obj:?}" + ); + let data = err_obj + .data() + .expect("EIP-7966 timeout must include tx hash in error.data"); + let timed_out_hash: TxHash = + serde_json::from_str(data.get()).expect("error.data must be a 32-byte hex tx hash"); + + // Advance block to confirm nonce=0 and verify the hash reported in timeout error.data matches. + let payload0 = node.advance_block().await?; + assert_eq!(payload0.block().body().transactions.len(), 1); + let receipt0: Value = client + .request("eth_getTransactionReceipt", (timed_out_hash,)) + .await?; + assert_eq!( + receipt0["transactionHash"].as_str(), + Some(timed_out_hash.to_string().as_str()) + ); + + // 2. Submit nonce=1 via `eth_sendRawTransactionSync` while advancing a block -> returns receipt. + let raw_tx1 = make_transfer_tx(wallet.chain_id, wallet.inner.clone(), 1).await; + let sync_client = client.clone(); + let sync_task = tokio::spawn(async move { + sync_client + .request::("eth_sendRawTransactionSync", (raw_tx1, 10_000u64)) + .await + }); + + // Wait briefly until tx1 enters the pool, then seal the block. + let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(5); + while node.inner.pool.pool_size().total == 0 { + assert!( + tokio::time::Instant::now() < deadline, + "tx1 did not enter pool in time" + ); + tokio::time::sleep(std::time::Duration::from_millis(20)).await; + } + node.advance_block().await?; + + let receipt1 = sync_task.await??; + assert_eq!(receipt1["status"].as_str(), Some("0x1")); + + Ok(()) +} diff --git a/crates/rpc/Cargo.toml b/crates/rpc/Cargo.toml index fc3703e5..4985b7f2 100644 --- a/crates/rpc/Cargo.toml +++ b/crates/rpc/Cargo.toml @@ -19,6 +19,7 @@ morph-evm = { workspace = true, features = ["rpc"] } morph-proofs.workspace = true # Reth +reth-chain-state.workspace = true reth-chainspec.workspace = true reth-node-api.workspace = true reth-node-builder.workspace = true @@ -53,6 +54,7 @@ jsonrpsee.workspace = true async-trait.workspace = true # Serialization +futures.workspace = true serde.workspace = true derive_more.workspace = true tokio.workspace = true diff --git a/crates/rpc/src/error.rs b/crates/rpc/src/error.rs index f2be3be1..08fcfe97 100644 --- a/crates/rpc/src/error.rs +++ b/crates/rpc/src/error.rs @@ -1,6 +1,7 @@ //! Error types for Morph RPC use alloy_primitives::B256; +use alloy_rpc_types_eth::error::EthRpcErrorCode; use evm2::interpreter::InstrStop; use reth_errors::ProviderError; use reth_evm::BlockExecutionError; @@ -96,6 +97,13 @@ impl MorphEthApiError { impl From for jsonrpsee::types::ErrorObject<'static> { fn from(err: MorphEthApiError) -> Self { match err { + MorphEthApiError::Eth( + ref e @ EthApiError::TransactionConfirmationTimeout { hash, .. }, + ) => jsonrpsee::types::ErrorObject::owned( + EthRpcErrorCode::TransactionConfirmationTimeout.code(), + e.to_string(), + Some(hash), + ), MorphEthApiError::Eth(e) => e.into(), MorphEthApiError::BlockNotFound => { jsonrpsee::types::ErrorObject::owned(-32001, "Block not found", None::<()>) @@ -252,6 +260,23 @@ mod tests { ); } + #[test] + fn confirmation_timeout_error_includes_code_4_and_tx_hash_data() { + let hash = B256::repeat_byte(0xab); + let err = MorphEthApiError::Eth(EthApiError::TransactionConfirmationTimeout { + hash, + duration: std::time::Duration::from_secs(2), + }); + let obj: jsonrpsee::types::ErrorObject<'static> = err.into(); + assert_eq!(obj.code(), 4); + assert!(obj.message().contains(&hash.to_string())); + let data = obj + .data() + .expect("EIP-7966 timeout error must carry tx hash in error.data"); + let parsed: B256 = serde_json::from_str(data.get()).expect("error.data must be a hex hash"); + assert_eq!(parsed, hash); + } + #[test] fn error_to_json_rpc_error_codes() { let check = |err: MorphEthApiError, expected_code: i32| { diff --git a/crates/rpc/src/eth/mod.rs b/crates/rpc/src/eth/mod.rs index 51642da0..799bcb3f 100644 --- a/crates/rpc/src/eth/mod.rs +++ b/crates/rpc/src/eth/mod.rs @@ -350,6 +350,78 @@ where .await .map_err(Into::into) } + + fn send_raw_transaction_sync( + &self, + tx: alloy_primitives::Bytes, + timeout_ms: Option, + ) -> impl std::future::Future< + Output = Result, Self::Error>, + > + Send + where + Self: reth_rpc_eth_api::helpers::LoadReceipt, + { + let this = self.clone(); + let configured_timeout = self.send_raw_transaction_sync_timeout(); + let timeout_duration = timeout_ms + .filter(|timeout_ms| *timeout_ms > 0) + .map(Duration::from_millis) + .map(|timeout| timeout.min(configured_timeout)) + .unwrap_or(configured_timeout); + async move { + use futures::StreamExt; + use reth_chain_state::CanonStateSubscriptions; + use reth_rpc_eth_types::block::convert_transaction_receipt; + + let mut stream = this.provider().canonical_state_stream(); + let hash = EthTransactions::send_raw_transaction(&this, tx).await?; + + // DB receipt fallback right after submission (covers fast inclusion or + // already-committed notifications before the stream is polled). + if let Some(receipt) = this.transaction_receipt(hash).await? { + return Ok(receipt); + } + + let receipt_res = tokio::time::timeout(timeout_duration, async { + while let Some(notification) = stream.next().await { + let chain = notification.committed(); + if let Some((block, tx, receipt, all_receipts)) = + chain.find_transaction_and_receipt_by_hash(hash) + && let Some(receipt) = convert_transaction_receipt( + block, + all_receipts, + tx, + receipt, + this.converter(), + ) + .transpose()? + { + return Ok(Some(receipt)); + } + } + Ok::<_, Self::Error>(None) + }) + .await; + + match receipt_res { + Ok(Ok(Some(receipt))) => return Ok(receipt), + Ok(Err(err)) => return Err(err), + Ok(Ok(None)) | Err(_) => {} + } + + // Final DB receipt fallback before returning the EIP-7966 timeout error. + if let Some(receipt) = this.transaction_receipt(hash).await? { + return Ok(receipt); + } + + Err(reth_rpc_eth_api::FromEthApiError::from_eth_err( + EthApiError::TransactionConfirmationTimeout { + hash, + duration: timeout_duration, + }, + )) + } + } } impl EthSubscriptions for MorphEthApi diff --git a/crates/txpool/src/error.rs b/crates/txpool/src/error.rs index 24418c99..b4765608 100644 --- a/crates/txpool/src/error.rs +++ b/crates/txpool/src/error.rs @@ -73,6 +73,16 @@ pub enum MorphTxError { /// Reason for the validation failure. reason: String, }, + + /// Transaction type or version requires a hardfork that is not yet active on this node. + /// + /// Separated from [`Self::InvalidFormat`] / `TxTypeNotSupported` so peers that are one + /// block ahead across a hardfork boundary are not penalized or banned for relaying valid + /// post-fork transactions. + ForkNotActive { + /// Human-readable description of the inactive hardfork gate. + reason: String, + }, } impl fmt::Display for MorphTxError { @@ -120,6 +130,9 @@ impl fmt::Display for MorphTxError { Self::InvalidFormat { reason } => { write!(f, "invalid MorphTx format: {reason}") } + Self::ForkNotActive { reason } => { + write!(f, "{reason}") + } } } } @@ -129,12 +142,15 @@ impl std::error::Error for MorphTxError {} impl PoolTransactionError for MorphTxError { fn is_bad_transaction(&self) -> bool { // MorphTx validation errors are not necessarily "bad" transactions that warrant - // peer penalization. They are often just insufficient balance or inactive tokens. + // peer penalization. They are often just insufficient balance, inactive tokens, + // or a peer being slightly ahead across a hardfork activation boundary. match self { // Missing/invalid MorphTx fee fields indicate malformed transaction input. Self::InvalidTokenId => true, // Format violations (bad version, memo too long, etc.) are malformed input. Self::InvalidFormat { .. } => true, + // Fork not yet active on our local head - peer may simply be 1 block ahead + Self::ForkNotActive { .. } => false, // Token not found or not active - could be due to temporary state, not penalizable Self::TokenNotFound { .. } | Self::TokenNotActive { .. } => false, // Invalid price ratio or scale - configuration issue, not penalizable @@ -158,12 +174,8 @@ impl From for InvalidPoolTransactionError { cost: value, balance, }, - MorphTxError::InsufficientTokenBalance { - balance, required, .. - } => Self::Overdraft { - cost: required, - balance, - }, + // Keep `InsufficientTokenBalance` as `Other` rather than `Overdraft` so RPC + // callers receive the token-denominated message instead of ETH wei wording. _ => Self::Other(Box::new(err)), } } @@ -220,6 +232,9 @@ mod tests { #[test] fn test_error_conversion_insufficient_token() { + use alloy_primitives::TxHash; + use reth_transaction_pool::error::PoolError; + let err = MorphTxError::InsufficientTokenBalance { token_id: 1, token_address: address!("1234567890123456789012345678901234567890"), @@ -227,14 +242,19 @@ mod tests { required: U256::from(60), }; let pool_err: InvalidPoolTransactionError = err.into(); - assert!(matches!( - pool_err, - InvalidPoolTransactionError::Overdraft { .. } - )); + assert!(matches!(pool_err, InvalidPoolTransactionError::Other(_))); + assert!( + pool_err.to_string().contains("insufficient token balance"), + "expected token balance error message, got: {pool_err}" + ); + assert!(!PoolError::new(TxHash::ZERO, pool_err).is_bad_transaction()); } #[test] fn test_is_bad_transaction() { + use alloy_primitives::TxHash; + use reth_transaction_pool::error::PoolError; + // Malformed = bad assert!(MorphTxError::InvalidTokenId.is_bad_transaction()); assert!( @@ -244,6 +264,14 @@ mod tests { .is_bad_transaction() ); + // Fork not active = not bad (peer may be 1 block ahead across a fork boundary) + let fork_err = MorphTxError::ForkNotActive { + reason: "MorphTx version 2 is not yet active (celadon fork not reached)".into(), + }; + assert!(!fork_err.is_bad_transaction()); + let pool_fork_err: InvalidPoolTransactionError = fork_err.into(); + assert!(!PoolError::new(TxHash::ZERO, pool_fork_err).is_bad_transaction()); + // Insufficient funds = not bad (shouldn't penalize peer) assert!( !MorphTxError::InsufficientTokenBalance { diff --git a/crates/txpool/src/morph_tx_validation.rs b/crates/txpool/src/morph_tx_validation.rs index f524dd66..6b33b03c 100644 --- a/crates/txpool/src/morph_tx_validation.rs +++ b/crates/txpool/src/morph_tx_validation.rs @@ -7,7 +7,7 @@ use alloy_primitives::{Address, U256}; use morph_chainspec::hardfork::MorphHardfork; use morph_primitives::{ - MorphTxEnvelope, + MorphTxEnvelope, TxMorph, transaction::morph_transaction::{MORPH_TX_VERSION_1, MORPH_TX_VERSION_2}, }; use morph_revm::{MorphEvmEnv, TokenFeeInfo}; @@ -68,23 +68,17 @@ pub fn validate_morph_tx( }) } -/// Validates a MorphTx transaction using a caller-supplied fee-token resolver. +/// Validates stateless MorphTx fork gates and structural invariants without any DB access. /// -/// Structural rules, ETH `value` coverage, and `fee_token_id == 0` ETH-fee checks run before -/// `resolve_token`, so invalid or ETH-paid MorphTxs never touch token registry state. -pub(crate) fn validate_morph_tx_with( - input: &MorphTxValidationInput<'_>, - resolve_token: impl FnOnce(u16, Address) -> Result, -) -> Result { - // Keep MorphTx structural validation in the shared path so both initial - // admission and background revalidation enforce the same invariants. - let morph_tx = match input.consensus_tx { - MorphTxEnvelope::Morph(signed) => signed.tx(), - _ => return Err(MorphTxError::InvalidTokenId), - }; - - if !input.hardfork.is_jade() && morph_tx.version == MORPH_TX_VERSION_1 { - return Err(MorphTxError::InvalidFormat { +/// Called early in [`MorphTransactionValidator`](crate::MorphTransactionValidator) before +/// state lookups, and again inside [`validate_morph_tx_with`] so background revalidation +/// enforces the exact same rules. +pub(crate) fn validate_morph_tx_stateless( + morph_tx: &TxMorph, + hardfork: MorphHardfork, +) -> Result<(), MorphTxError> { + if !hardfork.is_jade() && morph_tx.version == MORPH_TX_VERSION_1 { + return Err(MorphTxError::ForkNotActive { reason: "MorphTx version 1 is not yet active (jade fork not reached)".to_string(), }); } @@ -94,8 +88,8 @@ pub(crate) fn validate_morph_tx_with( // non-empty V2 list forbids CREATE; an empty V2 list is allowed); authority // tracking and delegated-sender limits come from the upstream validator, // which reads the list through `Transaction::authorization_list`. - if !input.hardfork.is_celadon() && morph_tx.version == MORPH_TX_VERSION_2 { - return Err(MorphTxError::InvalidFormat { + if !hardfork.is_celadon() && morph_tx.version == MORPH_TX_VERSION_2 { + return Err(MorphTxError::ForkNotActive { reason: "MorphTx version 2 is not yet active (celadon fork not reached)".to_string(), }); } @@ -106,6 +100,26 @@ pub(crate) fn validate_morph_tx_with( }); } + Ok(()) +} + +/// Validates a MorphTx transaction using a caller-supplied fee-token resolver. +/// +/// Structural rules, ETH `value` coverage, and `fee_token_id == 0` ETH-fee checks run before +/// `resolve_token`, so invalid or ETH-paid MorphTxs never touch token registry state. +pub(crate) fn validate_morph_tx_with( + input: &MorphTxValidationInput<'_>, + resolve_token: impl FnOnce(u16, Address) -> Result, +) -> Result { + // Keep MorphTx structural validation in the shared path so both initial + // admission and background revalidation enforce the same invariants. + let morph_tx = match input.consensus_tx { + MorphTxEnvelope::Morph(signed) => signed.tx(), + _ => return Err(MorphTxError::InvalidTokenId), + }; + + validate_morph_tx_stateless(morph_tx, input.hardfork)?; + let tx_value = morph_tx.value; if tx_value > input.eth_balance { return Err(MorphTxError::InsufficientEthForValue { @@ -512,7 +526,7 @@ mod tests { let err = validate_morph_tx(&mut db, &input).unwrap_err(); assert_eq!( err, - MorphTxError::InvalidFormat { + MorphTxError::ForkNotActive { reason: "MorphTx version 2 is not yet active (celadon fork not reached)" .to_string(), } @@ -555,7 +569,7 @@ mod tests { let err = validate_morph_tx(&mut db, &input).unwrap_err(); assert_eq!( err, - MorphTxError::InvalidFormat { + MorphTxError::ForkNotActive { reason: "MorphTx version 2 is not yet active (celadon fork not reached)" .to_string(), } diff --git a/crates/txpool/src/validator.rs b/crates/txpool/src/validator.rs index f0693eb7..e4e1ffa5 100644 --- a/crates/txpool/src/validator.rs +++ b/crates/txpool/src/validator.rs @@ -405,7 +405,9 @@ where ); } - // Reject EIP-7702 transactions before Viridian hardfork (PRAGUE) + // Reject EIP-7702 transactions before Viridian hardfork (PRAGUE). + // Use `ForkNotActive` (`is_bad_transaction() == false`) so a peer one block ahead + // across the fork boundary is not penalized. if transaction.is_eip7702() && !self .chain_spec() @@ -413,7 +415,11 @@ where { return TransactionValidationOutcome::Invalid( transaction, - InvalidTransactionError::TxTypeNotSupported.into(), + MorphTxError::ForkNotActive { + reason: "EIP-7702 transactions are not yet active (viridian fork not reached)" + .to_string(), + } + .into(), ); } @@ -429,10 +435,31 @@ where { return TransactionValidationOutcome::Invalid( transaction, - InvalidTransactionError::TxTypeNotSupported.into(), + MorphTxError::ForkNotActive { + reason: "MorphTx type is not yet active (emerald fork not reached)".to_string(), + } + .into(), ); } + // Run stateless MorphTx fork gates (Jade V1 / Celadon V2) and structural checks + // (`TxMorph::validate`) BEFORE `inner.validate_one_with_state` so malformed or + // pre-fork MorphTx payloads are rejected without paying for DB / account / authority reads. + if is_morph_tx { + let hardfork = self + .chain_spec() + .morph_hardfork_at(self.block_number(), self.block_timestamp()); + let stateless_res = match transaction.consensus_ref().into_inner() { + MorphTxEnvelope::Morph(signed) => { + crate::morph_tx_validation::validate_morph_tx_stateless(signed.tx(), hardfork) + } + _ => Err(MorphTxError::InvalidTokenId), + }; + if let Err(err) = stateless_res { + return TransactionValidationOutcome::Invalid(transaction, err.into()); + } + } + // EIP-3860: enforce max initcode size on contract-creation transactions. // // Morph has been post-Shanghai since genesis (morph-geth's @@ -1266,4 +1293,170 @@ mod tests { U256::from(2818 + HEAD_TIMESTAMP) ); } + + #[test] + fn fork_not_active_rejections_do_not_penalize_peers() { + use alloy_consensus::TxEip7702; + use alloy_primitives::TxHash; + use reth_transaction_pool::error::PoolError; + + let client = new_mock_provider(); + let signer = address!("0000000000000000000000000000000000000001"); + let morph_evm_config = MorphEvmConfig::new_with_default_factory(MORPH_MAINNET.clone()); + let eth_validator: EthTransactionValidator< + MockEthProvider, + crate::MorphPooledTransaction, + MorphEvmConfig, + > = EthTransactionValidatorBuilder::new(client, morph_evm_config) + .with_custom_tx_type(morph_primitives::MORPH_TX_TYPE_ID) + .disable_balance_check() + .no_eip4844() + .build::(InMemoryBlobStore::default()); + let validator = MorphTransactionValidator::new(eth_validator); + + // Pre-Viridian EIP-7702 (timestamp 0) + validator + .block_info + .update(L1BlockInfo::default(), 0, 1, Some(1)); + let tx_7702 = MorphTxEnvelope::Eip7702(Signed::new_unchecked( + TxEip7702 { + chain_id: 2818, + nonce: 0, + gas_limit: 21_000, + max_fee_per_gas: 1_000_000, + max_priority_fee_per_gas: 0, + to: address!("0000000000000000000000000000000000000002"), + value: U256::ZERO, + access_list: Default::default(), + authorization_list: Vec::new(), + input: Default::default(), + }, + Signature::test_signature(), + B256::ZERO, + )); + let pooled_7702 = + crate::MorphPooledTransaction::new(Recovered::new_unchecked(tx_7702, signer), 100); + match validator.validate_one(TransactionOrigin::External, pooled_7702) { + TransactionValidationOutcome::Invalid(_, err) => { + assert!(err.to_string().contains("not yet active")); + assert!( + !PoolError::new(TxHash::ZERO, err).is_bad_transaction(), + "pre-Viridian EIP-7702 must not penalize peers" + ); + } + other => panic!("expected Invalid(ForkNotActive), got {other:?}"), + } + + // Pre-Emerald MorphTx (timestamp 0) + let make_morph = |version: u8| { + let tx = TxMorph { + chain_id: 2818, + nonce: 0, + gas_limit: 21_000, + max_fee_per_gas: 1_000_000, + max_priority_fee_per_gas: 0, + to: TxKind::Call(address!("0000000000000000000000000000000000000002")), + value: U256::ZERO, + access_list: Default::default(), + version, + fee_token_id: 1, + fee_limit: U256::ZERO, + reference: None, + memo: None, + authorization_list: Vec::new(), + input: Default::default(), + }; + let env = MorphTxEnvelope::Morph(Signed::new_unchecked( + tx, + Signature::test_signature(), + B256::ZERO, + )); + crate::MorphPooledTransaction::new(Recovered::new_unchecked(env, signer), 100) + }; + + match validator.validate_one(TransactionOrigin::External, make_morph(0)) { + TransactionValidationOutcome::Invalid(_, err) => { + assert!(err.to_string().contains("not yet active")); + assert!( + !PoolError::new(TxHash::ZERO, err).is_bad_transaction(), + "pre-Emerald MorphTx must not penalize peers" + ); + } + other => panic!("expected Invalid(ForkNotActive), got {other:?}"), + } + + // Post-Emerald, pre-Jade MorphTx V1 (Emerald timestamp = 1_767_765_600) + validator + .block_info + .update(L1BlockInfo::default(), 1_767_765_600, 10, Some(1)); + match validator.validate_one(TransactionOrigin::External, make_morph(1)) { + TransactionValidationOutcome::Invalid(_, err) => { + assert!(err.to_string().contains("not yet active")); + assert!( + !PoolError::new(TxHash::ZERO, err).is_bad_transaction(), + "pre-Jade MorphTx V1 must not penalize peers" + ); + } + other => panic!("expected Invalid(ForkNotActive), got {other:?}"), + } + } + + #[test] + fn malformed_morph_tx_rejected_before_stateful_validation() { + let client = new_mock_provider(); + let signer = address!("0000000000000000000000000000000000000001"); + // Intentionally give signer nonce=10 so inner stateful check would fail with NonceTooLow + // if it ran before our stateless `TxMorph::validate()`. + client.add_account(signer, ExtendedAccount::new(10, U256::ZERO)); + + let morph_evm_config = MorphEvmConfig::new_with_default_factory(MORPH_MAINNET.clone()); + let eth_validator: EthTransactionValidator< + MockEthProvider, + crate::MorphPooledTransaction, + MorphEvmConfig, + > = EthTransactionValidatorBuilder::new(client, morph_evm_config) + .with_custom_tx_type(morph_primitives::MORPH_TX_TYPE_ID) + .disable_balance_check() + .no_eip4844() + .build::(InMemoryBlobStore::default()); + let validator = MorphTransactionValidator::new(eth_validator); + // Active through Jade so V1 is enabled. + validator + .block_info + .update(L1BlockInfo::default(), u64::MAX - 1, 100, Some(1)); + + let malformed = TxMorph { + chain_id: 2818, + nonce: 0, // < on-chain nonce 10 + gas_limit: 21_000, + max_fee_per_gas: 1_000_000, + max_priority_fee_per_gas: 0, + to: TxKind::Call(address!("0000000000000000000000000000000000000002")), + value: U256::ZERO, + access_list: Default::default(), + version: 1, + fee_token_id: 0, + fee_limit: U256::from(1u64), // invalid: fee_token_id == 0 with fee_limit > 0 + reference: None, + memo: None, + authorization_list: Vec::new(), + input: Default::default(), + }; + let env = MorphTxEnvelope::Morph(Signed::new_unchecked( + malformed, + Signature::test_signature(), + B256::ZERO, + )); + let pooled = crate::MorphPooledTransaction::new(Recovered::new_unchecked(env, signer), 100); + + match validator.validate_one(TransactionOrigin::External, pooled) { + TransactionValidationOutcome::Invalid(_, err) => { + assert!( + err.to_string().contains("invalid MorphTx format"), + "stateless MorphTx format check must fire before stateful nonce check, got: {err}" + ); + } + other => panic!("expected InvalidFormat before stateful check, got {other:?}"), + } + } } From 5c67c7ee89dc26bc1aaa642087ab084fa02e0dd6 Mon Sep 17 00:00:00 2001 From: panos-xyz Date: Fri, 27 Nov 2026 00:09:18 +0800 Subject: [PATCH 08/16] feat(pr-229): port main PRs #239-#246 and add evm2 audit regression tests --- Cargo.lock | 8 +- bin/morph-reth/Cargo.toml | 1 + bin/morph-reth/src/main.rs | 169 +++- crates/chainspec/src/genesis.rs | 73 +- crates/chainspec/src/lib.rs | 2 +- crates/chainspec/src/spec.rs | 478 ++++++++-- crates/engine-api/Cargo.toml | 1 + crates/engine-api/src/builder.rs | 296 +++++- crates/evm/src/lib.rs | 2 +- crates/node/Cargo.toml | 2 +- crates/node/src/add_ons.rs | 15 +- crates/node/src/test_utils.rs | 89 +- crates/node/src/validator.rs | 325 +++++-- crates/node/tests/it/consensus.rs | 75 ++ crates/node/tests/it/engine.rs | 260 +++++- .../node/tests/it/invalid_payload_recovery.rs | 164 +++- crates/node/tests/it/network.rs | 8 +- crates/node/tests/it/reference_index.rs | 96 ++ crates/node/tests/it/rpc.rs | 693 ++++++++++++++ crates/node/tests/it/txpool.rs | 119 ++- crates/payload/builder/Cargo.toml | 2 + crates/payload/builder/src/builder.rs | 868 +++++++++++++++++- crates/reference-index/src/lib.rs | 2 +- crates/reference-index/src/reader.rs | 63 +- crates/reference-index/src/runtime.rs | 141 ++- crates/revm/src/handler.rs | 271 +++++- crates/rpc/Cargo.toml | 2 + crates/rpc/src/eth/call.rs | 438 ++++++++- crates/rpc/src/eth/mod.rs | 31 +- crates/rpc/src/eth/transaction.rs | 130 ++- crates/rpc/src/morph/handler.rs | 808 ++++++++++++---- crates/rpc/src/morph/rpc.rs | 9 +- crates/txpool/src/maintain.rs | 49 +- crates/txpool/src/morph_tx_validation.rs | 13 +- crates/txpool/src/validator.rs | 35 +- 35 files changed, 5162 insertions(+), 576 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 510ff14b..9576c9eb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5338,6 +5338,7 @@ dependencies = [ "reth-rpc-api", "serde_json", "thiserror 2.0.21", + "tokio", "tracing", ] @@ -5386,7 +5387,6 @@ dependencies = [ "alloy-signer", "alloy-signer-local", "clap", - "dashmap", "eyre", "futures", "jsonrpsee", @@ -5405,6 +5405,7 @@ dependencies = [ "parking_lot", "reth-chain-state", "reth-chainspec", + "reth-consensus", "reth-db", "reth-e2e-test-utils", "reth-engine-local", @@ -5454,6 +5455,7 @@ dependencies = [ "morph-evm", "morph-payload-types", "morph-primitives", + "morph-txpool", "reth-basic-payload-builder", "reth-chainspec", "reth-evm", @@ -5467,6 +5469,7 @@ dependencies = [ "reth-storage-api", "reth-tasks", "reth-transaction-pool", + "reth-trie-common", "reth-trie-parallel", "thiserror 2.0.21", "tracing", @@ -5616,6 +5619,7 @@ dependencies = [ "reth-cli-util", "reth-ethereum-cli", "reth-node-builder", + "reth-node-core", "reth-provider", "reth-rpc-server-types", "reth-stages-types", @@ -5655,6 +5659,7 @@ dependencies = [ "async-trait", "derive_more", "evm2", + "evm2-inspectors", "eyre", "futures", "jsonrpsee", @@ -5669,6 +5674,7 @@ dependencies = [ "reth-chainspec", "reth-errors", "reth-evm", + "reth-execution-types", "reth-metrics", "reth-node-api", "reth-node-builder", diff --git a/bin/morph-reth/Cargo.toml b/bin/morph-reth/Cargo.toml index f2e74e48..4947ffc0 100644 --- a/bin/morph-reth/Cargo.toml +++ b/bin/morph-reth/Cargo.toml @@ -31,6 +31,7 @@ reth-cli-runner.workspace = true reth-cli-util.workspace = true reth-ethereum-cli.workspace = true reth-node-builder.workspace = true +reth-node-core.workspace = true reth-provider.workspace = true reth-stages-types.workspace = true reth-rpc-server-types.workspace = true diff --git a/bin/morph-reth/src/main.rs b/bin/morph-reth/src/main.rs index 65b7a028..900b6b05 100644 --- a/bin/morph-reth/src/main.rs +++ b/bin/morph-reth/src/main.rs @@ -19,7 +19,9 @@ static MALLOC_CONF: &[u8] = b"prof:true,prof_active:true,lg_prof_sample:19\0"; use alloy_primitives::U256; use clap::Parser; -use morph_chainspec::{MORPH_DEFAULT_PRIORITY_FEE, MorphChainSpec, MorphChainSpecParser}; +use morph_chainspec::{ + MORPH_BASE_FEE, MORPH_DEFAULT_PRIORITY_FEE, MorphChainSpec, MorphChainSpecParser, +}; use morph_consensus::MorphConsensus; use morph_evm::{MorphEvmConfig, evm::MorphEvmFactory}; use morph_node::{MorphAddOns, MorphArgs, MorphNode}; @@ -30,16 +32,59 @@ use reth_chainspec::EthChainSpec; use reth_cli_util::sigsegv_handler; use reth_ethereum_cli::{Cli, Commands}; use reth_node_builder::Node; -use reth_rpc_server_types::DefaultRpcModuleValidator; -use std::sync::Arc; +use reth_node_core::args::{DefaultTxPoolValues, TxPoolArgs}; +use reth_rpc_server_types::{RethRpcModule, RpcModuleSelection, RpcModuleValidator}; +use std::{str::FromStr, sync::Arc}; use tracing::info; +/// Morph RPC module validator: accepts all standard Reth RPC modules plus the +/// Morph-specific `morph` namespace while rejecting any other unknown module name. +#[derive(Debug, Clone, Copy, Default)] +struct MorphRpcModuleValidator; + +impl RpcModuleValidator for MorphRpcModuleValidator { + fn parse_selection(s: &str) -> Result { + let selection = RpcModuleSelection::from_str(s) + .map_err(|e| format!("Failed to parse RPC modules: {e}"))?; + + if let RpcModuleSelection::Selection(modules) = &selection { + for module in modules { + if let RethRpcModule::Other(name) = module + && name != "morph" + { + return Err(format!("Unknown RPC module: '{name}'")); + } + } + } + + Ok(selection) + } +} + fn morph_default_suggested_fee() -> U256 { U256::from_limbs([MORPH_DEFAULT_PRIORITY_FEE, 0, 0, 0]) } +/// Set Morph's default txpool minimum protocol base fee before CLI parsing. +/// +/// Morph fixes L2 `baseFee` at `MORPH_BASE_FEE` (0.001 Gwei = 1_000_000 wei), +/// so transactions with `maxFeePerGas < MORPH_BASE_FEE` can never be included +/// in a block. Raising the default from Ethereum L1's 7 wei prevents them from +/// parking indefinitely in `basefee_pool` and inflating `eth_getTransactionCount("pending")`, +/// while still allowing operators to override via `--txpool.minimal-protocol-fee`. +fn init_morph_txpool_defaults() { + let _ = DefaultTxPoolValues::default() + .with_minimal_protocol_basefee(MORPH_BASE_FEE) + .try_init(); + debug_assert_eq!( + TxPoolArgs::default().minimal_protocol_basefee, + MORPH_BASE_FEE, + "txpool defaults must be initialized before CLI parsing" + ); +} + fn apply_morph_cli_defaults( - cli: &mut Cli, + cli: &mut Cli, ) { if let Commands::Node(command) = &mut cli.command { command @@ -55,6 +100,10 @@ fn main() { // commit SHA, and build timestamp. Must be called before CLI parsing. morph_node::version::init_version_metadata(); + // Override reth's default minimal protocol base fee (7 wei on Ethereum L1) + // with Morph's fixed base fee (0.001 Gwei). Must be called before CLI parsing. + init_morph_txpool_defaults(); + // Install signal handler for segmentation faults sigsegv_handler::install(); @@ -74,7 +123,7 @@ fn main() { }; let mut cli = - Cli::::parse(); + Cli::::parse(); apply_morph_cli_defaults(&mut cli); // Run the node @@ -175,13 +224,16 @@ fn main() { mod tests { use super::*; - type MorphCli = - Cli; + type MorphCli = Cli; + + fn parse_cli(args: impl IntoIterator) -> MorphCli { + init_morph_txpool_defaults(); + MorphCli::try_parse_from(args).expect("CLI arguments must parse") + } #[test] fn parses_top_level_proofs_command() { - let cli = MorphCli::try_parse_from(["morph-reth", "proofs", "init", "--chain", "hoodi"]) - .expect("top-level proofs command must parse"); + let cli = parse_cli(["morph-reth", "proofs", "init", "--chain", "hoodi"]); assert!(matches!( cli.command, Commands::Ext(MorphSubcommand::Proofs(_)) @@ -190,12 +242,107 @@ mod tests { #[test] fn disabled_mode_keeps_reth_historical_overlay_off() { - let cli = MorphCli::try_parse_from(["morph-reth", "node", "--chain", "hoodi"]) - .expect("node command must parse"); + let cli = parse_cli(["morph-reth", "node", "--chain", "hoodi"]); let Commands::Node(command) = cli.command else { panic!("expected node command") }; assert!(!command.ext.proofs_history); assert_eq!(command.rpc.rpc_eth_proof_window, 0); } + + #[test] + fn default_minimal_protocol_fee_matches_morph_base_fee() { + let cli = parse_cli(["morph-reth", "node", "--chain", "hoodi"]); + let Commands::Node(command) = cli.command else { + panic!("expected node command") + }; + assert_eq!(command.txpool.minimal_protocol_basefee, MORPH_BASE_FEE); + } + + #[test] + fn minimal_protocol_fee_cli_flag_overrides_default() { + for expected in [0u64, 7, 2_000_000] { + let value = expected.to_string(); + init_morph_txpool_defaults(); + let cli = MorphCli::try_parse_from([ + "morph-reth", + "node", + "--chain", + "hoodi", + "--txpool.minimal-protocol-fee", + value.as_str(), + ]) + .expect("node command with --txpool.minimal-protocol-fee must parse"); + let Commands::Node(command) = cli.command else { + panic!("expected node command") + }; + assert_eq!(command.txpool.minimal_protocol_basefee, expected); + } + } + + #[test] + fn cli_rpc_module_validator_accepts_morph_on_http_ws_and_all() { + let cli = parse_cli([ + "morph-reth", + "node", + "--chain", + "hoodi", + "--http", + "--http.api", + "eth,morph", + "--ws", + "--ws.api", + "eth,morph", + ]); + let Commands::Node(command) = cli.command else { + panic!("expected node command") + }; + + let http_api = command.rpc.http_api.as_ref().expect("http.api set"); + let ws_api = command.rpc.ws_api.as_ref().expect("ws.api set"); + assert!(http_api.contains(&RethRpcModule::Other("morph".into()))); + assert!(ws_api.contains(&RethRpcModule::Other("morph".into()))); + assert!(MorphRpcModuleValidator::validate_selection(http_api, "http.api").is_ok()); + assert!(MorphRpcModuleValidator::validate_selection(ws_api, "ws.api").is_ok()); + + let all_cli = parse_cli([ + "morph-reth", + "node", + "--chain", + "hoodi", + "--http", + "--http.api", + "all", + ]); + let Commands::Node(all_cmd) = all_cli.command else { + panic!("expected node command") + }; + let all_api = all_cmd.rpc.http_api.as_ref().expect("http.api set"); + assert!(all_api.contains(&RethRpcModule::Other("morph".into()))); + assert!(MorphRpcModuleValidator::validate_selection(all_api, "http.api").is_ok()); + } + + #[test] + fn cli_rpc_module_validator_rejects_unknown_module_names() { + let cli = parse_cli([ + "morph-reth", + "node", + "--chain", + "hoodi", + "--http", + "--http.api", + "eth,unknown", + ]); + let Commands::Node(command) = cli.command else { + panic!("expected node command") + }; + + let http_api = command.rpc.http_api.as_ref().expect("http.api set"); + let err = MorphRpcModuleValidator::validate_selection(http_api, "http.api") + .expect_err("unknown RPC module must be rejected by MorphRpcModuleValidator"); + assert!( + err.contains("Unknown RPC module: 'unknown'"), + "unexpected validation error: {err}" + ); + } } diff --git a/crates/chainspec/src/genesis.rs b/crates/chainspec/src/genesis.rs index ca5231d1..44c4eaf3 100644 --- a/crates/chainspec/src/genesis.rs +++ b/crates/chainspec/src/genesis.rs @@ -27,7 +27,7 @@ impl TryFrom<&OtherFields> for MorphGenesisInfo { type Error = serde_json::Error; fn try_from(others: &OtherFields) -> Result { - let hard_fork_info = MorphHardforkInfo::try_from(others).ok(); + let hard_fork_info = Some(MorphHardforkInfo::try_from(others)?); let morph_chain_info = MorphChainConfig::try_from(others)?; Ok(Self { @@ -134,10 +134,9 @@ impl TryFrom<&OtherFields> for MorphChainConfig { type Error = serde_json::Error; fn try_from(others: &OtherFields) -> Result { - if let Some(Ok(morph_config)) = others.get_deserialized::("morph") { - Ok(morph_config) - } else { - Err(serde_json::Error::missing_field("morph")) + match others.get_deserialized::("morph") { + Some(res) => res, + None => Err(serde_json::Error::missing_field("morph")), } } } @@ -264,4 +263,68 @@ mod tests { ); assert_eq!(config.max_tx_payload_bytes_per_block, 122_880); } + + #[test] + fn test_morph_genesis_info_rejects_malformed_hardfork_field() { + for raw in [ + r#"{"celadonTime": "1750000000", "morph": {}}"#, + r#"{"bernoulliBlock": -1, "morph": {}}"#, + r#"{"viridianTime": true, "morph": {}}"#, + ] { + let others: OtherFields = serde_json::from_str(raw).unwrap(); + let err = MorphGenesisInfo::try_from(&others) + .expect_err("malformed Morph hardfork field must fail deserialization"); + let msg = err.to_string(); + assert!( + !msg.contains("missing field `morph`"), + "expected hardfork deserialization error, got: {msg}" + ); + assert!( + MorphGenesisInfo::extract_from(&others).is_none(), + "extract_from must not silently drop malformed hardforks" + ); + } + } + + #[test] + fn test_morph_genesis_info_allows_empty_hardfork_fields() { + let others: OtherFields = serde_json::from_str(r#"{"morph": {}}"#).unwrap(); + let info = MorphGenesisInfo::try_from(&others).expect("empty hardforks must succeed"); + + assert_eq!(info.hard_fork_info, Some(MorphHardforkInfo::default())); + assert_eq!(info.morph_chain_info, MorphChainConfig::default()); + } + + #[test] + fn test_morph_chain_config_preserves_inner_serde_error() { + // Missing `morph` key reports missing field `morph`. + let missing: OtherFields = serde_json::from_str(r#"{}"#).unwrap(); + let err = MorphChainConfig::try_from(&missing).unwrap_err(); + assert!( + err.to_string().contains("missing field `morph`"), + "expected missing field error, got: {err}" + ); + + // Malformed subfields or wrong type for `morph` preserve the real serde error. + for raw in [ + r#"{"morph": {"feeVaultAddress": "not-an-address"}}"#, + r#"{"morph": {"maxTxPayloadBytesPerBlock": "122880"}}"#, + r#"{"morph": "not-an-object"}"#, + ] { + let others: OtherFields = serde_json::from_str(raw).unwrap(); + let err = MorphChainConfig::try_from(&others) + .expect_err("malformed morph config must fail deserialization"); + let msg = err.to_string(); + assert!( + !msg.contains("missing field `morph`"), + "inner serde error for `{raw}` must not be replaced by missing field: {msg}" + ); + let genesis_err = MorphGenesisInfo::try_from(&others) + .expect_err("MorphGenesisInfo::try_from must propagate inner morph error"); + assert!( + !genesis_err.to_string().contains("missing field `morph`"), + "MorphGenesisInfo error for `{raw}` must preserve inner error: {genesis_err}" + ); + } + } } diff --git a/crates/chainspec/src/lib.rs b/crates/chainspec/src/lib.rs index 843d062b..80253ac8 100644 --- a/crates/chainspec/src/lib.rs +++ b/crates/chainspec/src/lib.rs @@ -66,9 +66,9 @@ pub use hardfork::{MorphHardfork, MorphHardforks}; pub use morph::MORPH_MAINNET; pub use morph_hoodi::MORPH_HOODI; -pub use spec::MorphChainSpec; #[cfg(feature = "cli")] pub use spec::MorphChainSpecParser; +pub use spec::{MorphChainSpec, MorphChainSpecError}; // Convenience re-export of the chain spec provider. pub use reth_chainspec::ChainSpecProvider; diff --git a/crates/chainspec/src/spec.rs b/crates/chainspec/src/spec.rs index 5376cbaa..7cccb30d 100644 --- a/crates/chainspec/src/spec.rs +++ b/crates/chainspec/src/spec.rs @@ -25,25 +25,45 @@ use crate::{morph::MORPH_MAINNET, morph_hoodi::MORPH_HOODI}; use std::sync::Arc; // ============================================================================= -// Genesis Helper Functions +// Genesis Helper Functions & Error Types // ============================================================================= -/// Build a genesis header with the given state root. -/// -/// This allows using a ZK-trie state root (from go-ethereum) instead of -/// computing an MPT state root from alloc. This is necessary because -/// Morph uses ZK-trie before Jade hardfork. -pub(crate) fn make_genesis_header(genesis: &Genesis, state_root: B256) -> MorphHeader { - let base_spec = ChainSpec::from_genesis(genesis.clone()); - let mut inner = base_spec.genesis_header.header().clone(); - inner.state_root = state_root; - // morph-geth defaults to MORPH_BASE_FEE (1_000_000) when baseFeePerGas is - // absent, not Ethereum's INITIAL_BASE_FEE (1_000_000_000). Apply the same - // default so the genesis block header hash matches. - if genesis.base_fee_per_gas.is_none() { - inner.base_fee_per_gas = Some(MORPH_BASE_FEE); - } - MorphHeader::from(inner) +/// Errors returned when constructing a [`MorphChainSpec`] from a [`Genesis`]. +#[derive(Debug)] +pub enum MorphChainSpecError { + /// Failed to deserialize Morph-specific fields from `genesis.config.extra_fields`. + InvalidGenesisInfo(serde_json::Error), + /// [`GenesisConfig::state_root`] was specified without a matching + /// [`GenesisConfig::genesis_hash`]. + MissingGenesisHash, +} + +impl std::fmt::Display for MorphChainSpecError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::InvalidGenesisInfo(err) => { + write!(f, "invalid Morph genesis configuration: {err}") + } + Self::MissingGenesisHash => { + write!(f, "genesis_hash is required when state_root is provided") + } + } + } +} + +impl std::error::Error for MorphChainSpecError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Self::InvalidGenesisInfo(err) => Some(err), + Self::MissingGenesisHash => None, + } + } +} + +impl From for MorphChainSpecError { + fn from(err: serde_json::Error) -> Self { + Self::InvalidGenesisInfo(err) + } } /// Configuration for building a genesis header. @@ -74,22 +94,18 @@ impl GenesisConfig { } } -/// Build Morph hardforks configuration from genesis. +/// Extend base Ethereum hardforks with Morph hardforks from genesis. /// /// This is the unified hardfork construction logic, eliminating code duplication /// between different construction paths (CLI genesis parsing vs predefined networks). /// /// # Arguments -/// * `genesis` - Genesis configuration containing Ethereum and Morph hardfork info +/// * `hardforks` - Base Ethereum hardforks parsed from genesis /// * `chain_info` - Morph-specific genesis information extracted from genesis config /// /// # Returns /// A `ChainHardforks` containing both Ethereum and Morph hardforks -fn build_hardforks(genesis: &Genesis, chain_info: &MorphGenesisInfo) -> ChainHardforks { - // Start with Ethereum hardforks from genesis - let base_spec = ChainSpec::from_genesis(genesis.clone()); - let mut hardforks = base_spec.hardforks; - +fn build_hardforks(mut hardforks: ChainHardforks, chain_info: &MorphGenesisInfo) -> ChainHardforks { let hardfork_info = chain_info .hard_fork_info .as_ref() @@ -154,7 +170,9 @@ pub fn chain_value_parser(s: &str) -> eyre::Result> { Ok(match s { "mainnet" => MORPH_MAINNET.clone(), "hoodi" => MORPH_HOODI.clone(), - _ => Arc::new(MorphChainSpec::from(reth_cli::chainspec::parse_genesis(s)?)), + _ => Arc::new(MorphChainSpec::try_from_genesis( + reth_cli::chainspec::parse_genesis(s)?, + )?), }) } @@ -210,15 +228,111 @@ impl MorphChainSpec { Self { inner, info } } + /// Fallibly build a [`MorphChainSpec`] from a genesis configuration. + /// + /// Automatically computes the MPT state root from the genesis alloc. + /// Suitable for CLI scenarios where users provide custom `genesis.json` files. + pub fn try_from_genesis(genesis: Genesis) -> Result { + Self::try_from_genesis_with_config(genesis, GenesisConfig::default()) + } + + /// Fallibly build a [`MorphChainSpec`] from a genesis configuration with custom settings. + /// + /// Preserves all fields parsed by [`ChainSpec::from_genesis`] (such as + /// `paris_block_and_final_difficulty`, `base_fee_params`, `blob_params`, + /// `deposit_contract`, and `prune_delete_limit`) while layering Morph's hardforks + /// and genesis header defaults on top. + /// + /// # Errors + /// Returns [`MorphChainSpecError::InvalidGenesisInfo`] if the Morph genesis fields are + /// missing or malformed, or [`MorphChainSpecError::MissingGenesisHash`] if + /// `config.state_root` is provided without `config.genesis_hash`. + pub fn try_from_genesis_with_config( + genesis: Genesis, + config: GenesisConfig, + ) -> Result { + let chain_info = MorphGenesisInfo::try_from(&genesis.config.extra_fields)?; + if config.state_root.is_some() && config.genesis_hash.is_none() { + return Err(MorphChainSpecError::MissingGenesisHash); + } + + let base_spec = ChainSpec::from_genesis(genesis); + Self::from_base_spec_with_info(base_spec, chain_info, config) + } + + fn from_base_spec_with_info( + base_spec: ChainSpec, + chain_info: MorphGenesisInfo, + config: GenesisConfig, + ) -> Result { + let ChainSpec { + chain, + genesis, + genesis_header: base_genesis_header, + paris_block_and_final_difficulty, + hardforks: base_hardforks, + deposit_contract, + base_fee_params, + prune_delete_limit, + blob_params, + } = base_spec; + + // Extend Ethereum hardforks with Morph hardforks (and Prague at Viridian time). + let hardforks = build_hardforks(base_hardforks, &chain_info); + + // Apply Morph's genesis base fee default and optional custom state root. + let mut header = base_genesis_header.unseal(); + // morph-geth defaults to MORPH_BASE_FEE (1_000_000) when baseFeePerGas is + // absent, not Ethereum's INITIAL_BASE_FEE (1_000_000_000). Apply the same + // default so the genesis block header hash matches. + if genesis.base_fee_per_gas.is_none() { + header.base_fee_per_gas = Some(MORPH_BASE_FEE); + } + + let genesis_header = match config.state_root { + Some(state_root) => { + // Use custom state root (for predefined networks with ZK-trie) + let genesis_hash = config + .genesis_hash + .ok_or(MorphChainSpecError::MissingGenesisHash)?; + header.state_root = state_root; + SealedHeader::new(MorphHeader::from(header), genesis_hash) + } + None => { + // Use MPT state root computed from alloc (for CLI-provided genesis) + let header = MorphHeader::from(header); + // Recompute genesis hash with the corrected base fee + let hash = header.hash_slow(); + SealedHeader::new(header, hash) + } + }; + + Ok(Self { + inner: ChainSpec { + chain, + genesis_header, + genesis, + paris_block_and_final_difficulty, + hardforks, + deposit_contract, + base_fee_params, + prune_delete_limit, + blob_params, + }, + info: chain_info, + }) + } + /// Build a [`MorphChainSpec`] from a genesis configuration. /// /// This is the default method for constructing a chain spec from genesis. /// It automatically computes the MPT state root from the genesis alloc. /// - /// This method is suitable for CLI scenarios where users provide custom - /// genesis.json files. + /// # Panics + /// Panics if the Morph genesis fields are missing or malformed. Use + /// [`Self::try_from_genesis`] for fallible construction. pub fn from_genesis(genesis: Genesis) -> Self { - Self::from_genesis_with_config(genesis, GenesisConfig::default()) + Self::try_from_genesis(genesis).expect("failed to build morph chain spec from genesis") } /// Build a [`MorphChainSpec`] from a genesis configuration with custom settings. @@ -231,7 +345,9 @@ impl MorphChainSpec { /// * `config` - Genesis header configuration (state root, genesis hash) /// /// # Panics - /// Panics if `config.state_root` is provided but `config.genesis_hash` is not. + /// Panics if the Morph genesis fields are missing or malformed, or if + /// `config.state_root` is provided without `config.genesis_hash`. Use + /// [`Self::try_from_genesis_with_config`] for fallible construction. /// /// # Example /// ```no_run @@ -247,49 +363,8 @@ impl MorphChainSpec { /// let spec = MorphChainSpec::from_genesis_with_config(genesis, config); /// ``` pub fn from_genesis_with_config(genesis: Genesis, config: GenesisConfig) -> Self { - let chain_info = MorphGenesisInfo::extract_from(&genesis.config.extra_fields) - .expect("failed to extract morph genesis info"); - - // Build hardforks using the unified logic - let hardforks = build_hardforks(&genesis, &chain_info); - - // Build genesis header based on configuration - let genesis_header = match config.state_root { - Some(state_root) => { - // Use custom state root (for predefined networks with ZK-trie) - let header = make_genesis_header(&genesis, state_root); - let genesis_hash = config - .genesis_hash - .expect("genesis_hash is required when state_root is provided"); - SealedHeader::new(header, genesis_hash) - } - None => { - // Compute MPT state root from alloc (for CLI-provided genesis) - let base_spec = ChainSpec::from_genesis(genesis.clone()); - let mut header = base_spec.genesis_header.header().clone(); - // morph-geth defaults to MORPH_BASE_FEE (1_000_000) when - // baseFeePerGas is absent, not Ethereum's INITIAL_BASE_FEE - // (1_000_000_000). Override to match. - if genesis.base_fee_per_gas.is_none() { - header.base_fee_per_gas = Some(MORPH_BASE_FEE); - } - let header = MorphHeader::from(header); - // Recompute genesis hash with the corrected base fee - let hash = header.hash_slow(); - SealedHeader::new(header, hash) - } - }; - - Self { - inner: ChainSpec { - chain: genesis.config.chain_id.into(), - genesis_header, - genesis, - hardforks, - ..Default::default() - }, - info: chain_info, - } + Self::try_from_genesis_with_config(genesis, config) + .expect("failed to build morph chain spec from genesis") } /// Returns whether the fee vault is enabled. @@ -310,8 +385,10 @@ impl MorphChainSpec { impl From for MorphChainSpec { fn from(value: ChainSpec) -> Self { - let genesis = value.genesis; - genesis.into() + let chain_info = MorphGenesisInfo::try_from(&value.genesis.config.extra_fields) + .expect("failed to extract morph genesis info"); + Self::from_base_spec_with_info(value, chain_info, GenesisConfig::default()) + .expect("failed to build morph chain spec from chain spec") } } @@ -915,4 +992,257 @@ mod tests { ); assert_eq!(config.max_tx_payload_bytes_per_block(), 122_880); } + + #[test] + fn test_try_from_genesis_rejects_malformed_hardfork_and_morph_config() { + // Malformed Morph hardfork field (string instead of u64) must return Err. + let malformed_fork: Genesis = serde_json::from_value(json!({ + "config": { + "chainId": 1337, + "celadonTime": "1750000000", + "morph": {} + }, + "alloc": {} + })) + .unwrap(); + let err = MorphChainSpec::try_from_genesis(malformed_fork) + .expect_err("malformed celadonTime must fail try_from_genesis"); + assert!(matches!(err, MorphChainSpecError::InvalidGenesisInfo(_))); + assert!( + !err.to_string().contains("missing field `morph`"), + "unexpected error: {err}" + ); + + // Missing `morph` object must return Err mentioning missing field `morph`. + let missing_morph: Genesis = serde_json::from_value(json!({ + "config": { + "chainId": 1337 + }, + "alloc": {} + })) + .unwrap(); + let err = MorphChainSpec::try_from_genesis(missing_morph) + .expect_err("missing morph section must fail try_from_genesis"); + assert!(matches!(err, MorphChainSpecError::InvalidGenesisInfo(_))); + assert!( + err.to_string().contains("missing field `morph`"), + "expected missing field error, got: {err}" + ); + + // Malformed `morph` subfield must preserve inner serde error (not `missing field 'morph'`). + let malformed_morph: Genesis = serde_json::from_value(json!({ + "config": { + "chainId": 1337, + "morph": { + "feeVaultAddress": "not-an-address" + } + }, + "alloc": {} + })) + .unwrap(); + let err = MorphChainSpec::try_from_genesis(malformed_morph) + .expect_err("malformed feeVaultAddress must fail try_from_genesis"); + assert!(matches!(err, MorphChainSpecError::InvalidGenesisInfo(_))); + assert!( + !err.to_string().contains("missing field `morph`"), + "inner serde error must not be masked: {err}" + ); + + // Custom state_root without genesis_hash must return MissingGenesisHash without panicking. + let valid_empty_forks: Genesis = serde_json::from_value(json!({ + "config": { + "chainId": 1337, + "morph": {} + }, + "alloc": {} + })) + .unwrap(); + let err = MorphChainSpec::try_from_genesis_with_config( + valid_empty_forks.clone(), + GenesisConfig { + state_root: Some(B256::ZERO), + genesis_hash: None, + }, + ) + .expect_err("state_root without genesis_hash must fail"); + assert!(matches!(err, MorphChainSpecError::MissingGenesisHash)); + + // Empty Morph hardfork fields still succeed. + let spec = MorphChainSpec::try_from_genesis(valid_empty_forks) + .expect("empty Morph hardfork fields must succeed"); + assert_eq!(spec.chain().id(), 1337); + assert_eq!( + spec.genesis_header().inner.base_fee_per_gas, + Some(MORPH_BASE_FEE) + ); + } + + #[test] + fn test_from_genesis_preserves_chainspec_fields() { + let deposit_addr = address!("1111111111111111111111111111111111111111"); + let genesis: Genesis = serde_json::from_value(json!({ + "config": { + "chainId": 1337, + "homesteadBlock": 0, + "eip150Block": 0, + "eip155Block": 0, + "eip158Block": 0, + "byzantiumBlock": 0, + "constantinopleBlock": 0, + "petersburgBlock": 0, + "istanbulBlock": 0, + "berlinBlock": 0, + "londonBlock": 0, + "mergeNetsplitBlock": 0, + "terminalTotalDifficulty": 42, + "terminalTotalDifficultyPassed": true, + "shanghaiTime": 0, + "cancunTime": 0, + "depositContractAddress": "0x1111111111111111111111111111111111111111", + "blobSchedule": { + "cancun": { + "target": 4, + "max": 8, + "baseFeeUpdateFraction": 3338477 + } + }, + "bernoulliBlock": 0, + "curieBlock": 0, + "morph": {} + }, + "alloc": {} + })) + .expect("genesis should be valid"); + + let base_spec = ChainSpec::from_genesis(genesis.clone()); + let morph_spec = MorphChainSpec::try_from_genesis(genesis).unwrap(); + + assert_eq!( + morph_spec.inner.paris_block_and_final_difficulty, + Some((0, U256::from(42))) + ); + assert_eq!( + morph_spec.final_paris_total_difficulty(), + Some(U256::from(42)) + ); + assert_eq!( + morph_spec.deposit_contract().map(|c| c.address), + Some(deposit_addr) + ); + let blob_params = morph_spec + .blob_params_at_timestamp(0) + .expect("cancun blob params should be preserved"); + assert_eq!(blob_params.target_blob_count, 4); + assert_eq!(blob_params.max_blob_count, 8); + assert_eq!(blob_params.update_fraction, 3_338_477); + assert_eq!(morph_spec.inner.base_fee_params, base_spec.base_fee_params); + assert_eq!( + morph_spec.prune_delete_limit(), + base_spec.prune_delete_limit + ); + + // From must also preserve explicit ChainSpec overrides. + let mut custom_base = base_spec; + let custom_base_fee_params = + reth_chainspec::BaseFeeParamsKind::Constant(BaseFeeParams::new(42, 7)); + custom_base.base_fee_params = custom_base_fee_params.clone(); + custom_base.prune_delete_limit = 12_345; + let converted = MorphChainSpec::from(custom_base); + assert_eq!(converted.inner.base_fee_params, custom_base_fee_params); + assert_eq!(converted.prune_delete_limit(), 12_345); + } + + #[cfg(feature = "cli")] + #[test] + fn test_chain_value_parser_handles_invalid_and_valid_custom_genesis() { + // Malformed hardfork field returns Err instead of panicking. + let malformed_fork = json!({ + "config": { + "chainId": 1337, + "celadonTime": "1750000000", + "morph": {} + }, + "alloc": {} + }) + .to_string(); + let err = chain_value_parser(&malformed_fork) + .expect_err("malformed hardfork in custom genesis must return Err"); + assert!( + !err.to_string().contains("missing field `morph`"), + "unexpected error: {err}" + ); + + // Missing `morph` section returns Err instead of panicking. + let missing_morph = json!({ + "config": { + "chainId": 1337 + }, + "alloc": {} + }) + .to_string(); + let err = chain_value_parser(&missing_morph) + .expect_err("missing morph config in custom genesis must return Err"); + assert!( + err.to_string().contains("missing field `morph`"), + "expected missing field error, got: {err}" + ); + + // Malformed `morph` subfield preserves inner serde error instead of panicking. + let malformed_morph = json!({ + "config": { + "chainId": 1337, + "morph": { + "maxTxPayloadBytesPerBlock": "not-a-number" + } + }, + "alloc": {} + }) + .to_string(); + let err = chain_value_parser(&malformed_morph) + .expect_err("malformed morph subfield must return Err"); + assert!( + !err.to_string().contains("missing field `morph`"), + "inner serde error must not be replaced: {err}" + ); + + // Valid custom genesis with empty hardfork fields succeeds. + let valid_custom = json!({ + "config": { + "chainId": 1337, + "morph": {} + }, + "alloc": {} + }) + .to_string(); + let parsed = chain_value_parser(&valid_custom) + .expect("valid custom genesis must parse without error"); + assert_eq!(parsed.chain().id(), 1337); + assert_eq!( + parsed.genesis_header().inner.base_fee_per_gas, + Some(MORPH_BASE_FEE) + ); + + // Predefined networks remain intact with expected genesis hash and base fee default. + let mainnet = chain_value_parser("mainnet").unwrap(); + assert_eq!(mainnet.genesis_hash(), crate::MORPH_MAINNET_GENESIS_HASH); + assert_eq!( + mainnet.genesis_header().hash_slow(), + crate::MORPH_MAINNET_GENESIS_HASH + ); + assert_eq!( + mainnet.genesis_header().inner.base_fee_per_gas, + Some(MORPH_BASE_FEE) + ); + + let hoodi = chain_value_parser("hoodi").unwrap(); + assert_eq!(hoodi.genesis_hash(), crate::MORPH_HOODI_GENESIS_HASH); + assert_eq!( + hoodi.genesis_header().hash_slow(), + crate::MORPH_HOODI_GENESIS_HASH + ); + assert_eq!( + hoodi.genesis_header().inner.base_fee_per_gas, + Some(MORPH_BASE_FEE) + ); + } } diff --git a/crates/engine-api/Cargo.toml b/crates/engine-api/Cargo.toml index e52b121d..a6630d7a 100644 --- a/crates/engine-api/Cargo.toml +++ b/crates/engine-api/Cargo.toml @@ -39,6 +39,7 @@ auto_impl.workspace = true jsonrpsee = { workspace = true, features = ["server", "macros"] } parking_lot.workspace = true thiserror.workspace = true +tokio = { workspace = true, features = ["sync"] } tracing.workspace = true [dev-dependencies] diff --git a/crates/engine-api/src/builder.rs b/crates/engine-api/src/builder.rs index 252a9b2c..979ddd09 100644 --- a/crates/engine-api/src/builder.rs +++ b/crates/engine-api/src/builder.rs @@ -50,6 +50,14 @@ pub struct RealMorphL2EngineApi { /// Tracks L1-derived finalized block tags for FCU updates. block_tag_tracker: Arc, + /// Serializes payload builds to prevent concurrent deterministic `PayloadId` + /// collisions in reth's `PayloadBuilderService`. + build_lock: tokio::sync::Mutex<()>, + + /// Serializes forkchoice and block-tag updates across `import_l2_block_via_engine` + /// and `set_block_tags` so tag updates cannot race concurrent reorgs. + fcu_lock: tokio::sync::Mutex<()>, + /// Prometheus metrics for custom Morph L2 Engine API endpoints and chain head health. metrics: MorphEngineApiMetrics, } @@ -138,13 +146,18 @@ fn payload_timestamp( } // Derivation rebuilds a block already committed to L1 and must reproduce it exactly. Some(timestamp) => timestamp, - None => std::cmp::max( - parent_timestamp + 1, - std::time::SystemTime::now() + None => { + let earliest = if emerald_active { + parent_timestamp + } else { + parent_timestamp + 1 + }; + let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap_or_default() - .as_secs(), - ), + .as_secs(); + now.max(earliest) + } } } @@ -163,6 +176,8 @@ impl RealMorphL2EngineApi { chain_spec, engine_handle, block_tag_tracker, + build_lock: tokio::sync::Mutex::new(()), + fcu_lock: tokio::sync::Mutex::new(()), metrics: MorphEngineApiMetrics::default(), } } @@ -353,6 +368,23 @@ where } }; + // 2b. Validate `next_l1_message_index` before calling `new_payload`: the field is not + // covered by the block hash, so an `AlreadySeen` hit in the engine tree would + // otherwise return `Valid` without re-running `validate_payload`. + if let Err(err) = self.validate_next_l1_message_index(payload.block.as_ref()) { + tracing::warn!( + target: "morph::engine", + block_hash = %data.hash, + error = %err, + "invalid next_l1_message_index during validate_l2_block" + ); + self.metrics.validate_l2_block_failures_total.increment(1); + self.metrics + .validate_l2_block_duration_seconds + .record(validate_started.elapsed()); + return Ok(GenericResponse { success: false }); + } + let status = match self.engine_handle.new_payload(payload).await { Ok(status) => status, Err(err) => { @@ -624,42 +656,93 @@ where safe_block_hash: B256, finalized_block_hash: B256, ) -> EngineApiResult<()> { - // Match geth's SetBlockTags: look up the header by hash and call set_finalized / - // set_safe on the provider directly, skipping zero hashes. This avoids a full - // FCU round-trip through the async engine pipeline for what is purely a tag - // update, and correctly skips the update when the caller passes B256::ZERO. - // - // Order matters: set safe FIRST, then finalized. The Ethereum invariant - // `finalized.number <= safe.number` must hold at every observable point - // for an RPC reader. Updating finalized first and then safe leaves a - // window between the two writes where `eth_getBlockByNumber("finalized")` - // returns the new value but `eth_getBlockByNumber("safe")` returns the - // stale older value — a transient `finalized > safe` violation. Updating - // safe first keeps the invariant satisfied throughout (finalized stays - // at its older, smaller value while safe advances). + if safe_block_hash == B256::ZERO && finalized_block_hash == B256::ZERO { + return Ok(()); + } + + // Serialize tag updates against forkchoice imports so a concurrent reorg cannot + // invalidate a resolved hash or advance the canonical head mid-call. + let _fcu_guard = self.fcu_lock.lock().await; + let safe = if safe_block_hash != B256::ZERO { - Some(self.resolve_block_tag(safe_block_hash, "safe")?) + Some(self.resolve_canonical_block_tag(safe_block_hash, "safe")?) } else { None }; let finalized = if finalized_block_hash != B256::ZERO { - Some(self.resolve_block_tag(finalized_block_hash, "finalized")?) + Some(self.resolve_canonical_block_tag(finalized_block_hash, "finalized")?) } else { None }; - if safe.is_none() && finalized.is_none() { - return Ok(()); - } let canonical_head = self.current_head()?; + let existing_safe = self + .provider + .safe_block_number() + .map_err(|e| MorphEngineApiError::Database(e.to_string()))?; + let existing_finalized = self + .provider + .finalized_block_number() + .map_err(|e| MorphEngineApiError::Database(e.to_string()))?; + validate_resolved_block_tags( safe.as_ref().map(|header| header.number()), finalized.as_ref().map(|header| header.number()), + existing_safe, + existing_finalized, canonical_head.number, )?; - if let Some(sealed) = safe { - self.provider.set_safe(sealed); + // Route tag updates through reth's engine tree FCU without pre-mutating + // `CanonicalInMemoryState`. In reth's `update_finalized_block` / `update_safe_block`, + // `B256::ZERO` is a no-op (preserving the other tag), while a non-zero change schedules + // MDBX persistence (`save_safe_block_number` / `save_finalized_block_number`), updates + // `CanonicalInMemoryState`, and updates finalized/safe height metrics. + // + // When both tags are supplied, apply `safe` before `finalized` so concurrent RPC + // readers never observe a transient `finalized > safe` window. + if safe.is_some() && finalized.is_some() { + let safe_fcu = alloy_rpc_types_engine::ForkchoiceState { + head_block_hash: canonical_head.hash, + safe_block_hash, + finalized_block_hash: B256::ZERO, + }; + self.provider.on_forkchoice_update_received(&safe_fcu); + let safe_res = self + .engine_handle + .fork_choice_updated(safe_fcu, None) + .await + .map_err(|e| MorphEngineApiError::ExecutionFailed(e.to_string()))?; + ensure_payload_status_valid(&safe_res.payload_status, "forkchoiceUpdated")?; + + let finalized_fcu = alloy_rpc_types_engine::ForkchoiceState { + head_block_hash: canonical_head.hash, + safe_block_hash: B256::ZERO, + finalized_block_hash, + }; + self.provider.on_forkchoice_update_received(&finalized_fcu); + let finalized_res = self + .engine_handle + .fork_choice_updated(finalized_fcu, None) + .await + .map_err(|e| MorphEngineApiError::ExecutionFailed(e.to_string()))?; + ensure_payload_status_valid(&finalized_res.payload_status, "forkchoiceUpdated")?; + } else { + let forkchoice = alloy_rpc_types_engine::ForkchoiceState { + head_block_hash: canonical_head.hash, + safe_block_hash, + finalized_block_hash, + }; + self.provider.on_forkchoice_update_received(&forkchoice); + let fcu_res = self + .engine_handle + .fork_choice_updated(forkchoice, None) + .await + .map_err(|e| MorphEngineApiError::ExecutionFailed(e.to_string()))?; + ensure_payload_status_valid(&fcu_res.payload_status, "forkchoiceUpdated")?; + } + + if safe.is_some() { tracing::info!( target: "morph::engine", hash = %safe_block_hash, @@ -667,8 +750,11 @@ where ); } - if let Some(sealed) = finalized { - self.provider.set_finalized(sealed); + if finalized.is_some() { + // Cache the L1-derived finalized hash only after FCU succeeds; when + // `finalized_block_hash == B256::ZERO`, leave any previously cached hash intact. + self.block_tag_tracker + .record_finalized_hash(Some(finalized_block_hash)); tracing::info!( target: "morph::engine", hash = %finalized_block_hash, @@ -676,38 +762,41 @@ where ); } - // Cache the L1-derived finalized hash so subsequent FCU calls can forward it. - // Safe is not cached: FCU safe is supplied by each import caller, and the - // RPC-visible safe tag can also be advanced by set_block_tags. - self.block_tag_tracker - .record_finalized_hash(if finalized_block_hash != B256::ZERO { - Some(finalized_block_hash) - } else { - None - }); - Ok(()) } } impl RealMorphL2EngineApi { - /// Looks up a sealed header by hash. + /// Looks up a sealed header by hash and verifies that it belongs to the current + /// canonical chain. /// - /// Used by `set_block_tags` to validate both tag updates before mutating provider state. - fn resolve_block_tag( + /// Used by `set_block_tags` to validate both tag updates before mutating state. + fn resolve_canonical_block_tag( &self, hash: B256, tag_name: &str, ) -> EngineApiResult> where - Provider: HeaderProvider
, + Provider: HeaderProvider
+ BlockNumReader, { - self.provider + let header = self + .provider .sealed_header_by_hash(hash) .map_err(|e| MorphEngineApiError::Internal(e.to_string()))? .ok_or_else(|| { MorphEngineApiError::Internal(format!("{tag_name} block {hash} not found")) - }) + })?; + let canonical_hash = self + .provider + .block_hash(header.number()) + .map_err(|e| MorphEngineApiError::Database(e.to_string()))?; + if canonical_hash != Some(header.hash()) { + return Err(MorphEngineApiError::ValidationFailed(format!( + "{tag_name} block {hash} (number {}) is not canonical", + header.number() + ))); + } + Ok(header) } async fn build_l2_payload( @@ -727,6 +816,10 @@ impl RealMorphL2EngineApi { + Sync + 'static, { + // Serialize builds so overlapping requests with identical `(parent, timestamp, txs)` + // never collide on the deterministic `PayloadId` in reth's `PayloadBuilderService`. + let _build_guard = self.build_lock.lock().await; + tracing::debug!( target: "morph::engine", block_number = params.number, @@ -850,6 +943,75 @@ impl RealMorphL2EngineApi { }) } + /// Validates the unhashed `next_l1_message_index` header field against the parent header + /// and the block's leading L1 messages before calling `engine_handle.new_payload`. + /// + /// Because `next_l1_msg_index` is not part of the block hash, reth's `AlreadySeen` + /// short-circuit would otherwise return `Valid` for a tampered `next_l1_message_index` + /// whenever the block hash is already in `tree_state` (e.g., pre-inserted by + /// `assembleL2Block`) or in the DB. Checking it here rejects the tampered request + /// without invoking `new_payload` (so `invalid_headers` is never poisoned). + fn validate_next_l1_message_index(&self, block: &SealedBlock) -> EngineApiResult<()> + where + Provider: HeaderProvider
, + { + let Some(parent) = self + .provider + .sealed_header_by_hash(block.parent_hash()) + .map_err(|e| MorphEngineApiError::Database(e.to_string()))? + else { + return Ok(()); + }; + + let mut expected = parent.next_l1_msg_index; + let mut first_l1_msg = true; + for tx in block.body().transactions() { + if !tx.is_l1_msg() { + break; + } + let Some(queue_index) = tx.queue_index() else { + // Malformed L1 message is committed by the block hash; let the engine + // validator reject and cache it. + return Ok(()); + }; + if first_l1_msg { + first_l1_msg = false; + if queue_index < parent.next_l1_msg_index { + // Cross-block L1 replay is committed by the block hash; let the engine + // validator reject and cache it with `L1MessagesNotInOrder`. + return Ok(()); + } + } + expected = match queue_index.checked_add(1) { + Some(next) => next, + None => { + return Err(MorphEngineApiError::ValidationFailed(format!( + "invalid block.NextL1MsgIndex: expected {}, got {}", + u64::MAX, + block.header().next_l1_msg_index + ))); + } + }; + } + + let actual = block.header().next_l1_msg_index; + let is_jade = self + .chain_spec + .is_jade_active_at_timestamp(block.header().timestamp()); + let invalid = if is_jade { + actual != expected + } else { + actual < expected + }; + if invalid { + return Err(MorphEngineApiError::ValidationFailed(format!( + "invalid block.NextL1MsgIndex: expected {expected}, got {actual}" + ))); + } + + Ok(()) + } + async fn import_l2_block_via_engine( &self, data: ExecutableL2Data, @@ -861,6 +1023,7 @@ impl RealMorphL2EngineApi { + CanonChainTracker
, { let (payload, header) = self.execution_payload_from_executable_data(&data)?; + self.validate_next_l1_message_index(payload.block.as_ref())?; let payload_status = self .engine_handle @@ -869,6 +1032,10 @@ impl RealMorphL2EngineApi { .map_err(|e| MorphEngineApiError::ExecutionFailed(e.to_string()))?; ensure_payload_status_valid(&payload_status, "newPayload")?; + // Serialize FCU against `set_block_tags` so tag updates see a stable canonical head + // and this FCU observes any newly recorded L1 finalized hash. + let _fcu_guard = self.fcu_lock.lock().await; + // FCU safe/finalized must be canonical ancestors. Unsafe imports pass safe zero; // new_safe_l2_block passes the imported block itself, never a cached old safe. // Forward only the L1-derived finalized tag; zero is a no-op when it is absent, @@ -1036,6 +1203,8 @@ impl RealMorphL2EngineApi { fn validate_resolved_block_tags( safe_number: Option, finalized_number: Option, + existing_safe_number: Option, + existing_finalized_number: Option, canonical_head_number: u64, ) -> EngineApiResult<()> { if let Some(safe_number) = safe_number @@ -1054,7 +1223,10 @@ fn validate_resolved_block_tags( ))); } - if let (Some(safe_number), Some(finalized_number)) = (safe_number, finalized_number) + let effective_safe = safe_number.or(existing_safe_number); + let effective_finalized = finalized_number.or(existing_finalized_number); + + if let (Some(safe_number), Some(finalized_number)) = (effective_safe, effective_finalized) && finalized_number > safe_number { return Err(MorphEngineApiError::ValidationFailed(format!( @@ -1356,7 +1528,7 @@ mod tests { #[test] fn test_validate_resolved_block_tags_rejects_finalized_after_safe() { - let err = validate_resolved_block_tags(Some(10), Some(11), 11).unwrap_err(); + let err = validate_resolved_block_tags(Some(10), Some(11), None, None, 11).unwrap_err(); match err { MorphEngineApiError::ValidationFailed(msg) => { assert!(msg.contains("finalized block number 11 exceeds safe block number 10")); @@ -1367,7 +1539,7 @@ mod tests { #[test] fn test_validate_resolved_block_tags_rejects_safe_after_canonical_head() { - let err = validate_resolved_block_tags(Some(12), Some(11), 11).unwrap_err(); + let err = validate_resolved_block_tags(Some(12), Some(11), None, None, 11).unwrap_err(); match err { MorphEngineApiError::ValidationFailed(msg) => { assert!(msg.contains("safe block number 12 exceeds canonical head number 11")); @@ -1376,6 +1548,32 @@ mod tests { } } + #[test] + fn test_validate_resolved_block_tags_enforces_partial_update_ordering() { + // Updating finalized only past existing safe must fail. + let err = validate_resolved_block_tags(None, Some(11), Some(10), Some(8), 12).unwrap_err(); + match err { + MorphEngineApiError::ValidationFailed(msg) => { + assert!(msg.contains("finalized block number 11 exceeds safe block number 10")); + } + other => panic!("unexpected error: {other}"), + } + + // Updating safe only below existing finalized must fail. + let err = validate_resolved_block_tags(Some(7), None, Some(10), Some(8), 12).unwrap_err(); + match err { + MorphEngineApiError::ValidationFailed(msg) => { + assert!(msg.contains("finalized block number 8 exceeds safe block number 7")); + } + other => panic!("unexpected error: {other}"), + } + + // Partial updates preserving effective_finalized <= effective_safe <= head succeed. + assert!(validate_resolved_block_tags(None, Some(10), Some(10), Some(8), 12).is_ok()); + assert!(validate_resolved_block_tags(Some(12), None, Some(10), Some(8), 12).is_ok()); + assert!(validate_resolved_block_tags(None, Some(5), None, None, 12).is_ok()); + } + // ========================================================================= // apply_executable_data_overrides edge cases // ========================================================================= @@ -1486,8 +1684,14 @@ mod tests { fn test_payload_timestamp_defaults_after_parent() { // Ahead of the wall clock, so the parent decides the default. let parent_timestamp = 20_000_000_000; + // From Emerald on, default timestamp may share parent_timestamp. assert_eq!( payload_timestamp(None, parent_timestamp, true, TxPoolPolicy::Include), + parent_timestamp + ); + // Before Emerald, default timestamp must be strictly after parent_timestamp. + assert_eq!( + payload_timestamp(None, parent_timestamp, false, TxPoolPolicy::Include), parent_timestamp + 1 ); } diff --git a/crates/evm/src/lib.rs b/crates/evm/src/lib.rs index 6acd31f5..3e008f72 100644 --- a/crates/evm/src/lib.rs +++ b/crates/evm/src/lib.rs @@ -89,7 +89,7 @@ use crate::block::DefaultMorphReceiptBuilder; pub use crate::block::{MorphBlockExecutor, MorphTxResult, morph_invalid_tx_error}; use morph_chainspec::MorphChainSpec; -pub use morph_revm::{MorphBlockEnv, MorphEvmEnv, MorphEvmTypes}; +pub use morph_revm::{MorphBlockEnv, MorphEvmEnv, MorphEvmTypes, MorphInvalidTransaction}; /// Morph EVM configuration and block executor factory. /// diff --git a/crates/node/Cargo.toml b/crates/node/Cargo.toml index 5ed56333..506c60fb 100644 --- a/crates/node/Cargo.toml +++ b/crates/node/Cargo.toml @@ -28,6 +28,7 @@ reth-db.workspace = true reth-chain-state.workspace = true reth-node-core.workspace = true reth-chainspec.workspace = true +reth-consensus.workspace = true reth-engine-local.workspace = true reth-engine-tree.workspace = true reth-errors.workspace = true @@ -62,7 +63,6 @@ alloy-rpc-types-eth.workspace = true # Async eyre.workspace = true clap.workspace = true -dashmap.workspace = true futures.workspace = true parking_lot.workspace = true tokio = { workspace = true, features = ["sync", "rt"] } diff --git a/crates/node/src/add_ons.rs b/crates/node/src/add_ons.rs index b3446bfe..5b10637f 100644 --- a/crates/node/src/add_ons.rs +++ b/crates/node/src/add_ons.rs @@ -267,13 +267,18 @@ where .merge_if_module_configured(RethRpcModule::Eth, eth_config_handler.into_rpc()) .map_err(|e| eyre::eyre!("Failed to register eth_config handler: {}", e))?; - // The namespace remains registered while the index catches up; handlers return - // a structured unavailable/behind error until the durable cursor is live. - tracing::debug!(target: "morph::node", "Registering morph_ RPC namespace"); + // Expose `morph_` only on transports where `morph` (or `all`) is configured, + // matching morph-geth's explicit `morph` module namespace rather than exposing it + // by default. While enabled, handlers return a structured unavailable/behind error + // until the durable cursor is live. + tracing::debug!(target: "morph::node", "Registering morph_ RPC namespace on configured transports"); modules - .merge_configured(reference_rpc_handler.into_rpc()) + .merge_if_module_configured( + RethRpcModule::Other("morph".into()), + reference_rpc_handler.into_rpc(), + ) .map_err(|e| eyre::eyre!("Failed to register morph_ RPC: {}", e))?; - tracing::info!(target: "morph::node", "morph_ RPC namespace registered"); + tracing::info!(target: "morph::node", "morph_ RPC namespace registered for configured transports"); // Create and register Morph L2 Engine API tracing::debug!(target: "morph::node", "Registering Morph L2 Engine API"); diff --git a/crates/node/src/test_utils.rs b/crates/node/src/test_utils.rs index 34d97f2a..6c83086c 100644 --- a/crates/node/src/test_utils.rs +++ b/crates/node/src/test_utils.rs @@ -221,6 +221,9 @@ pub struct TestNodeBuilder { desired_gas_limit: Option, debug_tip: Option, trusted_peer: Option, + http_api: Option, + minimal_protocol_basefee: u64, + startup_sync_state_idle: Option, morph_args: Option, } @@ -248,6 +251,9 @@ impl TestNodeBuilder { desired_gas_limit: None, debug_tip: None, trusted_peer: None, + http_api: None, + minimal_protocol_basefee: morph_chainspec::MORPH_BASE_FEE, + startup_sync_state_idle: None, morph_args: None, } } @@ -316,6 +322,62 @@ impl TestNodeBuilder { self } + /// Override an account's storage slot in the test genesis. + pub fn with_account_storage(mut self, address: Address, slot: U256, value: U256) -> Self { + let alloc = self + .genesis_json + .get_mut("alloc") + .and_then(serde_json::Value::as_object_mut) + .expect("test genesis alloc must be an object"); + let address_lower = address.to_string().to_ascii_lowercase(); + let key = alloc + .keys() + .find(|existing| existing.eq_ignore_ascii_case(&address_lower)) + .cloned() + .unwrap_or(address_lower); + let entry = alloc + .entry(key) + .or_insert_with(|| serde_json::json!({ "balance": "0x0" })); + let entry = entry + .as_object_mut() + .expect("test genesis account entry must be an object"); + let storage = entry + .entry("storage") + .or_insert_with(|| serde_json::json!({})); + let storage = storage + .as_object_mut() + .expect("test genesis account storage must be an object"); + storage.insert( + format!("{slot:#066x}"), + serde_json::json!(format!("{value:#066x}")), + ); + self + } + + /// Override the configured HTTP RPC modules (`--http.api`). + pub fn with_http_api(mut self, http_api: RpcModuleSelection) -> Self { + self.http_api = Some(http_api); + self + } + + /// Override the txpool minimal protocol base fee, as `--txpool.minimal-protocol-fee` would. + /// + /// Defaults to [`morph_chainspec::MORPH_BASE_FEE`] to match the `morph-reth` CLI. + pub fn with_minimal_protocol_basefee(mut self, fee: u64) -> Self { + self.minimal_protocol_basefee = fee; + self + } + + /// Override `--debug.startup-sync-state-idle` on the test node. + /// + /// Upstream `reth-e2e-test-utils` defaults this to `true` in tests, whereas + /// production `morph-reth` defaults it to `false`. Set to `false` to exercise + /// the production start-up sync state. + pub fn with_startup_sync_state_idle(mut self, idle: bool) -> Self { + self.startup_sync_state_idle = Some(idle); + self + } + /// Override the maximum pool-transaction payload bytes included in a block. /// /// Restricted to single-node setups. @@ -345,8 +407,14 @@ impl TestNodeBuilder { self.num_nodes )); } - let (node, wallet) = - launch_test_node_with_args(Arc::new(chain_spec), self.is_dev, args).await?; + let (node, wallet) = launch_test_node_with_args( + Arc::new(chain_spec), + self.is_dev, + self.minimal_protocol_basefee, + args, + self.http_api, + ) + .await?; return Ok((vec![node], wallet)); } @@ -356,6 +424,9 @@ impl TestNodeBuilder { let desired_gas_limit = self.desired_gas_limit; let debug_tip = self.debug_tip; let trusted_peer = self.trusted_peer; + let http_api = self.http_api; + let minimal_protocol_basefee = self.minimal_protocol_basefee; + let startup_sync_state_idle = self.startup_sync_state_idle; reth_e2e_test_utils::E2ETestSetupBuilder::::new_with_attributes_generator( self.num_nodes, Arc::new(chain_spec), @@ -364,9 +435,16 @@ impl TestNodeBuilder { .with_node_config_modifier(move |mut config| { config.builder.gas_limit = desired_gas_limit; config.debug.tip = debug_tip; + config.txpool.minimal_protocol_basefee = minimal_protocol_basefee; + if let Some(idle) = startup_sync_state_idle { + config.debug.startup_sync_state_idle = idle; + } if let Some(ref enode) = trusted_peer { config.network.trusted_peers = vec![enode.parse().expect("valid trusted enode")]; } + if let Some(ref http_api) = http_api { + config.rpc.http_api = Some(http_api.clone()); + } config.set_dev(is_dev) }) .build() @@ -384,7 +462,9 @@ impl TestNodeBuilder { async fn launch_test_node_with_args( chain_spec: Arc, is_dev: bool, + minimal_protocol_basefee: u64, args: MorphArgs, + http_api: Option, ) -> eyre::Result<(MorphTestNode, Wallet)> { use reth_chainspec::EthChainSpec; @@ -396,16 +476,17 @@ async fn launch_test_node_with_args( }, ..NetworkArgs::default() }; - let node_config = NodeConfig::new(chain_spec.clone()) + let mut node_config = NodeConfig::new(chain_spec.clone()) .with_network(network) .with_unused_ports() .with_rpc( RpcServerArgs::default() .with_unused_ports() .with_http() - .with_http_api(RpcModuleSelection::All), + .with_http_api(http_api.unwrap_or(RpcModuleSelection::All)), ) .set_dev(is_dev); + node_config.txpool.minimal_protocol_basefee = minimal_protocol_basefee; let node = MorphNode::new(args); let tree_config = TreeConfig::default().with_cross_block_cache_size(1024 * 1024); let span = span!(Level::INFO, "node", idx = 0); diff --git a/crates/node/src/validator.rs b/crates/node/src/validator.rs index b903e675..2665cfcb 100644 --- a/crates/node/src/validator.rs +++ b/crates/node/src/validator.rs @@ -3,7 +3,6 @@ use crate::MorphNode; use alloy_consensus::BlockHeader; use alloy_primitives::{B256, keccak256}; -use dashmap::DashMap; use morph_chainspec::{ L2_MESSAGE_QUEUE_ADDRESS, L2_MESSAGE_QUEUE_WITHDRAW_TRIE_ROOT_SLOT, MorphChainSpec, MorphHardforks, @@ -14,6 +13,7 @@ use morph_primitives::{MorphHeader, MorphPrimitives, MorphTxEnvelope}; use parking_lot::Mutex; use reth_chain_state::ExecutedBlock; use reth_chainspec::EthChainSpec; +use reth_consensus::{Consensus, FullConsensus, HeaderValidator}; use reth_engine_tree::tree::payload_validator::TreeCtx; use reth_engine_tree::tree::{ BasicEngineValidator, CacheWaitDurations, EngineApiTreeState, EngineValidator, @@ -25,7 +25,7 @@ use reth_engine_tree::tree::{ StateRootJobOutcome, StateRootStrategy, }, }; -use reth_errors::{ConsensusError, ProviderResult}; +use reth_errors::{ConsensusError, ProviderError, ProviderResult}; use reth_evm::{ConfigureEvm, EvmEnv as _}; use reth_node_api::{ AddOnsContext, FullNodeComponents, InvalidPayloadAttributesError, NewPayloadError, NodeTypes, @@ -48,7 +48,10 @@ use reth_tracing::tracing; use reth_transaction_pool::{ BestTransactions, BestTransactionsAttributes, PoolTransaction, TransactionPool, }; -use std::{collections::VecDeque, sync::Arc}; +use std::{ + collections::{HashMap, VecDeque}, + sync::Arc, +}; /// Builder for Morph engine validator (payload validation). /// @@ -127,6 +130,8 @@ where let post_execution_validator = validator.clone(); let provider = ctx.node.provider().clone(); + let consensus: Arc> = + Arc::new(ctx.node.consensus().clone()); let state_root_strategy: Arc< dyn StateRootStrategy, > = Arc::new(MorphStateRootStrategy::new( @@ -138,7 +143,7 @@ where let txpool_prewarming = tree_config.txpool_prewarming(); let mut validator = BasicEngineValidator::new( provider.clone(), - Arc::new(ctx.node.consensus().clone()), + consensus.clone(), ctx.node.evm_config().clone(), validator, tree_config, @@ -157,6 +162,7 @@ where validator, provider, chain_spec, + consensus, post_execution_validator, )) } @@ -240,6 +246,7 @@ where inner: BasicEngineValidator, provider: P, chain_spec: Arc, + consensus: Arc>, post_execution_validator: MorphEngineValidator, } @@ -251,12 +258,14 @@ where inner: BasicEngineValidator, provider: P, chain_spec: Arc, + consensus: Arc>, post_execution_validator: MorphEngineValidator, ) -> Self { Self { inner, provider, chain_spec, + consensus, post_execution_validator, } } @@ -267,30 +276,25 @@ where Evm: ConfigureEvm, P: BlockReader
, { - fn validate_next_l1_msg_index( + /// Enforces parent-aware L1 message queue invariants: + /// + /// 1. Across **all** hardforks (both pre-Jade and post-Jade), if the block contains + /// leading L1 messages, the first message's `queue_index` must be `>= parent.next_l1_msg_index`. + /// Violations are cross-block L1 message replays and return cacheable + /// [`MorphConsensusError::L1MessagesNotInOrder`] (since transactions are committed by the + /// block hash). Forward skips (`first_queue_index > parent.next_l1_msg_index`) remain + /// permitted. + /// 2. From Jade onward, `header.next_l1_msg_index` must match the exact derived index + /// (`parent.next_l1_msg_index` when no L1 messages are present, or `last_queue_index + 1` + /// otherwise). Mismatches return transient [`MorphConsensusError::InvalidNextL1MessageIndex`] + /// so an unhashed header field cannot poison `invalid_headers`. + fn validate_l1_msg_index_against_parent( &self, block: &SealedBlock, - ctx: &TreeCtx<'_, MorphPrimitives>, - ) -> Result<(), InsertBlockErrorKind> { - if !self - .chain_spec - .is_jade_active_at_timestamp(block.header().timestamp()) - { - return Ok(()); - } - - let parent_hash = block.parent_hash(); - let parent = match ctx.state().tree_state().sealed_header_by_hash(&parent_hash) { - Some(parent) => Some(parent), - None => self.provider.sealed_header_by_hash(parent_hash)?, - }; - let Some(parent) = parent else { - // The upstream validator reports the missing parent with the - // canonical provider error before executing the block. - return Ok(()); - }; - + parent: &MorphHeader, + ) -> Result<(), ConsensusError> { let mut expected = parent.next_l1_msg_index; + let mut first_l1_msg = true; for tx in block.body().transactions() { if !tx.is_l1_msg() { break; @@ -298,6 +302,17 @@ where let queue_index = tx.queue_index().ok_or_else(|| { ConsensusError::msg("L1 message transaction is missing queue index") })?; + if first_l1_msg { + first_l1_msg = false; + if queue_index < parent.next_l1_msg_index { + return Err(ConsensusError::other( + MorphConsensusError::L1MessagesNotInOrder { + expected: parent.next_l1_msg_index, + actual: queue_index, + }, + )); + } + } expected = queue_index.checked_add(1).ok_or_else(|| { ConsensusError::other(MorphConsensusError::InvalidNextL1MessageIndex { expected: u64::MAX, @@ -306,22 +321,45 @@ where })?; } + if !self + .chain_spec + .is_jade_active_at_timestamp(block.header().timestamp()) + { + return Ok(()); + } + // Typed so that `MorphConsensus::is_transient_error` keeps this rejection out of // reth's invalid-header cache: the field is not covered by the block hash, so // the cache entry would also match the honest block. let actual = block.header().next_l1_msg_index; if actual != expected { - return Err( - ConsensusError::other(MorphConsensusError::InvalidNextL1MessageIndex { - expected, - actual, - }) - .into(), - ); + return Err(ConsensusError::other( + MorphConsensusError::InvalidNextL1MessageIndex { expected, actual }, + )); } Ok(()) } + fn validate_next_l1_msg_index( + &self, + block: &SealedBlock, + ctx: &TreeCtx<'_, MorphPrimitives>, + ) -> Result<(), InsertBlockErrorKind> { + let parent_hash = block.parent_hash(); + let parent = match ctx.state().tree_state().sealed_header_by_hash(&parent_hash) { + Some(parent) => Some(parent), + None => self.provider.sealed_header_by_hash(parent_hash)?, + }; + let Some(parent) = parent else { + // The upstream validator reports the missing parent with the + // canonical provider error before executing the block. + return Ok(()); + }; + + self.validate_l1_msg_index_against_parent(block, parent.header()) + .map_err(Into::into) + } + fn validate_next_l1_msg_index_for_block( &self, block: &SealedBlock, @@ -332,6 +370,30 @@ where .map_err(|kind| InsertBlockError::new(block.clone(), kind).into()) } + /// Runs lightweight structural consensus validation before admitting a locally built + /// block via `InsertExecutedBlock`, ensuring pre-inserted blocks obey the same + /// header, parent, L1 queue, MorphTx, and DA payload rules as imported blocks. + fn validate_pre_inserted_block( + &self, + block: &RecoveredBlock, + ) -> ProviderResult<()> { + let sealed_header = block.sealed_header(); + self.consensus + .validate_header(sealed_header) + .map_err(ProviderError::other)?; + if let Some(parent) = self.provider.sealed_header_by_hash(block.parent_hash())? { + self.consensus + .validate_header_against_parent(sealed_header, &parent) + .map_err(ProviderError::other)?; + self.validate_l1_msg_index_against_parent(block.sealed_block(), parent.header()) + .map_err(ProviderError::other)?; + } + self.consensus + .validate_block_pre_execution(block.sealed_block()) + .map_err(ProviderError::other)?; + Ok(()) + } + fn validate_withdraw_trie_root( &self, output: reth_engine_tree::tree::ValidationOutput, @@ -352,6 +414,26 @@ where Ok(output) } + + fn validate_withdraw_trie_root_direct( + expected_withdraw_trie_root: Option, + output: reth_engine_tree::tree::ValidationOutput, + ) -> reth_engine_tree::tree::ValidationOutcome { + let expectation = MorphEngineValidator::expectation_from_root(expected_withdraw_trie_root); + if let Err(err) = + MorphEngineValidator::validate_withdraw_trie_root_expectation(expectation, || { + output.executed_block.hashed_state() + }) + { + return Err(InsertBlockError::consensus_error( + err, + output.executed_block.sealed_block().clone(), + ) + .into()); + } + + Ok(output) + } } impl EngineValidator @@ -373,29 +455,48 @@ where fn convert_payload_to_block( &self, - payload: MorphExecutionData, + mut payload: MorphExecutionData, ) -> Result, NewPayloadError> { + let block_hash = payload.block.hash(); + // Avoid leaking expectations into the cache when the block is already known + // or no non-zero cross-check root was supplied. + let is_zero_root = payload + .expected_withdraw_trie_root + .is_some_and(|root| root == B256::ZERO); + if is_zero_root { + self.post_execution_validator + .take_withdraw_trie_root_expectation(block_hash); + payload.expected_withdraw_trie_root = None; + } else if payload.expected_withdraw_trie_root.is_some() + && self + .provider + .sealed_header_by_hash(block_hash) + .ok() + .flatten() + .is_some() + { + payload.expected_withdraw_trie_root = None; + } self.inner.convert_payload_to_block(payload) } fn validate_payload( &mut self, - payload: MorphExecutionData, + mut payload: MorphExecutionData, ctx: TreeCtx<'_, MorphPrimitives>, ) -> reth_engine_tree::tree::ValidationOutcome { let block_hash = payload.block.hash(); - // `convert_payload_to_block` may already have registered a withdraw-root - // expectation for this hash. Clear it on every early reject path so a - // later re-import of the same hash does not observe a stale entry. - let l1_validation = self.validate_next_l1_msg_index_for_block(payload.block.as_ref(), &ctx); + // Extract the expectation directly onto the stack so the live `validate_payload` + // path never inserts into (or can leak from) `expected_withdraw_trie_roots`. + // Also clear any residual entry left by an earlier buffered conversion. + let expected_withdraw_trie_root = payload.expected_withdraw_trie_root.take(); self.post_execution_validator - .clear_withdraw_trie_root_expectation_on_error(block_hash, l1_validation)?; + .take_withdraw_trie_root_expectation(block_hash); - let validation = self.inner.validate_payload(payload, ctx); - let output = self - .post_execution_validator - .clear_withdraw_trie_root_expectation_on_error(block_hash, validation)?; - self.validate_withdraw_trie_root(output) + self.validate_next_l1_msg_index_for_block(payload.block.as_ref(), &ctx)?; + + let output = self.inner.validate_payload(payload, ctx)?; + Self::validate_withdraw_trie_root_direct(expected_withdraw_trie_root, output) } fn validate_block( @@ -419,6 +520,7 @@ where &self, block: BuiltPayloadExecutedBlock, ) -> ProviderResult> { + self.validate_pre_inserted_block(block.recovered_block.as_ref())?; self.inner.on_inserted_executed_block(block) } @@ -561,6 +663,12 @@ where } } +#[derive(Debug, Default)] +struct WithdrawTrieRootCache { + entries: HashMap, + order: VecDeque, +} + /// Morph engine validator for payload validation. /// /// This validator is used by the engine API to validate incoming payloads. @@ -568,8 +676,7 @@ where #[derive(Debug, Default, Clone)] #[non_exhaustive] pub struct MorphEngineValidator { - expected_withdraw_trie_roots: Arc>, - expected_withdraw_trie_root_order: Arc>>, + expected_withdraw_trie_roots: Arc>, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -586,25 +693,31 @@ impl MorphEngineValidator { Self::default() } + fn expectation_from_root(root: Option) -> WithdrawTrieRootExpectation { + match root { + Some(root) if !root.is_zero() => WithdrawTrieRootExpectation::Verify(root), + // Match morph-geth: zero means the caller did not provide this optional + // CL/EL cross-check value, not that the expected root is actually zero. + _ => WithdrawTrieRootExpectation::SkipValidation, + } + } + fn record_withdraw_trie_root_expectation( &self, block_hash: B256, expectation: WithdrawTrieRootExpectation, ) { - let is_new_entry = self - .expected_withdraw_trie_roots - .insert(block_hash, expectation) - .is_none(); + let mut cache = self.expected_withdraw_trie_roots.lock(); + let is_new_entry = cache.entries.insert(block_hash, expectation).is_none(); if is_new_entry { - let mut order = self.expected_withdraw_trie_root_order.lock(); - order.push_back(block_hash); + cache.order.push_back(block_hash); - while self.expected_withdraw_trie_roots.len() > Self::MAX_EXPECTED_WITHDRAW_TRIE_ROOTS { - let Some(evicted_hash) = order.pop_front() else { + while cache.entries.len() > Self::MAX_EXPECTED_WITHDRAW_TRIE_ROOTS { + let Some(evicted_hash) = cache.order.pop_front() else { break; }; - self.expected_withdraw_trie_roots.remove(&evicted_hash); + cache.entries.remove(&evicted_hash); } } } @@ -613,15 +726,11 @@ impl MorphEngineValidator { &self, block_hash: B256, ) -> Option { - let removed = self - .expected_withdraw_trie_roots - .remove(&block_hash) - .map(|(_, expected)| expected); + let mut cache = self.expected_withdraw_trie_roots.lock(); + let removed = cache.entries.remove(&block_hash); if removed.is_some() { - self.expected_withdraw_trie_root_order - .lock() - .retain(|hash| *hash != block_hash); + cache.order.retain(|hash| *hash != block_hash); } removed @@ -656,19 +765,10 @@ impl MorphEngineValidator { }) } - fn validate_withdraw_trie_root_update( - &self, - block_hash: B256, + fn validate_withdraw_trie_root_expectation( + expectation: WithdrawTrieRootExpectation, state_updates: impl FnOnce() -> Arc, ) -> Result<(), ConsensusError> { - let Some(expectation) = self.take_withdraw_trie_root_expectation(block_hash) else { - tracing::debug!( - target: "morph::engine_validator", - %block_hash, - "no withdraw trie root expectation registered; skipping CL cross-check" - ); - return Ok(()); - }; let WithdrawTrieRootExpectation::Verify(expected) = expectation else { return Ok(()); }; @@ -688,6 +788,22 @@ impl MorphEngineValidator { } Ok(()) } + + fn validate_withdraw_trie_root_update( + &self, + block_hash: B256, + state_updates: impl FnOnce() -> Arc, + ) -> Result<(), ConsensusError> { + let Some(expectation) = self.take_withdraw_trie_root_expectation(block_hash) else { + tracing::debug!( + target: "morph::engine_validator", + %block_hash, + "no withdraw trie root expectation registered; skipping CL cross-check" + ); + return Ok(()); + }; + Self::validate_withdraw_trie_root_expectation(expectation, state_updates) + } } impl PayloadValidator for MorphEngineValidator { @@ -700,13 +816,10 @@ impl PayloadValidator for MorphEngineValidator { let expected_withdraw_trie_root = payload.expected_withdraw_trie_root; let sealed_block = Arc::unwrap_or_clone(payload.block); - let expectation = match expected_withdraw_trie_root { - Some(root) if root != B256::ZERO => WithdrawTrieRootExpectation::Verify(root), - // Match morph-geth: zero means the caller did not provide this optional - // CL/EL cross-check value, not that the expected root is actually zero. - _ => WithdrawTrieRootExpectation::SkipValidation, - }; - self.record_withdraw_trie_root_expectation(sealed_block.hash(), expectation); + if expected_withdraw_trie_root.is_some() { + let expectation = Self::expectation_from_root(expected_withdraw_trie_root); + self.record_withdraw_trie_root_expectation(sealed_block.hash(), expectation); + } Ok(sealed_block) } @@ -782,10 +895,14 @@ mod tests { WithdrawTrieRootExpectation::Verify(B256::from([0xaa; 32])), ); } - assert_eq!( - validator.expected_withdraw_trie_roots.len(), - MorphEngineValidator::MAX_EXPECTED_WITHDRAW_TRIE_ROOTS - ); + { + let cache = validator.expected_withdraw_trie_roots.lock(); + assert_eq!( + cache.entries.len(), + MorphEngineValidator::MAX_EXPECTED_WITHDRAW_TRIE_ROOTS + ); + assert_eq!(cache.order.len(), cache.entries.len()); + } let oldest = key(0); let newest = key(MorphEngineValidator::MAX_EXPECTED_WITHDRAW_TRIE_ROOTS); @@ -794,23 +911,15 @@ mod tests { WithdrawTrieRootExpectation::Verify(B256::from([0xbb; 32])), ); + let cache = validator.expected_withdraw_trie_roots.lock(); assert_eq!( - validator.expected_withdraw_trie_roots.len(), + cache.entries.len(), MorphEngineValidator::MAX_EXPECTED_WITHDRAW_TRIE_ROOTS ); - assert!(!validator.expected_withdraw_trie_roots.is_empty()); - assert!( - validator - .expected_withdraw_trie_roots - .get(&newest) - .is_some() - ); - assert!( - validator - .expected_withdraw_trie_roots - .get(&oldest) - .is_none() - ); + assert_eq!(cache.order.len(), cache.entries.len()); + assert!(!cache.entries.is_empty()); + assert!(cache.entries.contains_key(&newest)); + assert!(!cache.entries.contains_key(&oldest)); } #[test] @@ -1070,6 +1179,26 @@ mod tests { ); } + #[test] + fn convert_payload_to_block_none_root_does_not_leak_cache_entry() { + let validator = MorphEngineValidator::new(); + let hash = B256::from([0x77; 32]); + let block = empty_recovered_block_with_hash(hash); + let payload = + morph_payload_types::MorphExecutionData::new(Arc::new(block.into_sealed_block())); + + validator + .convert_payload_to_block(payload) + .expect("payload conversion should succeed"); + + let cache = validator.expected_withdraw_trie_roots.lock(); + assert!( + cache.entries.is_empty(), + "None expected_withdraw_trie_root must not insert into cache" + ); + assert!(cache.order.is_empty()); + } + /// Verify expectation that mismatches an actually-updated slot must fail. #[test] fn validate_block_post_execution_rejects_mismatched_root() { diff --git a/crates/node/tests/it/consensus.rs b/crates/node/tests/it/consensus.rs index 21d6cc16..30ee6c25 100644 --- a/crates/node/tests/it/consensus.rs +++ b/crates/node/tests/it/consensus.rs @@ -441,6 +441,65 @@ async fn next_l1_msg_index_first_msg_skips_parent_allowed_pre_jade() -> eyre::Re Ok(()) } +/// Cross-block L1 message replay (`first_queue_index < parent.next_l1_msg_index`) must be +/// rejected post-Jade, even when in-block indices are contiguous and `header.next_l1_msg_index` +/// equals `last_queue_index + 1` and `>= parent.next_l1_msg_index`. +#[tokio::test(flavor = "multi_thread")] +async fn l1_message_cross_block_replay_rejected_post_jade() -> eyre::Result<()> { + reth_tracing::init_test_tracing(); + let (mut nodes, _wallet) = TestNodeBuilder::new() + .with_schedule(HardforkSchedule::AllActive) + .build() + .await?; + let mut node = nodes.pop().unwrap(); + + // Block 1 includes queue indices 0, 1 -> parent.next_l1_msg_index = 2. + advance_block_with_l1_messages(&mut node, L1MessageBuilder::build_sequential(0, 2)).await?; + + // Build a valid continuation block (queue 2, 3) then rewrite its L1 messages to replay + // index 1 (i.e. [1, 2], next_l1_msg_index = 3 >= parent's 2). + let base = build_block_no_submit(&mut node, L1MessageBuilder::build_sequential(2, 2)).await?; + let accepted = craft_and_try_import_block(&mut node, &base, |block| { + rewrite_l1_queue_indices_from(block, 1); + block.header.next_l1_msg_index = 3; + }) + .await?; + + assert!( + !accepted, + "post-Jade: cross-block L1 message replay ([1, 2] after parent next=2) must be rejected" + ); + Ok(()) +} + +/// Cross-block L1 message replay must also be rejected pre-Jade. +#[tokio::test(flavor = "multi_thread")] +async fn l1_message_cross_block_replay_rejected_pre_jade() -> eyre::Result<()> { + reth_tracing::init_test_tracing(); + let (mut nodes, _wallet) = TestNodeBuilder::new() + .with_schedule(HardforkSchedule::PreJade) + .build() + .await?; + let mut node = nodes.pop().unwrap(); + + // Block 1 includes queue indices 0, 1 -> parent.next_l1_msg_index = 2. + advance_block_with_l1_messages(&mut node, L1MessageBuilder::build_sequential(0, 2)).await?; + + // Rewrite block 2's L1 messages to replay [0, 1] with header.next_l1_msg_index = 2. + let base = build_block_no_submit(&mut node, L1MessageBuilder::build_sequential(2, 2)).await?; + let accepted = craft_and_try_import_block(&mut node, &base, |block| { + rewrite_l1_queue_indices_from(block, 0); + block.header.next_l1_msg_index = 2; + }) + .await?; + + assert!( + !accepted, + "pre-Jade: cross-block L1 message replay ([0, 1] after parent next=2) must be rejected" + ); + Ok(()) +} + /// Shift every leading L1 message's `queue_index` up by `delta`, re-sealing each tx. /// /// Used to craft a block whose L1 stream no longer continues the parent's queue index @@ -459,3 +518,19 @@ fn rewrite_l1_queue_indices(block: &mut morph_primitives::Block, delta: u64) { } } } + +/// Rewrite every leading L1 message's `queue_index` sequentially starting from `start`. +fn rewrite_l1_queue_indices_from(block: &mut morph_primitives::Block, start: u64) { + use alloy_consensus::Sealable; + use morph_primitives::MorphTxEnvelope; + + let mut next = start; + for tx in block.body.transactions.iter_mut() { + if let MorphTxEnvelope::L1Msg(sealed) = tx { + let mut inner = sealed.inner().clone(); + inner.queue_index = next; + next += 1; + *sealed = inner.seal_slow(); + } + } +} diff --git a/crates/node/tests/it/engine.rs b/crates/node/tests/it/engine.rs index 714ddc5e..feb09b54 100644 --- a/crates/node/tests/it/engine.rs +++ b/crates/node/tests/it/engine.rs @@ -22,7 +22,9 @@ use morph_primitives::MorphHeader; use reth_node_api::PayloadTypes; use reth_payload_builder::BuildNewPayload; use reth_payload_primitives::BuiltPayload; -use reth_provider::{BlockIdReader, BlockReaderIdExt}; +use reth_provider::{ + BlockIdReader, BlockReaderIdExt, ChainStateBlockReader, DatabaseProviderFactory, +}; use super::helpers::{ LOCAL_POLL_BUDGET, POLL_INTERVAL, assemble_l2_block, assemble_l2_block_v2, @@ -1253,3 +1255,259 @@ async fn empty_block_is_imported_without_execution_artifacts() -> eyre::Result<( Ok(()) } + +/// M-M10: `engine_setBlockTags` must: +/// 1. Reject non-canonical (orphaned) block hashes; +/// 2. Enforce `effective_finalized <= effective_safe <= canonical_head` across partial updates; +/// 3. Preserve the cached L1 finalized hash when `finalized_block_hash == B256::ZERO`; +/// 4. Persist updated `safe` and `finalized` tags to MDBX via the engine FCU pipeline. +#[tokio::test(flavor = "multi_thread")] +async fn set_block_tags_persists_to_mdbx_enforces_ordering_canonicality_and_preserves_zero_hash() +-> eyre::Result<()> { + reth_tracing::init_test_tracing(); + + let (mut nodes, _wallet) = TestNodeBuilder::new().build().await?; + let node = nodes.pop().unwrap(); + let client = node.auth_server_handle().http_client(); + + let base_ts = head_timestamp(&node)?; + + // Block 1 (canonical ancestor). + let b1 = assemble_l2_block( + &node, + AssembleL2BlockParams { + number: 1, + transactions: vec![], + timestamp: Some(base_ts + 1), + }, + ) + .await?; + import_l2_block(&node, b1.clone()).await?; + + // Import an orphaned sibling block at height 2, then reorg onto the canonical branch. + let orphan_2 = assemble_l2_block_v2( + &node, + AssembleL2BlockV2Params { + parent_hash: b1.hash, + transactions: vec![], + timestamp: Some(base_ts + 2), + }, + ) + .await?; + import_l2_block(&node, orphan_2.clone()).await?; + + let canon_2 = assemble_l2_block_v2( + &node, + AssembleL2BlockV2Params { + parent_hash: b1.hash, + transactions: vec![], + timestamp: Some(base_ts + 3), + }, + ) + .await?; + assert_ne!(canon_2.hash, orphan_2.hash); + import_l2_block(&node, canon_2.clone()).await?; + + let canon_3 = assemble_l2_block_v2( + &node, + AssembleL2BlockV2Params { + parent_hash: canon_2.hash, + transactions: vec![], + timestamp: Some(base_ts + 4), + }, + ) + .await?; + import_l2_block(&node, canon_3.clone()).await?; + + let canon_4 = assemble_l2_block_v2( + &node, + AssembleL2BlockV2Params { + parent_hash: canon_3.hash, + transactions: vec![], + timestamp: Some(base_ts + 5), + }, + ) + .await?; + import_l2_block(&node, canon_4.clone()).await?; + + // 1. Orphaned hash must be rejected as non-canonical (or not found). + let orphan_err = client + .request::<(), _>("engine_setBlockTags", (orphan_2.hash, B256::ZERO)) + .await + .expect_err("orphaned block hash must be rejected by engine_setBlockTags") + .to_string(); + assert!( + orphan_err.contains("not canonical") || orphan_err.contains("not found"), + "unexpected orphan rejection error: {orphan_err}" + ); + + // 2. Set safe = 2, finalized = 1. + client + .request::<(), _>("engine_setBlockTags", (canon_2.hash, b1.hash)) + .await?; + assert_eq!(node.inner.provider.safe_block_hash()?, Some(canon_2.hash)); + assert_eq!(node.inner.provider.finalized_block_hash()?, Some(b1.hash)); + + // Partial update: finalized = 3 > existing safe = 2 must fail. + let fin_gt_safe = client + .request::<(), _>("engine_setBlockTags", (B256::ZERO, canon_3.hash)) + .await + .expect_err("finalized > existing safe must fail") + .to_string(); + assert!( + fin_gt_safe.contains("finalized block number 3 exceeds safe block number 2"), + "unexpected partial finalized > safe error: {fin_gt_safe}" + ); + + // Advance safe = 3, finalized = 2. + client + .request::<(), _>("engine_setBlockTags", (canon_3.hash, canon_2.hash)) + .await?; + assert_eq!(node.inner.provider.safe_block_hash()?, Some(canon_3.hash)); + assert_eq!( + node.inner.provider.finalized_block_hash()?, + Some(canon_2.hash) + ); + + // Partial update: safe = 1 < existing finalized = 2 must fail. + let safe_lt_fin = client + .request::<(), _>("engine_setBlockTags", (b1.hash, B256::ZERO)) + .await + .expect_err("safe < existing finalized must fail") + .to_string(); + assert!( + safe_lt_fin.contains("finalized block number 2 exceeds safe block number 1"), + "unexpected partial safe < finalized error: {safe_lt_fin}" + ); + + // 3. Safe-only update (finalized == B256::ZERO) must advance safe to 4 while + // preserving finalized = 2 in both provider state and cached L1 finalized tracker. + client + .request::<(), _>("engine_setBlockTags", (canon_4.hash, B256::ZERO)) + .await?; + assert_eq!(node.inner.provider.safe_block_hash()?, Some(canon_4.hash)); + assert_eq!( + node.inner.provider.finalized_block_hash()?, + Some(canon_2.hash) + ); + + // 4. Advance additional blocks past reth's default persistence threshold (50) and + // memory buffer target (5) so block 4 is flushed to disk together with the queued + // safe=4 and finalized=2 MDBX checkpoints. + let mut parent_hash = canon_4.hash; + for offset in 6..=56u64 { + let next = assemble_l2_block_v2( + &node, + AssembleL2BlockV2Params { + parent_hash, + transactions: vec![], + timestamp: Some(base_ts + offset), + }, + ) + .await?; + parent_hash = next.hash; + import_l2_block(&node, next).await?; + } + + assert_eq!( + node.inner.provider.finalized_block_hash()?, + Some(canon_2.hash), + "cached L1 finalized hash must be preserved across subsequent imports" + ); + + let deadline = tokio::time::Instant::now() + LOCAL_POLL_BUDGET; + loop { + let db = node.inner.provider.database_provider_ro()?; + let db_finalized = db.last_finalized_block_number()?; + let db_safe = db.last_safe_block_number()?; + if db_finalized == Some(2) && db_safe == Some(4) { + break; + } + assert!( + tokio::time::Instant::now() < deadline, + "expected MDBX safe=Some(4) and finalized=Some(2), got safe={db_safe:?} finalized={db_finalized:?}" + ); + tokio::time::sleep(POLL_INTERVAL).await; + } + + Ok(()) +} + +/// M-M11: Concurrent `engine_assembleL2BlockV2` calls with identical inputs must serialize +/// cleanly instead of colliding on deterministic `PayloadId` in `PayloadBuilderService`. +#[tokio::test(flavor = "multi_thread")] +async fn concurrent_identical_assemble_l2_block_v2_calls_do_not_collide() -> eyre::Result<()> { + reth_tracing::init_test_tracing(); + + let (mut nodes, wallet) = TestNodeBuilder::new().build().await?; + let node = nodes.pop().unwrap(); + + let raw_tx = make_transfer_tx(wallet.chain_id, wallet.inner.clone(), wallet.inner_nonce).await; + let tx_hash = node.rpc.inject_tx(raw_tx).await?; + wait_until_pooled(&node, tx_hash).await?; + + let head = canonical_snapshot(&node)?; + let ts = head_timestamp(&node)? + 1; + + let calls = (0..8).map(|_| { + assemble_l2_block_v2( + &node, + AssembleL2BlockV2Params { + parent_hash: head.hash, + transactions: vec![], + timestamp: Some(ts), + }, + ) + }); + + let results = futures::future::try_join_all(calls).await?; + assert_eq!(results.len(), 8); + for block in results { + assert_eq!(block.parent_hash, head.hash); + assert_eq!(block.number, head.number + 1); + assert_eq!(block.transactions.len(), 1); + } + + Ok(()) +} + +/// M-H10: `engine_newSafeL2Block` must reject a supplied MorphTx V2 before Celadon +/// activates, even when Prague is active (Jade) and the authorization list is empty. +#[tokio::test(flavor = "multi_thread")] +async fn new_safe_l2_block_rejects_v2_morph_tx_before_celadon() -> eyre::Result<()> { + reth_tracing::init_test_tracing(); + + let (mut nodes, wallet) = TestNodeBuilder::new() + .with_schedule(HardforkSchedule::PreCeladon) + .build() + .await?; + let node = nodes.pop().unwrap(); + + let v2_tx = MorphTxBuilder::new(wallet.chain_id, wallet.inner.clone(), wallet.inner_nonce) + .with_v2_eth_fee() + .build_signed()?; + + let head = canonical_snapshot(&node)?; + let safe_data = SafeL2Data { + number: 1, + gas_limit: 30_000_000, + base_fee_per_gas: Some(1_000_000), + timestamp: head_timestamp(&node)? + 1, + transactions: vec![v2_tx], + parent_hash: Some(head.hash), + }; + + let client = node.auth_server_handle().http_client(); + let err = client + .request::("engine_newSafeL2Block", (safe_data,)) + .await + .expect_err("pre-Celadon newSafeL2Block must reject supplied MorphTx V2") + .to_string(); + assert!( + err.contains("celadon") || err.contains("failed to get built payload"), + "unexpected pre-Celadon MorphTx V2 error: {err}" + ); + assert_eq!(canonical_snapshot(&node)?, head); + + Ok(()) +} diff --git a/crates/node/tests/it/invalid_payload_recovery.rs b/crates/node/tests/it/invalid_payload_recovery.rs index d67d5590..a9082125 100644 --- a/crates/node/tests/it/invalid_payload_recovery.rs +++ b/crates/node/tests/it/invalid_payload_recovery.rs @@ -4,13 +4,14 @@ use alloy_consensus::{BlockHeader, Sealable, transaction::TxHashRef}; use alloy_primitives::B256; use jsonrpsee::core::client::ClientT; use morph_node::test_utils::{TestNodeBuilder, make_transfer_tx}; -use morph_payload_types::{AssembleL2BlockParams, GenericResponse}; +use morph_payload_types::{AssembleL2BlockParams, AssembleL2BlockV2Params, GenericResponse}; use morph_primitives::MorphHeader; use reth_payload_primitives::BuiltPayload; -use reth_provider::{AccountReader, StateProviderFactory}; +use reth_provider::{AccountReader, BlockIdReader, StateProviderFactory}; use super::helpers::{ - assemble_l2_block, build_block_no_submit, canonical_snapshot, head_timestamp, import_l2_block, + LOCAL_POLL_BUDGET, POLL_INTERVAL, assemble_l2_block, assemble_l2_block_v2, + build_block_no_submit, canonical_snapshot, head_timestamp, import_l2_block, payload_with_receipts_root, wait_until_evicted, wait_until_pooled, }; @@ -181,3 +182,160 @@ async fn corrupted_next_l1_msg_index_does_not_poison_the_honest_block() -> eyre: Ok(()) } + +/// M-H07: Even when a non-empty block hash is already in `tree_state` (pre-inserted by +/// `assembleL2BlockV2`, so reth's `on_new_payload` would short-circuit on `AlreadySeen`), +/// tampering with the unhashed `next_l1_message_index` must be rejected by +/// `engine_validateL2Block`, `engine_newL2Block`, and `engine_newL2BlockV2` without +/// poisoning `invalid_headers` for the honest block. +#[tokio::test(flavor = "multi_thread")] +async fn tampered_next_l1_msg_index_rejected_when_block_already_seen() -> eyre::Result<()> { + reth_tracing::init_test_tracing(); + + let (mut nodes, wallet) = TestNodeBuilder::new().build().await?; + let node = nodes.pop().expect("one node requested"); + + let raw_tx = make_transfer_tx(wallet.chain_id, wallet.inner.clone(), wallet.inner_nonce).await; + let tx_hash = node.rpc.inject_tx(raw_tx).await?; + wait_until_pooled(&node, tx_hash).await?; + + let before = canonical_snapshot(&node)?; + let honest = assemble_l2_block_v2( + &node, + AssembleL2BlockV2Params { + parent_hash: before.hash, + transactions: vec![], + timestamp: Some(head_timestamp(&node)? + 1), + }, + ) + .await?; + assert_eq!(honest.transactions.len(), 1); + + // Wait until the engine tree has pre-inserted the non-empty block so `AlreadySeen` + // is guaranteed to be armed in `tree_state`. + let deadline = tokio::time::Instant::now() + LOCAL_POLL_BUDGET; + loop { + if node + .inner + .provider + .pending_block_num_hash()? + .map(|p| p.hash) + == Some(honest.hash) + { + break; + } + assert!( + tokio::time::Instant::now() < deadline, + "precondition: non-empty candidate was not pre-inserted into tree_state" + ); + tokio::time::sleep(POLL_INTERVAL).await; + } + + let mut tampered = honest.clone(); + tampered.next_l1_message_index += 1; + + let client = node.auth_server_handle().http_client(); + + let validation: GenericResponse = client + .request("engine_validateL2Block", (tampered.clone(),)) + .await?; + assert!( + !validation.success, + "engine_validateL2Block must reject tampered next_l1_message_index on AlreadySeen block" + ); + + let err_v1 = client + .request::<(), _>("engine_newL2Block", (tampered.clone(),)) + .await + .expect_err("engine_newL2Block must reject tampered next_l1_message_index") + .to_string(); + assert!( + err_v1.contains("invalid block.NextL1MsgIndex"), + "unexpected engine_newL2Block error: {err_v1}" + ); + + let err_v2 = import_l2_block(&node, tampered) + .await + .expect_err("engine_newL2BlockV2 must reject tampered next_l1_message_index") + .to_string(); + assert!( + err_v2.contains("invalid block.NextL1MsgIndex"), + "unexpected engine_newL2BlockV2 error: {err_v2}" + ); + + assert_eq!( + canonical_snapshot(&node)?, + before, + "rejected tampered requests must leave canonical chain unchanged" + ); + + // The honest copy sharing the same block hash must still import cleanly. + let imported = import_l2_block(&node, honest.clone()).await?; + assert_eq!(imported.hash_slow(), honest.hash); + assert_eq!(canonical_snapshot(&node)?.hash, honest.hash); + + Ok(()) +} + +/// M-H07: A locally built non-empty block that violates consensus (e.g., future timestamp) +/// must be rejected by `on_inserted_executed_block` so it is NOT pre-inserted into +/// `tree_state` and cannot subsequently bypass validation via `AlreadySeen`. +#[tokio::test(flavor = "multi_thread")] +async fn pre_inserted_consensus_invalid_block_is_rejected_and_not_cached() -> eyre::Result<()> { + reth_tracing::init_test_tracing(); + + let (mut nodes, wallet) = TestNodeBuilder::new().build().await?; + let node = nodes.pop().expect("one node requested"); + + let raw_tx = make_transfer_tx(wallet.chain_id, wallet.inner.clone(), wallet.inner_nonce).await; + let tx_hash = node.rpc.inject_tx(raw_tx).await?; + wait_until_pooled(&node, tx_hash).await?; + + let before = canonical_snapshot(&node)?; + let future_timestamp = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_secs() + + 3600; + + let future_block = assemble_l2_block_v2( + &node, + AssembleL2BlockV2Params { + parent_hash: before.hash, + transactions: vec![], + timestamp: Some(future_timestamp), + }, + ) + .await?; + assert_eq!( + future_block.transactions.len(), + 1, + "precondition: block must be non-empty so InsertExecutedBlock is emitted" + ); + + // Give the async engine tree task ample time to process InsertExecutedBlock; + // `on_inserted_executed_block` must reject the future-timestamp header. + tokio::time::sleep(std::time::Duration::from_millis(500)).await; + assert_eq!( + node.inner.provider.pending_block_num_hash()?, + None, + "consensus-invalid future block must not be pre-inserted into tree_state" + ); + + // Importing it must fail consensus validation rather than hitting AlreadySeen. + let err = import_l2_block(&node, future_block) + .await + .expect_err("future-timestamp block must be rejected on import") + .to_string(); + assert!( + err.to_lowercase().contains("future"), + "expected future-timestamp consensus rejection, got: {err}" + ); + assert_eq!( + canonical_snapshot(&node)?, + before, + "canonical state must remain unchanged after rejecting future block" + ); + + Ok(()) +} diff --git a/crates/node/tests/it/network.rs b/crates/node/tests/it/network.rs index 6766d63e..aab70388 100644 --- a/crates/node/tests/it/network.rs +++ b/crates/node/tests/it/network.rs @@ -19,7 +19,13 @@ async fn peer_pool_reaches_node_before_first_block() -> eyre::Result<()> { reth_tracing::init_test_tracing(); // Built separately so they are not connected until the transaction is pending. - let (mut sequencers, wallet) = TestNodeBuilder::new().build().await?; + // Match production CLI defaults (`startup_sync_state_idle = false`) so the test + // exercises `MorphNetworkBuilder`'s start-up sync toggle rather than the E2E + // harness's `startup_sync_state_idle = true` shortcut. + let (mut sequencers, wallet) = TestNodeBuilder::new() + .with_startup_sync_state_idle(false) + .build() + .await?; let (mut rpcs, _) = TestNodeBuilder::new().build().await?; let mut sequencer = sequencers.pop().unwrap(); let mut rpc = rpcs.pop().unwrap(); diff --git a/crates/node/tests/it/reference_index.rs b/crates/node/tests/it/reference_index.rs index 7d9afaa4..6addb1bc 100644 --- a/crates/node/tests/it/reference_index.rs +++ b/crates/node/tests/it/reference_index.rs @@ -177,3 +177,99 @@ async fn reference_index_no_results_for_unrelated_reference() -> eyre::Result<() Ok(()) } + +/// M-M06: `morph_` RPC methods must NOT be registered on HTTP transports that do not +/// enable the `morph` module (e.g. `RpcModuleSelection::Standard` / `eth,net,web3`). +#[tokio::test(flavor = "multi_thread")] +async fn morph_rpc_not_exposed_when_morph_module_not_configured() -> eyre::Result<()> { + reth_tracing::init_test_tracing(); + + let (mut nodes, _wallet) = TestNodeBuilder::new() + .with_http_api(reth_rpc_builder::RpcModuleSelection::Standard) + .build() + .await?; + let node = nodes.pop().unwrap(); + let client = node + .rpc_client() + .ok_or_else(|| eyre::eyre!("HTTP RPC client not available"))?; + + // Standard `eth_` methods remain available. + let block_number: U64 = client + .request("eth_blockNumber", jsonrpsee::rpc_params![]) + .await?; + assert_eq!(block_number, U64::ZERO); + + // `morph_` namespace is not registered and must return Method Not Found (-32601). + let err = client + .request::, _>( + "morph_getTransactionHashesByReference", + (query_args(B256::with_last_byte(0x42), None, None),), + ) + .await + .expect_err("morph_ must not be registered under Standard HTTP modules"); + match err { + jsonrpsee::core::ClientError::Call(obj) => { + assert_eq!( + obj.code(), + -32601, + "expected Method Not Found (-32601), got {obj:?}" + ); + } + other => panic!("expected JSON-RPC Call error (-32601), got {other:?}"), + } + + Ok(()) +} + +/// M-M06: `morph_` RPC methods ARE registered when `morph` is explicitly enabled via +/// `--http.api eth,morph` (`RethRpcModule::Other("morph")`), while unconfigured modules +/// remain disabled. +#[tokio::test(flavor = "multi_thread")] +async fn morph_rpc_exposed_when_morph_module_explicitly_configured() -> eyre::Result<()> { + reth_tracing::init_test_tracing(); + + let selection: reth_rpc_builder::RpcModuleSelection = "eth,morph".parse()?; + assert!(selection.contains(&reth_rpc_builder::RethRpcModule::Other("morph".into()))); + + let (mut nodes, wallet) = TestNodeBuilder::new() + .with_http_api(selection) + .build() + .await?; + let mut node = nodes.pop().unwrap(); + + let reference = B256::with_last_byte(0xdd); + let raw_tx = MorphTxBuilder::new(wallet.chain_id, wallet.inner.clone(), wallet.inner_nonce) + .with_v1_token_fee(TEST_TOKEN_ID) + .with_reference(reference) + .build_signed()?; + node.rpc.inject_tx(raw_tx).await?; + let payload = node.advance_block().await?; + let tx_hash = *payload + .block() + .body() + .transactions + .first() + .unwrap() + .tx_hash(); + + let results = wait_for_reference_query(&node, query_args(reference, None, None)).await?; + assert_eq!(results.len(), 1); + assert_eq!(results[0].transaction_hash, tx_hash); + + // Confirm unconfigured module (`txpool`) is not accidentally exposed. + let client = node + .rpc_client() + .ok_or_else(|| eyre::eyre!("HTTP RPC client not available"))?; + let err = client + .request::("txpool_status", jsonrpsee::rpc_params![]) + .await + .expect_err("unconfigured txpool module must not be registered"); + match err { + jsonrpsee::core::ClientError::Call(obj) => { + assert_eq!(obj.code(), -32601); + } + other => panic!("expected JSON-RPC Call error (-32601), got {other:?}"), + } + + Ok(()) +} diff --git a/crates/node/tests/it/rpc.rs b/crates/node/tests/it/rpc.rs index b944e23d..e53dfbad 100644 --- a/crates/node/tests/it/rpc.rs +++ b/crates/node/tests/it/rpc.rs @@ -1636,3 +1636,696 @@ async fn send_raw_transaction_sync_timeout_includes_tx_hash_data_and_returns_rec Ok(()) } + +/// `eth_maxPriorityFeePerGas` and `eth_gasPrice` must never collapse to zero on +/// empty blocks, and must scale above the median tip when a block reaches capacity. +#[tokio::test(flavor = "multi_thread")] +async fn gas_price_oracle_returns_floor_on_empty_blocks_and_scales_at_capacity() -> eyre::Result<()> +{ + use alloy_consensus::TxEip1559; + use morph_chainspec::{MORPH_BASE_FEE, MORPH_DEFAULT_PRIORITY_FEE}; + + reth_tracing::init_test_tracing(); + + // 1. Genesis and consecutive empty blocks must return MORPH_DEFAULT_PRIORITY_FEE, + // not 0x0 (which upstream `GasPriceOracle::suggest_tip_cap` produced). + let (mut nodes, _wallet) = TestNodeBuilder::new().build().await?; + let mut node = nodes.pop().unwrap(); + let client = node + .rpc_client() + .ok_or_else(|| eyre::eyre!("HTTP RPC client not available"))?; + + let expected_tip = U256::from(MORPH_DEFAULT_PRIORITY_FEE); + let expected_gas_price = U256::from(MORPH_BASE_FEE + MORPH_DEFAULT_PRIORITY_FEE); + + let genesis_tip: U256 = client + .request("eth_maxPriorityFeePerGas", jsonrpsee::rpc_params![]) + .await?; + let genesis_gas_price: U256 = client + .request("eth_gasPrice", jsonrpsee::rpc_params![]) + .await?; + assert_eq!(genesis_tip, expected_tip); + assert_eq!(genesis_gas_price, expected_gas_price); + + for _ in 0..3 { + let payload = node.advance_block().await?; + assert!(payload.block().body().transactions.is_empty()); + } + + let empty_tip: U256 = client + .request("eth_maxPriorityFeePerGas", jsonrpsee::rpc_params![]) + .await?; + let empty_gas_price: U256 = client + .request("eth_gasPrice", jsonrpsee::rpc_params![]) + .await?; + assert_eq!(empty_tip, expected_tip); + assert_eq!(empty_gas_price, expected_gas_price); + + // 2. When a block reaches capacity (`gas_used + max_tx_gas_used > gas_limit`), + // `eth_maxPriorityFeePerGas` scales up to 110% of the block's median tip. + let (mut cap_nodes, cap_wallet) = TestNodeBuilder::new() + .with_gas_limit(30_000) + .build() + .await?; + let mut cap_node = cap_nodes.pop().unwrap(); + let cap_client = cap_node + .rpc_client() + .ok_or_else(|| eyre::eyre!("HTTP RPC client not available"))?; + + let high_tip = 10_000_000u128; + let tx = TxEip1559 { + chain_id: cap_wallet.chain_id, + nonce: 0, + gas_limit: 21_000, + max_fee_per_gas: 20_000_000, + max_priority_fee_per_gas: high_tip, + to: TxKind::Call(Address::with_last_byte(0x42)), + value: U256::ZERO, + access_list: Default::default(), + input: Bytes::new(), + }; + let sig = cap_wallet + .inner + .sign_hash_sync(&tx.signature_hash()) + .map_err(|e| eyre::eyre!("{e}"))?; + let raw: Bytes = MorphTxEnvelope::Eip1559(tx.into_signed(sig)) + .encoded_2718() + .into(); + + cap_node.rpc.inject_tx(raw).await?; + let payload = cap_node.advance_block().await?; + assert_eq!(payload.block().body().transactions.len(), 1); + assert_eq!(payload.block().header().gas_used(), 21_000); + + let congested_tip: U256 = cap_client + .request("eth_maxPriorityFeePerGas", jsonrpsee::rpc_params![]) + .await?; + let congested_gas_price: U256 = cap_client + .request("eth_gasPrice", jsonrpsee::rpc_params![]) + .await?; + let expected_congested_tip = U256::from(high_tip + high_tip / 10); + assert_eq!(congested_tip, expected_congested_tip); + assert_eq!( + congested_gas_price, + expected_congested_tip + U256::from(MORPH_BASE_FEE) + ); + + cap_node.advance_block().await?; + let recovered_tip: U256 = cap_client + .request("eth_maxPriorityFeePerGas", jsonrpsee::rpc_params![]) + .await?; + assert_eq!(recovered_tip, expected_tip); + + Ok(()) +} + +/// `eth_estimateGas` from a zero-balance account with `maxPriorityFeePerGas: 0x0` +/// and omitted `maxFeePerGas` must treat the request as zero-priced and succeed. +#[tokio::test(flavor = "multi_thread")] +async fn estimate_gas_zero_balance_zero_tip_without_max_fee_succeeds() -> eyre::Result<()> { + reth_tracing::init_test_tracing(); + let (mut nodes, _wallet) = TestNodeBuilder::new().build().await?; + let node = nodes.pop().unwrap(); + let client = node + .rpc_client() + .ok_or_else(|| eyre::eyre!("HTTP RPC client not available"))?; + + let zero_balance_sender = Address::random(); + let req = serde_json::json!({ + "from": zero_balance_sender, + "to": Address::with_last_byte(0x42), + "maxPriorityFeePerGas": "0x0", + }); + let gas: U256 = client.request("eth_estimateGas", (req,)).await?; + assert_eq!(gas, U256::from(21_000u64)); + + Ok(()) +} + +/// Decodes a 32-byte hex string (with `0x` prefix) returned by EVM calls into a [`U256`]. +fn decode_u256_word(hex: &str) -> U256 { + let bytes = + alloy_primitives::hex::decode(hex.trim_start_matches("0x")).expect("valid hex return data"); + assert_eq!(bytes.len(), 32, "expected 32-byte ABI word, got {hex}"); + U256::from_be_slice(&bytes) +} + +/// Decodes two concatenated 32-byte hex words returned by the 2-address balance reader. +fn decode_two_u256_words(hex: &str) -> (U256, U256) { + let bytes = + alloy_primitives::hex::decode(hex.trim_start_matches("0x")).expect("valid hex return data"); + assert_eq!(bytes.len(), 64, "expected 64-byte ABI output, got {hex}"); + ( + U256::from_be_slice(&bytes[..32]), + U256::from_be_slice(&bytes[32..]), + ) +} + +/// ABI-encodes a single address as a 32-byte calldata word. +fn encode_address_word(addr: Address) -> String { + let mut buf = [0u8; 32]; + buf[12..].copy_from_slice(addr.as_slice()); + format!("0x{}", alloy_primitives::hex::encode(buf)) +} + +/// ABI-encodes two addresses as 64 bytes of calldata. +fn encode_two_address_words(a: Address, b: Address) -> String { + let mut buf = [0u8; 64]; + buf[12..32].copy_from_slice(a.as_slice()); + buf[44..64].copy_from_slice(b.as_slice()); + format!("0x{}", alloy_primitives::hex::encode(buf)) +} + +/// ABI-encodes ERC-20 `balanceOf(address)`. +fn encode_balance_of(addr: Address) -> String { + let mut buf = [0u8; 36]; + buf[..4].copy_from_slice(&[0x70, 0xa0, 0x82, 0x31]); + buf[16..].copy_from_slice(addr.as_slice()); + format!("0x{}", alloy_primitives::hex::encode(buf)) +} + +/// `eth_simulateV1` with `validation: false` must disable L1 and L2 fee charging +/// for both ETH and token-fee MorphTxs post-Curie with non-zero L1 oracle fees: +/// - Omitted-`from` and zero-balance callers succeed. +/// - Funded caller balances and FeeVault balance are unchanged by L1/L2 fees +/// (and `value > 0` transfers move only `value`). +/// - Call-mode token-fee MorphTxs neither deduct tokens nor emit fee `Transfer` logs. +#[tokio::test(flavor = "multi_thread")] +async fn simulate_v1_validation_false_skips_l1_and_l2_fees() -> eyre::Result<()> { + reth_tracing::init_test_tracing(); + + const L1_ORACLE: Address = + alloy_primitives::address!("530000000000000000000000000000000000000f"); + const FEE_VAULT: Address = + alloy_primitives::address!("530000000000000000000000000000000000000a"); + const TEST_TOKEN: Address = + alloy_primitives::address!("5300000000000000000000000000000000000022"); + const L1_BASE_FEE: u64 = 10_000_000_000; // 10 gwei (non-zero Curie commit fee) + const L1_BLOB_BASE_FEE: u64 = 10_000_000_000; // 10 gwei (non-zero Curie blob fee) + // Runtime bytecode: return `BALANCE(calldataload(0))` (32 bytes). + const BALANCE_READER_CODE: &str = "0x6000353160005260206000f3"; + + let (mut nodes, wallet) = TestNodeBuilder::new() + .with_account_storage(L1_ORACLE, U256::from(1u64), U256::from(L1_BASE_FEE)) + .with_account_storage(L1_ORACLE, U256::from(6u64), U256::from(L1_BLOB_BASE_FEE)) + .build() + .await?; + let mut node = nodes.pop().unwrap(); + let funded = wallet.inner.address(); + advance_chain(1, &mut node, wallet_to_arc(wallet)).await?; + + let client = node + .rpc_client() + .ok_or_else(|| eyre::eyre!("HTTP RPC client not available"))?; + + let latest_state = node.inner.provider.latest()?; + let funded_account = latest_state + .basic_account(&funded)? + .expect("funded wallet exists"); + let initial_funded_balance = funded_account.balance; + let initial_funded_nonce = funded_account.nonce; + let initial_vault_balance = latest_state + .basic_account(&FEE_VAULT)? + .map(|a| a.balance) + .unwrap_or_default(); + + // Read funded wallet's initial call-mode fee token balance via eth_call. + let initial_token_hex: String = client + .request( + "eth_call", + ( + serde_json::json!({ + "to": TEST_TOKEN, + "input": encode_balance_of(funded), + }), + "latest", + ), + ) + .await?; + let initial_token_balance = decode_u256_word(&initial_token_hex); + assert!( + initial_token_balance > U256::ZERO, + "funded wallet must hold genesis test fee tokens" + ); + + let reader_addr = Address::random(); + let unfunded_caller = Address::random(); + let recipient = Address::random(); + let value_recipient = Address::random(); + let transfer_value = U256::from(1_000_000_000_000_000_000u128); // 1 ETH + let calldata = format!("0x{}", alloy_primitives::hex::encode(vec![0xaa; 128])); + + let payload = serde_json::json!({ + "blockStateCalls": [{ + "stateOverrides": { + reader_addr.to_string(): { + "code": BALANCE_READER_CODE, + }, + }, + "calls": [ + // 0: omitted `from` (spec default 0x0000...0000, zero ETH) + { + "to": recipient, + "input": calldata, + }, + // 1: explicit zero-balance caller with non-zero gasPrice + { + "from": unfunded_caller, + "to": recipient, + "gasPrice": "0x3b9aca00", + "input": calldata, + }, + // 2: funded caller, value = 0, non-zero EIP-1559 fee caps + calldata + { + "from": funded, + "to": recipient, + "maxFeePerGas": "0x77359400", + "maxPriorityFeePerGas": "0x3b9aca00", + "input": calldata, + }, + // 3: check funded caller ETH balance unchanged + { + "to": reader_addr, + "input": encode_address_word(funded), + }, + // 4: check FeeVault ETH balance unchanged (no phantom reward) + { + "to": reader_addr, + "input": encode_address_word(FEE_VAULT), + }, + // 5: funded caller, value = 1 ETH transfer + { + "from": funded, + "to": value_recipient, + "value": format!("{transfer_value:#x}"), + "maxFeePerGas": "0x77359400", + "maxPriorityFeePerGas": "0x3b9aca00", + }, + // 6: check funded caller ETH balance decreased by exact transfer_value + { + "to": reader_addr, + "input": encode_address_word(funded), + }, + // 7: check value_recipient received exact transfer_value + { + "to": reader_addr, + "input": encode_address_word(value_recipient), + }, + // 8: check FeeVault ETH balance still unchanged + { + "to": reader_addr, + "input": encode_address_word(FEE_VAULT), + }, + // 9: call-mode token-fee MorphTx from unfunded caller (0 ETH, 0 tokens) + { + "from": unfunded_caller, + "to": recipient, + "feeTokenID": format!("{TEST_TOKEN_ID:#x}"), + "feeLimit": "0x0", + "input": calldata, + }, + // 10: call-mode token-fee MorphTx from funded wallet (must emit 0 logs & deduct 0 tokens) + { + "from": funded, + "to": recipient, + "maxFeePerGas": "0x77359400", + "maxPriorityFeePerGas": "0x3b9aca00", + "feeTokenID": format!("{TEST_TOKEN_ID:#x}"), + "feeLimit": "0xde0b6b3a7640000", + "input": calldata, + }, + // 11: check funded wallet token balance unchanged + { + "to": TEST_TOKEN, + "input": encode_balance_of(funded), + }, + // 12: check FeeVault token balance unchanged (0) + { + "to": TEST_TOKEN, + "input": encode_balance_of(FEE_VAULT), + }, + ], + }], + "validation": false, + "returnFullTransactions": true, + }); + + let blocks: Value = client + .request("eth_simulateV1", (payload, "latest")) + .await?; + let block = &blocks[0]; + let calls = block["calls"].as_array().expect("calls array"); + assert_eq!(calls.len(), 13); + + for (idx, call) in calls.iter().enumerate() { + assert_eq!( + call["status"].as_str(), + Some("0x1"), + "call {idx} must succeed under validation=false: {call}" + ); + } + + // Funded caller ETH balance unchanged after value=0 call. + assert_eq!( + decode_u256_word(calls[3]["returnData"].as_str().unwrap()), + initial_funded_balance, + "validation=false must not deduct L1/L2 fees from funded caller" + ); + // FeeVault ETH balance unchanged after value=0 call. + assert_eq!( + decode_u256_word(calls[4]["returnData"].as_str().unwrap()), + initial_vault_balance, + "validation=false must not credit phantom fees to FeeVault" + ); + // Funded caller ETH balance reduced by exact transfer_value after value>0 call. + assert_eq!( + decode_u256_word(calls[6]["returnData"].as_str().unwrap()), + initial_funded_balance - transfer_value, + "value transfer under validation=false must debit only tx.value" + ); + assert_eq!( + decode_u256_word(calls[7]["returnData"].as_str().unwrap()), + transfer_value, + "recipient must receive exact transfer_value" + ); + assert_eq!( + decode_u256_word(calls[8]["returnData"].as_str().unwrap()), + initial_vault_balance, + "FeeVault balance must remain unchanged after value transfer" + ); + + // Call-mode token-fee MorphTxs must emit zero fee Transfer logs and move zero tokens. + assert!( + calls[9]["logs"].as_array().unwrap().is_empty(), + "unfunded token-fee MorphTx must emit no logs under validation=false" + ); + assert!( + calls[10]["logs"].as_array().unwrap().is_empty(), + "funded call-mode token-fee MorphTx must emit no fee Transfer logs under validation=false" + ); + assert_eq!( + decode_u256_word(calls[11]["returnData"].as_str().unwrap()), + initial_token_balance, + "funded caller token balance must be unchanged under validation=false" + ); + assert_eq!( + decode_u256_word(calls[12]["returnData"].as_str().unwrap()), + U256::ZERO, + "FeeVault token balance must remain zero under validation=false" + ); + + // Verify caller nonce bumped across funded ETH and MorphTx calls (indices 2, 5, 10). + let txs = block["transactions"] + .as_array() + .expect("transactions array"); + assert_eq!( + txs[2]["nonce"].as_str(), + Some(format!("{initial_funded_nonce:#x}").as_str()) + ); + assert_eq!( + txs[5]["nonce"].as_str(), + Some(format!("{:#x}", initial_funded_nonce + 1).as_str()) + ); + assert_eq!( + txs[10]["nonce"].as_str(), + Some(format!("{:#x}", initial_funded_nonce + 2).as_str()) + ); + + // Also exercise the `traceTransfers: true` (`TransferInspector`) branch under + // `validation: false`: a 1 ETH transfer emits exactly 1 synthetic ETH transfer + // log (to `value_recipient`) and zero FeeVault transfer logs. + let trace_payload = serde_json::json!({ + "blockStateCalls": [{ + "calls": [{ + "from": funded, + "to": value_recipient, + "value": format!("{transfer_value:#x}"), + "maxFeePerGas": "0x77359400", + "maxPriorityFeePerGas": "0x3b9aca00", + }], + }], + "traceTransfers": true, + "validation": false, + }); + let trace_blocks: Value = client + .request("eth_simulateV1", (trace_payload, "latest")) + .await?; + let trace_call = &trace_blocks[0]["calls"][0]; + assert_eq!(trace_call["status"].as_str(), Some("0x1")); + let trace_logs = trace_call["logs"].as_array().expect("trace logs array"); + assert_eq!( + trace_logs.len(), + 1, + "traceTransfers with validation=false must record only the value transfer, not fee transfers: {trace_logs:?}" + ); + + Ok(()) +} + +/// `eth_simulateV1` with `validation: true` must wrap simulated transactions with +/// their real EIP-2718 encoding so post-Curie `commit + blob` L1 fees are charged +/// and validated accurately (for both standard ETH txs and token-fee MorphTxs). +#[tokio::test(flavor = "multi_thread")] +async fn simulate_v1_validation_true_charges_full_curie_l1_and_l2_fees() -> eyre::Result<()> { + reth_tracing::init_test_tracing(); + + const L1_ORACLE: Address = + alloy_primitives::address!("530000000000000000000000000000000000000f"); + const FEE_VAULT: Address = + alloy_primitives::address!("530000000000000000000000000000000000000a"); + const L1_BASE_FEE: u64 = 10_000_000_000; // 10 gwei + const L1_BLOB_BASE_FEE: u64 = 10_000_000_000; // 10 gwei + // Matches `tests/assets/test-genesis.json` slots 7 & 8. + const COMMIT_SCALAR: u128 = 0x35ba5d7b55; + const BLOB_SCALAR: u128 = 0x18e38a4c; + const L1_FEE_PRECISION: u128 = 1_000_000_000; + // Runtime bytecode: return `(BALANCE(calldataload(0)), BALANCE(calldataload(32)))` (64 bytes). + const DUAL_BALANCE_READER_CODE: &str = "0x600035316000526020353160205260406000f3"; + + let (mut nodes, wallet) = TestNodeBuilder::new() + .with_account_storage(L1_ORACLE, U256::from(1u64), U256::from(L1_BASE_FEE)) + .with_account_storage(L1_ORACLE, U256::from(6u64), U256::from(L1_BLOB_BASE_FEE)) + .build() + .await?; + let mut node = nodes.pop().unwrap(); + let chain_id = wallet.chain_id; + let funded_wallet = wallet.inner.address(); + advance_chain(1, &mut node, wallet_to_arc(wallet)).await?; + + let client = node + .rpc_client() + .ok_or_else(|| eyre::eyre!("HTTP RPC client not available"))?; + + let initial_vault_balance = node + .inner + .provider + .latest()? + .basic_account(&FEE_VAULT)? + .map(|a| a.balance) + .unwrap_or_default(); + + let sender = Address::random(); + let recipient = Address::random(); + let reader_addr = Address::random(); + let calldata = Bytes::from(vec![0xab; 1024]); + let gas_limit = 50_000u64; + let max_fee_per_gas = 2_000_000_000u128; // 2 gwei + let max_priority_fee_per_gas = 1_000_000_000u128; // 1 gwei + + // Build the exact simulated EIP-1559 envelope (`Signature(0, 0, false)`) that + // `resolve_transaction` / `TryIntoSimTx` produces so we know its exact EIP-2718 length. + let sim_sig = alloy_primitives::Signature::new(U256::ZERO, U256::ZERO, false); + let expected_eth_envelope = MorphTxEnvelope::Eip1559( + alloy_consensus::TxEip1559 { + chain_id, + nonce: 0, + gas_limit, + max_fee_per_gas, + max_priority_fee_per_gas, + to: TxKind::Call(recipient), + value: U256::ZERO, + access_list: Default::default(), + input: calldata.clone(), + } + .into_signed(sim_sig), + ); + let encoded_len = expected_eth_envelope.encoded_2718().len() as u128; + let commit_only_l1_fee = + U256::from((COMMIT_SCALAR * u128::from(L1_BASE_FEE)) / L1_FEE_PRECISION); + let full_l1_fee = U256::from( + (COMMIT_SCALAR * u128::from(L1_BASE_FEE) + + BLOB_SCALAR * encoded_len * u128::from(L1_BLOB_BASE_FEE)) + / L1_FEE_PRECISION, + ); + assert!( + full_l1_fee > commit_only_l1_fee * U256::from(2u64), + "calldata blob fee must significantly exceed commit-only fee" + ); + + let l2_max_fee = U256::from(gas_limit) * U256::from(max_fee_per_gas); + let tx_call = serde_json::json!({ + "from": sender, + "to": recipient, + "gas": format!("{gas_limit:#x}"), + "maxFeePerGas": format!("{max_fee_per_gas:#x}"), + "maxPriorityFeePerGas": format!("{max_priority_fee_per_gas:#x}"), + "input": calldata.to_string(), + }); + + // (1) Balance covers L2 + commit-only L1 fee (+ half the blob fee), NOT full Curie L1 fee: + // must fail with insufficient funds (-38014). Under the old empty-RLP bug this passed! + let insufficient_balance = + l2_max_fee + commit_only_l1_fee + (full_l1_fee - commit_only_l1_fee) / U256::from(2u64); + let fail_payload = serde_json::json!({ + "blockStateCalls": [{ + "stateOverrides": { + sender.to_string(): { + "balance": format!("{insufficient_balance:#x}"), + }, + }, + "calls": [tx_call], + }], + "validation": true, + }); + let err = client + .request::("eth_simulateV1", (fail_payload, "latest")) + .await + .expect_err("validation=true must reject when balance omits Curie blob L1 fee"); + let err_str = err.to_string(); + assert!( + err_str.contains("insufficient funds") || err_str.contains("-38014"), + "expected insufficient funds error, got: {err_str}" + ); + + // (2) Balance covers exact `l2_max_fee + full_l1_fee`: must succeed and deduct exact + // `l2_used_fee + full_l1_fee` from sender and credit the same amount to FeeVault. + let exact_budget = l2_max_fee + full_l1_fee; + let pass_payload = serde_json::json!({ + "blockStateCalls": [{ + "stateOverrides": { + sender.to_string(): { + "balance": format!("{exact_budget:#x}"), + }, + reader_addr.to_string(): { + "code": DUAL_BALANCE_READER_CODE, + }, + }, + "calls": [ + tx_call, + // Executed immediately after Call 0 commits and BEFORE Call 1's own + // `reward_beneficiary` runs, so it observes exact post-Call-0 balances + // of both `sender` and `FEE_VAULT`. + { + "from": funded_wallet, + "to": reader_addr, + "gas": "0x186a0", + "maxFeePerGas": format!("{max_fee_per_gas:#x}"), + "maxPriorityFeePerGas": format!("{max_priority_fee_per_gas:#x}"), + "input": encode_two_address_words(sender, FEE_VAULT), + }, + ], + }], + "validation": true, + }); + let blocks: Value = client + .request("eth_simulateV1", (pass_payload, "latest")) + .await?; + let block = &blocks[0]; + let calls = block["calls"].as_array().expect("calls array"); + assert_eq!(calls[0]["status"].as_str(), Some("0x1")); + assert_eq!(calls[1]["status"].as_str(), Some("0x1")); + + let block_base_fee = u128::from_str_radix( + block["baseFeePerGas"] + .as_str() + .unwrap() + .trim_start_matches("0x"), + 16, + )?; + let gas_used = u64::from_str_radix( + calls[0]["gasUsed"] + .as_str() + .unwrap() + .trim_start_matches("0x"), + 16, + )?; + let effective_gas_price = max_fee_per_gas.min(block_base_fee + max_priority_fee_per_gas); + let expected_total_fee = U256::from(gas_used) * U256::from(effective_gas_price) + full_l1_fee; + + let (sender_balance_after, vault_balance_after) = + decode_two_u256_words(calls[1]["returnData"].as_str().unwrap()); + assert_eq!( + sender_balance_after, + exact_budget - expected_total_fee, + "sender must be charged exact L2 execution fee + full Curie (commit + blob) L1 fee" + ); + assert_eq!( + vault_balance_after, + initial_vault_balance + expected_total_fee, + "FeeVault must receive exact L2 execution fee + full Curie (commit + blob) L1 fee" + ); + + // (3) Token-fee MorphTx under `validation: true`: a `feeLimit` that only covers + // L2 (`gas_limit * effective_gas_price`) + commit-only L1 fee (+ half the blob fee) + // must fail, while covering full Curie L1 + L2 succeeds and emits the call-mode + // ERC-20 `Transfer` fee log(s). (Genesis token ID 1 has 1:1 price_ratio == scale == 1e18.) + let l2_effective_max_fee = U256::from(gas_limit) * U256::from(effective_gas_price); + let token_tight_limit = l2_effective_max_fee + + commit_only_l1_fee + + (full_l1_fee - commit_only_l1_fee) / U256::from(2u64); + let morph_fail_payload = serde_json::json!({ + "blockStateCalls": [{ + "calls": [{ + "from": funded_wallet, + "to": recipient, + "gas": format!("{gas_limit:#x}"), + "maxFeePerGas": format!("{max_fee_per_gas:#x}"), + "maxPriorityFeePerGas": format!("{max_priority_fee_per_gas:#x}"), + "feeTokenID": format!("{TEST_TOKEN_ID:#x}"), + "feeLimit": format!("{token_tight_limit:#x}"), + "input": calldata.to_string(), + }], + }], + "validation": true, + }); + client + .request::("eth_simulateV1", (morph_fail_payload, "latest")) + .await + .expect_err("token-fee MorphTx must fail under validation=true when feeLimit omits Curie blob L1 fee"); + + let token_generous_limit = l2_max_fee + full_l1_fee * U256::from(2u64); + let morph_pass_payload = serde_json::json!({ + "blockStateCalls": [{ + "calls": [{ + "from": funded_wallet, + "to": recipient, + "gas": format!("{gas_limit:#x}"), + "maxFeePerGas": format!("{max_fee_per_gas:#x}"), + "maxPriorityFeePerGas": format!("{max_priority_fee_per_gas:#x}"), + "feeTokenID": format!("{TEST_TOKEN_ID:#x}"), + "feeLimit": format!("{token_generous_limit:#x}"), + "input": calldata.to_string(), + }], + }], + "validation": true, + }); + let morph_blocks: Value = client + .request("eth_simulateV1", (morph_pass_payload, "latest")) + .await?; + let morph_call = &morph_blocks[0]["calls"][0]; + assert_eq!(morph_call["status"].as_str(), Some("0x1")); + let transfer_topic = "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"; + let logs = morph_call["logs"].as_array().expect("logs array"); + assert!( + logs.iter().any(|log| { + log["topics"] + .as_array() + .and_then(|t| t.first()) + .and_then(Value::as_str) + == Some(transfer_topic) + }), + "validated call-mode token-fee MorphTx must emit ERC-20 Transfer fee logs: {logs:?}" + ); + + Ok(()) +} diff --git a/crates/node/tests/it/txpool.rs b/crates/node/tests/it/txpool.rs index 72e79c41..e7c2d5f1 100644 --- a/crates/node/tests/it/txpool.rs +++ b/crates/node/tests/it/txpool.rs @@ -339,39 +339,116 @@ async fn tx_gas_limit_below_eip7623_floor_is_mined() -> eyre::Result<()> { Ok(()) } -#[tokio::test(flavor = "multi_thread")] -async fn tx_max_fee_below_base_fee_accepted_for_queuing() -> eyre::Result<()> { - reth_tracing::init_test_tracing(); - let (mut nodes, wallet) = TestNodeBuilder::new().build().await?; - let node = nodes.pop().unwrap(); - +/// Helper to sign and 2718-encode a simple EIP-1559 transfer with custom fees. +fn sign_eip1559_transfer( + chain_id: u64, + signer: &alloy_signer_local::PrivateKeySigner, + nonce: u64, + max_fee_per_gas: u128, + max_priority_fee_per_gas: u128, +) -> eyre::Result { use alloy_consensus::{SignableTransaction, TxEip1559}; use alloy_signer::SignerSync; + let tx = TxEip1559 { - chain_id: wallet.chain_id, - nonce: 0, + chain_id, + nonce, gas_limit: 21_000, - max_fee_per_gas: 500_000u128, // below base fee of 1_000_000 - max_priority_fee_per_gas: 500_000u128, - to: alloy_primitives::TxKind::Call(alloy_primitives::Address::with_last_byte(0x42)), - value: alloy_primitives::U256::from(100), + max_fee_per_gas, + max_priority_fee_per_gas, + to: TxKind::Call(Address::with_last_byte(0x42)), + value: U256::from(100), access_list: Default::default(), - input: alloy_primitives::Bytes::new(), + input: Bytes::new(), }; - let sig = wallet - .inner + let sig = signer .sign_hash_sync(&tx.signature_hash()) .map_err(|e| eyre::eyre!("{e}"))?; - let envelope = morph_primitives::MorphTxEnvelope::Eip1559(tx.into_signed(sig)); - use alloy_eips::eip2718::Encodable2718; - let raw: alloy_primitives::Bytes = envelope.encoded_2718().into(); + let envelope = MorphTxEnvelope::Eip1559(tx.into_signed(sig)); + Ok(envelope.encoded_2718().into()) +} + +#[tokio::test(flavor = "multi_thread")] +async fn tx_max_fee_below_morph_base_fee_rejected_by_default() -> eyre::Result<()> { + use jsonrpsee::core::client::ClientT; + + reth_tracing::init_test_tracing(); + let (mut nodes, wallet) = TestNodeBuilder::new().build().await?; + let mut node = nodes.pop().unwrap(); + + let below_floor = sign_eip1559_transfer( + wallet.chain_id, + &wallet.inner, + 0, + morph_chainspec::MORPH_BASE_FEE as u128 - 1, + 0, + )?; + + // Morph fixes L2 baseFee at MORPH_BASE_FEE (1_000_000 wei), so transactions + // below it can never be mined and must be rejected outright rather than + // parked in basefee_pool (where they would also inflate pending nonces). + let err = node + .rpc + .inject_tx(below_floor) + .await + .expect_err("tx with maxFeePerGas < MORPH_BASE_FEE must be rejected by default"); + let err_msg = err.to_string().to_lowercase(); + assert!( + err_msg.contains("underpriced") || err_msg.contains("below chain minimum"), + "expected underpriced/below-minimum error, got: {err}" + ); + + // Pending nonce must remain clean (0) after the rejection. + let client = node + .rpc_client() + .ok_or_else(|| eyre::eyre!("HTTP RPC client not available"))?; + let pending_nonce: U256 = client + .request( + "eth_getTransactionCount", + (wallet.inner.address(), "pending"), + ) + .await?; + assert_eq!( + pending_nonce, + U256::ZERO, + "rejected sub-basefee tx must not inflate eth_getTransactionCount(\"pending\")" + ); + + // Exact MORPH_BASE_FEE with zero priority fee must still be accepted and mined. + let at_floor = sign_eip1559_transfer( + wallet.chain_id, + &wallet.inner, + 0, + morph_chainspec::MORPH_BASE_FEE as u128, + 0, + )?; + node.rpc.inject_tx(at_floor).await?; + let payload = node.advance_block().await?; + assert_eq!( + payload.block().body().transactions.len(), + 1, + "tx with maxFeePerGas == MORPH_BASE_FEE should be included" + ); + + Ok(()) +} + +#[tokio::test(flavor = "multi_thread")] +async fn tx_max_fee_below_base_fee_accepted_when_minimal_protocol_fee_lowered() -> eyre::Result<()> +{ + reth_tracing::init_test_tracing(); + // Simulates operators passing `--txpool.minimal-protocol-fee 7`. + let (mut nodes, wallet) = TestNodeBuilder::new() + .with_minimal_protocol_basefee(7) + .build() + .await?; + let node = nodes.pop().unwrap(); - // reth pools low-fee txs for future execution when baseFee drops, - // so they are accepted into the queued set, not rejected outright. + let raw = sign_eip1559_transfer(wallet.chain_id, &wallet.inner, 0, 500_000, 500_000)?; let result = node.rpc.inject_tx(raw).await; assert!( result.is_ok(), - "tx with maxFeePerGas < baseFee should be accepted for queuing" + "tx with maxFeePerGas < baseFee should be accepted when minimal_protocol_basefee is lowered" ); Ok(()) } diff --git a/crates/payload/builder/Cargo.toml b/crates/payload/builder/Cargo.toml index 11def200..a217f79b 100644 --- a/crates/payload/builder/Cargo.toml +++ b/crates/payload/builder/Cargo.toml @@ -50,6 +50,8 @@ tracing.workspace = true thiserror.workspace = true [dev-dependencies] +morph-txpool.workspace = true +reth-trie-common.workspace = true [features] default = [] diff --git a/crates/payload/builder/src/builder.rs b/crates/payload/builder/src/builder.rs index 0c3ebdc5..c07e1281 100644 --- a/crates/payload/builder/src/builder.rs +++ b/crates/payload/builder/src/builder.rs @@ -2,17 +2,22 @@ use crate::metrics::MorphPayloadBuilderMetrics; use crate::{MorphBuilderConfig, MorphPayloadBuilderError, config::PayloadBuildingBreaker}; -use alloy_consensus::{BlockHeader, Transaction, Typed2718}; +use alloy_consensus::{BlockHeader, Transaction, Typed2718, transaction::TxHashRef}; use alloy_eips::eip2718::Encodable2718; -use alloy_primitives::{B256, Bytes, U256}; -use evm2::{DatabaseError, evm::State}; -use morph_chainspec::MorphChainSpec; -use morph_chainspec::{L2_MESSAGE_QUEUE_ADDRESS, L2_MESSAGE_QUEUE_WITHDRAW_TRIE_ROOT_SLOT}; -use morph_evm::{MorphEvmConfig, MorphNextBlockEnvAttributes}; +use alloy_primitives::{Address, B256, Bytes, U256}; +use evm2::{DatabaseError, evm::State, registry::HandlerError}; +use morph_chainspec::{ + L2_MESSAGE_QUEUE_ADDRESS, L2_MESSAGE_QUEUE_WITHDRAW_TRIE_ROOT_SLOT, MorphChainSpec, + MorphHardforks, +}; +use morph_evm::{MorphEvmConfig, MorphInvalidTransaction, MorphNextBlockEnvAttributes}; use morph_payload_types::{ ExecutableL2Data, MorphBuiltPayload, MorphPayloadAttributes, MorphPayloadBuilderAttributes, }; -use morph_primitives::{MorphHeader, MorphTxEnvelope}; +use morph_primitives::{ + MorphHeader, MorphTxEnvelope, + transaction::morph_transaction::{MORPH_TX_VERSION_1, MORPH_TX_VERSION_2}, +}; use reth_basic_payload_builder::{ BuildArguments, BuildOutcome, BuildOutcomeKind, MissingPayloadBehaviour, PayloadBuilder, PayloadConfig, is_better_payload, @@ -20,7 +25,8 @@ use reth_basic_payload_builder::{ use reth_chainspec::ChainSpecProvider; use reth_evm::{ BlockBuilder, BlockBuilderOutcome, BlockExecutionError, BlockValidationError, ConfigureEvm, - Database, EvmEnv as _, NextBlockEnvAttributes, OnStateHook, database::StateProviderDatabase, + Database, EvmEnv as _, InvalidTxError, NextBlockEnvAttributes, OnStateHook, + database::StateProviderDatabase, }; use reth_execution_cache::{CachedStateMetrics, CachedStateMetricsSource, CachedStateProvider}; use reth_execution_types::BlockExecutionOutput; @@ -31,8 +37,63 @@ use reth_primitives_traits::{FastInstant as Instant, RecoveredBlock, SealedHeade use reth_storage_api::{EvmStateProvider, StateProvider, StateProviderFactory}; use reth_tasks::CancelOnDrop; use reth_transaction_pool::{BestTransactionsAttributes, PoolTransaction, TransactionPool}; +use std::collections::HashSet; use std::sync::Arc; +/// Returns true when `error` wraps a deterministic Morph token-fee error that cannot +/// succeed without an on-chain configuration or token-contract state change, so a failing +/// pool transaction should be evicted rather than left in `Pending` to burn up to 200k gas +/// on every subsequent block-building tick. +/// +/// Explicitly excludes [`MorphInvalidTransaction::InsufficientTokenBalance`], which is a +/// normal balance shortfall (and may be caused by an earlier transaction in the same block). +fn is_evictable_token_fee_error(error: &dyn InvalidTxError) -> bool { + let Some(morph_err) = error + .as_any() + .downcast_ref::() + .and_then(|err| err.external_ref::()) + .or_else(|| error.as_any().downcast_ref::()) + else { + return false; + }; + matches!( + morph_err, + MorphInvalidTransaction::TokenTransferFailed { .. } + | MorphInvalidTransaction::TokenBalanceQueryFailed + | MorphInvalidTransaction::TokenNotRegistered(_) + | MorphInvalidTransaction::TokenNotActive(_) + | MorphInvalidTransaction::InvalidTokenConfig(_) + ) +} + +/// Validates MorphTx (0x7F) hardfork activation gates and structural field rules against +/// the target block timestamp, matching `MorphConsensus::validate_block_pre_execution`. +fn validate_morph_tx_for_block( + tx: &MorphTxEnvelope, + chain_spec: &MorphChainSpec, + block_timestamp: u64, +) -> Result<(), String> { + let MorphTxEnvelope::Morph(signed) = tx else { + return Ok(()); + }; + let morph_tx = signed.tx(); + + if !chain_spec.is_emerald_active_at_timestamp(block_timestamp) { + return Err("MorphTx type is not yet active (emerald fork not reached)".into()); + } + if !chain_spec.is_jade_active_at_timestamp(block_timestamp) + && morph_tx.version == MORPH_TX_VERSION_1 + { + return Err("MorphTx version 1 is not yet active (jade fork not reached)".into()); + } + if !chain_spec.is_celadon_active_at_timestamp(block_timestamp) + && morph_tx.version == MORPH_TX_VERSION_2 + { + return Err("MorphTx version 2 is not yet active (celadon fork not reached)".into()); + } + morph_tx.validate().map_err(str::to_string) +} + /// Reads the withdraw trie root from the L2MessageQueue contract storage. fn read_withdraw_trie_root(state: &mut State<'_>) -> Result { let value = state.storage_slot_untracked( @@ -233,6 +294,7 @@ where build_payload_inner( cached_reads.as_db_mut(state), state_provider.as_ref(), + &self.pool, ctx, best, state_root_handle, @@ -377,21 +439,55 @@ impl MorphPayloadBuilderCtx { )); } - // L1 messages must precede every L2 transaction. Consensus rejects a violation - // post-execution (`validate_l1_messages_in_block`), but under a deterministic - // build the supplied list may legitimately contain L2 transactions, so catching - // the bad ordering here fails fast and names the actual problem — the caller's - // transaction list — instead of surfacing it as a block validation error after - // the whole block has been executed. - if recovered_tx.is_l1_msg() { + // L1 messages must precede every L2 transaction and carry strictly sequential + // queue indices. Validate ordering, queue index, overflow, and MorphTx hardfork / + // structural gates *before* EVM execution so invalid supplied transactions are + // rejected cleanly without mutating block state. + let is_l1_msg = recovered_tx.is_l1_msg(); + let next_l1_message_index = if is_l1_msg { if saw_l2_transaction { return Err(PayloadBuilderError::other( MorphPayloadBuilderError::L1MessageAfterRegularTx, )); } + let queue_index = recovered_tx.queue_index().ok_or_else(|| { + PayloadBuilderError::other( + MorphPayloadBuilderError::InvalidSuppliedTransaction { + error: "L1 message transaction is missing queue index".to_string(), + }, + ) + })?; + if queue_index != info.next_l1_message_index { + return Err(PayloadBuilderError::other( + MorphPayloadBuilderError::InvalidSuppliedTransaction { + error: format!( + "invalid L1 message queue index: expected {}, got {}", + info.next_l1_message_index, queue_index + ), + }, + )); + } + let next_index = queue_index.checked_add(1).ok_or_else(|| { + PayloadBuilderError::other( + MorphPayloadBuilderError::InvalidSuppliedTransaction { + error: format!("L1 message queue index overflow: {queue_index}"), + }, + ) + })?; + Some(next_index) } else { saw_l2_transaction = true; - } + if let Err(reason) = validate_morph_tx_for_block( + recovered_tx.inner(), + self.evm_config.chain_spec(), + self.attributes().timestamp, + ) { + return Err(PayloadBuilderError::other( + MorphPayloadBuilderError::InvalidSuppliedTransaction { error: reason }, + )); + } + None + }; let tx_gas = recovered_tx.gas_limit(); @@ -491,24 +587,10 @@ impl MorphPayloadBuilderCtx { .commit_tx_apply_duration_seconds .record(apply_started.elapsed()); - // For L1 messages, track the next L1 message index. + // For L1 messages, advance the next L1 message index. // L1 gas is prepaid on L1, so no fees are collected here. - let is_l1_msg = recovered_tx.is_l1_msg(); - if is_l1_msg { - // Ensure the queue index is strictly sequential - if let Some(queue_index) = recovered_tx.queue_index() { - if queue_index != info.next_l1_message_index { - return Err(PayloadBuilderError::other( - MorphPayloadBuilderError::InvalidSuppliedTransaction { - error: format!( - "invalid L1 message queue index: expected {}, got {}", - info.next_l1_message_index, queue_index - ), - }, - )); - } - info.next_l1_message_index = queue_index + 1; - } + if let Some(next_index) = next_l1_message_index { + info.next_l1_message_index = next_index; } else { // Calculate fees for L2 transactions: effective_tip * gas_used let effective_tip = recovered_tx @@ -536,13 +618,39 @@ impl MorphPayloadBuilderCtx { /// /// Returns `Ok(Some(()))` if the job was cancelled or breaker triggered, `Ok(None)` otherwise. /// Executed transaction bytes are appended to the provided vector. - fn execute_pool_transactions( + fn execute_pool_transactions( + &self, + builder: &mut impl BlockBuilder, + info: &mut ExecutionInfo, + executed_txs: &mut Vec, + best_txs: BestTxs, + pool: &Pool, + breaker: &PayloadBuildingBreaker, + ) -> Result, PayloadBuilderError> + where + BestTxs: PayloadTransactions>, + Pool: TransactionPool>, + { + self.execute_pool_transactions_with_evictor( + builder, + info, + executed_txs, + best_txs, + breaker, + |tx_hash| { + pool.remove_transactions(vec![tx_hash]); + }, + ) + } + + fn execute_pool_transactions_with_evictor( &self, builder: &mut impl BlockBuilder, info: &mut ExecutionInfo, executed_txs: &mut Vec, mut best_txs: BestTxs, breaker: &PayloadBuildingBreaker, + mut evict_from_pool: impl FnMut(B256), ) -> Result, PayloadBuilderError> where BestTxs: PayloadTransactions>, @@ -553,6 +661,7 @@ impl MorphPayloadBuilderCtx { .gas_limit .saturating_to::(); let base_fee = builder.evm_env().block_base_fee(); + let mut executed_senders: HashSet
= HashSet::new(); while let Some(tx) = best_txs.next(()) { // Check if the job was cancelled. This must stay `is_cancelled`: `is_interrupted` @@ -596,6 +705,26 @@ impl MorphPayloadBuilderCtx { continue; } + // Enforce MorphTx hardfork gates and structural validation against the target + // block's timestamp (a reorg build via assembleL2BlockV2 may target an older + // fork than the canonical head at which the pool admitted the tx). + if let Err(reason) = validate_morph_tx_for_block( + tx.inner(), + self.evm_config.chain_spec(), + self.attributes().timestamp, + ) { + tracing::debug!( + target: "payload_builder", + signer = %tx.signer(), + nonce = tx.nonce(), + block_timestamp = self.attributes().timestamp, + %reason, + "skipping pool MorphTx invalid for target block timestamp" + ); + best_txs.mark_invalid(tx.signer(), tx.nonce()); + continue; + } + // Skip transactions that cannot fit in remaining block gas or DA size. let tx_size = tx.encode_2718_len() as u64; if info.is_tx_over_limits(tx.gas_limit(), tx_size, block_gas_limit) { @@ -644,6 +773,19 @@ impl MorphPayloadBuilderCtx { "skipping invalid transaction and its descendants" ); best_txs.mark_invalid(tx.signer(), tx.nonce()); + if is_evictable_token_fee_error(error.as_ref()) + && !executed_senders.contains(&tx.signer()) + { + tracing::debug!( + target: "payload_builder", + tx_hash = %tx.tx_hash(), + signer = %tx.signer(), + nonce = tx.nonce(), + %error, + "evicting pool transaction after deterministic token-fee failure" + ); + evict_from_pool(*tx.tx_hash()); + } } continue; } @@ -673,6 +815,7 @@ impl MorphPayloadBuilderCtx { self.metrics .commit_tx_apply_duration_seconds .record(apply_started.elapsed()); + executed_senders.insert(tx.signer()); // Update execution info info.cumulative_gas_used += gas_used; @@ -756,9 +899,10 @@ impl ExecutionInfo { } /// Builds the payload on top of the state. -fn build_payload_inner<'a, DB, BestTxs>( +fn build_payload_inner<'a, DB, BestTxs, Pool>( db: DB, state_provider: &(impl StateProvider + ?Sized), + pool: &Pool, ctx: MorphPayloadBuilderCtx, best: impl FnOnce(BestTransactionsAttributes) -> BestTxs + Send + Sync + 'a, mut state_root_handle: Option, @@ -766,6 +910,7 @@ fn build_payload_inner<'a, DB, BestTxs>( where DB: Database + 'a, BestTxs: PayloadTransactions> + 'a, + Pool: TransactionPool>, { let build_started = Instant::now(); let attributes = ctx.attributes(); @@ -849,6 +994,7 @@ where &mut info, &mut executed_txs, best_txs, + pool, &breaker, )? .is_some() @@ -1277,4 +1423,656 @@ mod tests { let root = read_withdraw_trie_root(&mut state).unwrap(); assert_eq!(root, B256::from(U256::MAX)); } + + // ========================================================================= + // Shared scripted test helpers for M-H09, M-H10, and M-M12 + // ========================================================================= + + /// Mirrors `morph_evm::block::MorphInvalidTxError`: wraps [`HandlerError`] and exposes it + /// via `as_any()` so `is_evictable_token_fee_error` exercises the real production downcast. + #[derive(Debug)] + struct TestInvalidTxError(HandlerError); + + impl core::fmt::Display for TestInvalidTxError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + self.0.fmt(f) + } + } + + impl core::error::Error for TestInvalidTxError {} + + impl InvalidTxError for TestInvalidTxError { + fn is_nonce_too_low(&self) -> bool { + matches!(self.0, HandlerError::InvalidNonce { expected, got } if got < expected) + } + + fn is_gas_limit_too_high(&self) -> bool { + matches!( + self.0, + HandlerError::GasLimitMoreThanBlock { .. } + | HandlerError::TxGasLimitGreaterThanCap { .. } + | HandlerError::IntrinsicGasGreaterThanCap { .. } + ) + } + + fn is_gas_limit_too_low(&self) -> bool { + matches!( + self.0, + HandlerError::IntrinsicGasTooLow { .. } | HandlerError::GasLimitBelowFloor { .. } + ) + } + + fn as_any(&self) -> &(dyn std::any::Any + 'static) { + &self.0 + } + } + + struct ScriptedBlockBuilder { + evm_env: morph_evm::MorphEvmEnv, + outcomes: std::collections::HashMap>, + executed_count: usize, + } + + impl ScriptedBlockBuilder { + fn new(outcomes: std::collections::HashMap>) -> Self { + let header = MorphHeader { + inner: alloy_consensus::Header { + gas_limit: 30_000_000, + base_fee_per_gas: Some(1), + timestamp: 1_800_000_000, + ..Default::default() + }, + ..Default::default() + }; + let evm_env = test_evm_config().evm_env(&header).expect("evm_env"); + Self { + evm_env, + outcomes, + executed_count: 0, + } + } + } + + impl BlockBuilder for ScriptedBlockBuilder { + type Primitives = morph_primitives::MorphPrimitives; + type Executor = morph_evm::MorphBlockExecutor<'static>; + type EvmEnv = morph_evm::MorphEvmEnv; + + fn evm_env(&self) -> &Self::EvmEnv { + &self.evm_env + } + + fn apply_pre_execution_changes(&mut self) -> Result<(), BlockExecutionError> { + Ok(()) + } + + fn execute_transaction_with_commit_condition( + &mut self, + tx: impl reth_evm::ExecutorTx, + _f: impl FnOnce( + &evm2::TxResult, + evm2::TxStateChanges<'_>, + ) -> reth_evm::CommitChanges, + ) -> Result, BlockExecutionError> { + use reth_evm::RecoveredTx as _; + self.executed_count += 1; + let (_tx_env, recovered) = tx.into_parts(); + let hash = *recovered.tx().tx_hash(); + match self.outcomes.remove(&hash).expect("scripted outcome") { + Ok(gas_used) => Ok(Some(reth_evm::GasOutput::new(gas_used, 0))), + Err(err) => Err(BlockExecutionError::Validation( + BlockValidationError::InvalidTx { + hash, + error: Box::new(TestInvalidTxError(err)), + }, + )), + } + } + + fn execute_transaction_with_result_closure( + &mut self, + _tx: impl reth_evm::ExecutorTx, + _f: impl FnOnce(&morph_evm::MorphTxResult), + ) -> Result { + unreachable!() + } + + fn finish_with_state_root( + self, + _state_provider: impl StateProvider, + _state_root: impl FnOnce( + &BlockExecutionOutput, + ) -> Result< + Option<(B256, reth_trie_common::updates::TrieUpdates)>, + BlockExecutionError, + >, + ) -> Result, BlockExecutionError> { + unreachable!() + } + + fn executor_mut(&mut self) -> &mut Self::Executor { + unreachable!() + } + + fn executor(&self) -> &Self::Executor { + unreachable!() + } + + fn into_executor(self) -> Self::Executor { + unreachable!() + } + } + + struct ScriptedPoolTxs { + txs: std::collections::VecDeque, + marked_invalid: Vec<(Address, u64)>, + } + + impl PayloadTransactions for ScriptedPoolTxs { + type Transaction = morph_txpool::MorphPooledTransaction; + + fn next(&mut self, _ctx: ()) -> Option { + self.txs.pop_front() + } + + fn mark_invalid(&mut self, sender: Address, nonce: u64) { + self.marked_invalid.push((sender, nonce)); + } + } + + fn test_ctx_with_timestamp_and_txs( + timestamp: u64, + transactions: Vec, + ) -> MorphPayloadBuilderCtx { + let mut rpc_attrs = morph_payload_types::MorphPayloadAttributes::default(); + rpc_attrs.inner.timestamp = timestamp; + rpc_attrs.transactions = Some(transactions); + let attrs = MorphPayloadBuilderAttributes::try_new( + B256::ZERO, + rpc_attrs, + morph_payload_types::MORPH_PAYLOAD_BUILDER_VERSION, + ) + .unwrap(); + let payload_id = attrs.payload_id(); + MorphPayloadBuilderCtx { + evm_config: test_evm_config(), + config: PayloadConfig::new( + Arc::new(SealedHeader::seal_slow(MorphHeader::default())), + attrs, + payload_id, + ), + cancel: Default::default(), + best_payload: None, + builder_config: MorphBuilderConfig::default(), + metrics: MorphPayloadBuilderMetrics::default(), + } + } + + // ========================================================================= + // M-H09: Pre-execution queue_index validation & overflow protection tests + // ========================================================================= + + #[test] + fn test_execute_supplied_transactions_rejects_bad_queue_index_before_execution() { + use alloy_consensus::Sealable; + use morph_primitives::TxL1Msg; + + let l1_msg = TxL1Msg { + queue_index: 5, + gas_limit: 50_000, + to: Address::repeat_byte(0xaa), + value: U256::ZERO, + sender: Address::repeat_byte(0xbb), + input: Bytes::new(), + }; + let encoded = Bytes::from(MorphTxEnvelope::L1Msg(l1_msg.seal_slow()).encoded_2718()); + let ctx = test_ctx_with_timestamp_and_txs(1_800_000_000, vec![encoded]); + let mut builder = ScriptedBlockBuilder::new(std::collections::HashMap::new()); + let mut info = ExecutionInfo::new(0, None); + + let err = ctx + .execute_supplied_transactions(&mut builder, &mut info) + .expect_err("non-sequential queue_index must be rejected"); + assert!( + err.to_string() + .contains("invalid L1 message queue index: expected 0, got 5"), + "unexpected error: {err}" + ); + assert_eq!( + builder.executed_count, 0, + "bad queue_index must be rejected before EVM execution" + ); + } + + #[test] + fn test_execute_supplied_transactions_rejects_queue_index_overflow() { + use alloy_consensus::Sealable; + use morph_primitives::TxL1Msg; + + let l1_msg = TxL1Msg { + queue_index: u64::MAX, + gas_limit: 50_000, + to: Address::repeat_byte(0xaa), + value: U256::ZERO, + sender: Address::repeat_byte(0xbb), + input: Bytes::new(), + }; + let encoded = Bytes::from(MorphTxEnvelope::L1Msg(l1_msg.seal_slow()).encoded_2718()); + let ctx = test_ctx_with_timestamp_and_txs(1_800_000_000, vec![encoded]); + let mut builder = ScriptedBlockBuilder::new(std::collections::HashMap::new()); + let mut info = ExecutionInfo::new(u64::MAX, None); + + let err = ctx + .execute_supplied_transactions(&mut builder, &mut info) + .expect_err("u64::MAX queue_index overflow must be rejected cleanly"); + assert!( + err.to_string().contains("queue index overflow"), + "unexpected error: {err}" + ); + assert_eq!( + builder.executed_count, 0, + "overflowing queue_index must be rejected before EVM execution" + ); + } + + // ========================================================================= + // M-H10: MorphTx hardfork & structural validation tests + // ========================================================================= + + #[test] + fn test_validate_morph_tx_for_block_enforces_hardfork_gates_and_validate() { + use alloy_consensus::Signed; + use alloy_primitives::{Signature, TxKind}; + use morph_primitives::TxMorph; + + let chain_spec = morph_chainspec::MORPH_MAINNET.as_ref(); + // Mainnet fork timestamps: emerald=1767765600, jade=1775628000, celadon=1793772000 + let pre_emerald = 1_767_765_599; + let pre_jade = 1_775_627_999; + let pre_celadon = 1_793_771_999; + let celadon = 1_793_772_000; + + let wrap = |tx: TxMorph| { + MorphTxEnvelope::Morph(Signed::new_unchecked( + tx, + Signature::test_signature(), + B256::repeat_byte(0x01), + )) + }; + + let v0 = wrap(TxMorph { + chain_id: 2818, + gas_limit: 50_000, + max_fee_per_gas: 100, + max_priority_fee_per_gas: 10, + to: TxKind::Call(Address::repeat_byte(0xee)), + fee_token_id: 1, + version: 0, + ..Default::default() + }); + let v1 = wrap(TxMorph { + chain_id: 2818, + gas_limit: 50_000, + max_fee_per_gas: 100, + max_priority_fee_per_gas: 10, + to: TxKind::Call(Address::repeat_byte(0xee)), + fee_token_id: 0, + version: MORPH_TX_VERSION_1, + ..Default::default() + }); + let v2 = wrap(TxMorph { + chain_id: 2818, + gas_limit: 50_000, + max_fee_per_gas: 100, + max_priority_fee_per_gas: 10, + to: TxKind::Call(Address::repeat_byte(0xee)), + fee_token_id: 0, + version: MORPH_TX_VERSION_2, + ..Default::default() + }); + let bad_v1_fee_limit = wrap(TxMorph { + chain_id: 2818, + gas_limit: 50_000, + max_fee_per_gas: 100, + max_priority_fee_per_gas: 10, + to: TxKind::Call(Address::repeat_byte(0xee)), + fee_token_id: 0, + fee_limit: U256::from(100), + version: MORPH_TX_VERSION_1, + ..Default::default() + }); + + // Pre-Emerald rejects every MorphTx version. + assert!(validate_morph_tx_for_block(&v0, chain_spec, pre_emerald).is_err()); + assert!(validate_morph_tx_for_block(&v1, chain_spec, pre_emerald).is_err()); + assert!(validate_morph_tx_for_block(&v2, chain_spec, pre_emerald).is_err()); + + // Emerald (pre-Jade) permits V0, rejects V1 & V2. + assert!(validate_morph_tx_for_block(&v0, chain_spec, pre_jade).is_ok()); + assert!(validate_morph_tx_for_block(&v1, chain_spec, pre_jade).is_err()); + assert!(validate_morph_tx_for_block(&v2, chain_spec, pre_jade).is_err()); + + // Jade (pre-Celadon) permits V0 & V1, rejects V2. + assert!(validate_morph_tx_for_block(&v0, chain_spec, pre_celadon).is_ok()); + assert!(validate_morph_tx_for_block(&v1, chain_spec, pre_celadon).is_ok()); + assert!(validate_morph_tx_for_block(&v2, chain_spec, pre_celadon).is_err()); + + // Celadon permits V2, but structural `TxMorph::validate()` still rejects bad fields. + assert!(validate_morph_tx_for_block(&v2, chain_spec, celadon).is_ok()); + assert!(validate_morph_tx_for_block(&bad_v1_fee_limit, chain_spec, celadon).is_err()); + } + + #[test] + fn test_execute_pool_transactions_skips_pre_celadon_v2_without_executing_or_evicting() { + use alloy_consensus::Signed; + use alloy_primitives::{Signature, TxKind}; + use morph_primitives::TxMorph; + use morph_txpool::MorphPooledTransaction; + use reth_primitives_traits::Recovered; + + let sender_v2 = Address::repeat_byte(0x11); + let sender_v1 = Address::repeat_byte(0x22); + + let v2_tx = TxMorph { + chain_id: 2818, + nonce: 0, + gas_limit: 50_000, + max_fee_per_gas: 100, + max_priority_fee_per_gas: 10, + to: TxKind::Call(Address::repeat_byte(0xee)), + fee_token_id: 0, + version: MORPH_TX_VERSION_2, + ..Default::default() + }; + let v2_hash = B256::repeat_byte(0xaa); + let v2_rec = Recovered::new_unchecked( + MorphTxEnvelope::Morph(Signed::new_unchecked( + v2_tx, + Signature::test_signature(), + v2_hash, + )), + sender_v2, + ); + let v2_len = v2_rec.encode_2718_len(); + let v2_pooled = MorphPooledTransaction::new(v2_rec, v2_len); + + let v1_tx = TxMorph { + chain_id: 2818, + nonce: 0, + gas_limit: 50_000, + max_fee_per_gas: 100, + max_priority_fee_per_gas: 10, + to: TxKind::Call(Address::repeat_byte(0xee)), + fee_token_id: 0, + version: MORPH_TX_VERSION_1, + ..Default::default() + }; + let v1_hash = B256::repeat_byte(0xbb); + let v1_rec = Recovered::new_unchecked( + MorphTxEnvelope::Morph(Signed::new_unchecked( + v1_tx, + Signature::test_signature(), + v1_hash, + )), + sender_v1, + ); + let v1_len = v1_rec.encode_2718_len(); + let v1_pooled = MorphPooledTransaction::new(v1_rec, v1_len); + + // Only v1_hash has a scripted outcome; if v2 were executed it would panic. + let mut outcomes = std::collections::HashMap::new(); + outcomes.insert(v1_hash, Ok(21_000)); + let mut builder = ScriptedBlockBuilder::new(outcomes); + let mut info = ExecutionInfo::default(); + let mut executed_txs = Vec::new(); + let best_txs = ScriptedPoolTxs { + txs: std::collections::VecDeque::from([v2_pooled, v1_pooled]), + marked_invalid: Vec::new(), + }; + // Pre-Celadon, post-Jade timestamp on MORPH_MAINNET. + let ctx = test_ctx_with_timestamp_and_txs(1_793_771_999, vec![]); + let breaker = ctx.builder_config.breaker(30_000_000); + let mut evicted = Vec::new(); + + ctx.execute_pool_transactions_with_evictor( + &mut builder, + &mut info, + &mut executed_txs, + best_txs, + &breaker, + |hash| evicted.push(hash), + ) + .expect("pool execution should complete"); + + assert_eq!( + builder.executed_count, 1, + "only V1 should execute; V2 must be skipped pre-Celadon" + ); + assert_eq!(executed_txs.len(), 1); + assert!( + evicted.is_empty(), + "fork-gated skip during reorg build must not evict from pool" + ); + } + + #[test] + fn test_execute_supplied_transactions_rejects_pre_celadon_v2_before_execution() { + use alloy_consensus::Signed; + use alloy_primitives::{Signature, TxKind}; + use morph_primitives::TxMorph; + + let v2_tx = TxMorph { + chain_id: 2818, + nonce: 0, + gas_limit: 50_000, + max_fee_per_gas: 100, + max_priority_fee_per_gas: 10, + to: TxKind::Call(Address::repeat_byte(0xee)), + fee_token_id: 0, + version: MORPH_TX_VERSION_2, + ..Default::default() + }; + let encoded = Bytes::from( + MorphTxEnvelope::Morph(Signed::new_unchecked( + v2_tx, + Signature::test_signature(), + B256::repeat_byte(0xcc), + )) + .encoded_2718(), + ); + // Pre-Celadon timestamp on MORPH_MAINNET. + let ctx = test_ctx_with_timestamp_and_txs(1_793_771_999, vec![encoded]); + let mut builder = ScriptedBlockBuilder::new(std::collections::HashMap::new()); + let mut info = ExecutionInfo::default(); + + let err = ctx + .execute_supplied_transactions(&mut builder, &mut info) + .expect_err("pre-Celadon supplied MorphTx V2 must be rejected"); + assert!( + err.to_string().contains("celadon fork not reached"), + "unexpected error: {err}" + ); + assert_eq!( + builder.executed_count, 0, + "fork-invalid supplied MorphTx must be rejected before EVM execution" + ); + } + + // ========================================================================= + // M-M12: Deterministic token-fee failure pool eviction tests + // ========================================================================= + + #[test] + fn test_is_evictable_token_fee_error_classification() { + let wrap = |err: HandlerError| TestInvalidTxError(err); + + // Deterministic token-fee failures MUST evict. + assert!(is_evictable_token_fee_error(&wrap( + MorphInvalidTransaction::TokenTransferFailed { + reason: "reverted".into(), + } + .into(), + ))); + assert!(is_evictable_token_fee_error(&wrap( + MorphInvalidTransaction::TokenBalanceQueryFailed.into(), + ))); + assert!(is_evictable_token_fee_error(&wrap( + MorphInvalidTransaction::TokenNotRegistered(1).into(), + ))); + assert!(is_evictable_token_fee_error(&wrap( + MorphInvalidTransaction::TokenNotActive(1).into(), + ))); + assert!(is_evictable_token_fee_error(&wrap( + MorphInvalidTransaction::InvalidTokenConfig(1).into(), + ))); + + // InsufficientTokenBalance and standard ETH errors MUST NOT evict. + assert!(!is_evictable_token_fee_error(&wrap( + MorphInvalidTransaction::InsufficientTokenBalance { + required: U256::from(100), + available: U256::from(50), + } + .into(), + ))); + assert!(!is_evictable_token_fee_error(&wrap( + HandlerError::InvalidNonce { + expected: 1, + got: 0, + }, + ))); + assert!(!is_evictable_token_fee_error(&wrap( + HandlerError::InsufficientFunds { + fee: U256::from(100), + balance: U256::ZERO, + }, + ))); + } + + #[test] + fn test_execute_pool_transactions_evicts_only_unexecuted_senders_deterministic_token_errors() { + use alloy_consensus::{Signed, TxEip1559}; + use alloy_primitives::{Signature, TxKind}; + use morph_primitives::TxMorph; + use morph_txpool::MorphPooledTransaction; + use reth_primitives_traits::Recovered; + use std::collections::{HashMap, VecDeque}; + + let make_morph_tx = |signer: Address, nonce: u64, tag: u8| { + let tx = TxMorph { + chain_id: 2818, + nonce, + gas_limit: 50_000, + max_fee_per_gas: 100, + max_priority_fee_per_gas: 10, + to: TxKind::Call(Address::repeat_byte(0xee)), + fee_token_id: 1, + ..Default::default() + }; + let hash = B256::repeat_byte(tag); + let env = MorphTxEnvelope::Morph(Signed::new_unchecked( + tx, + Signature::test_signature(), + hash, + )); + let recovered = Recovered::new_unchecked(env, signer); + let len = recovered.encode_2718_len(); + (hash, MorphPooledTransaction::new(recovered, len)) + }; + + let make_eth_tx = |signer: Address, nonce: u64, tag: u8| { + let tx = TxEip1559 { + chain_id: 2818, + nonce, + gas_limit: 21_000, + max_fee_per_gas: 100, + max_priority_fee_per_gas: 10, + to: TxKind::Call(Address::repeat_byte(0xee)), + ..Default::default() + }; + let hash = B256::repeat_byte(tag); + let env = MorphTxEnvelope::Eip1559(Signed::new_unchecked( + tx, + Signature::test_signature(), + hash, + )); + let recovered = Recovered::new_unchecked(env, signer); + let len = recovered.encode_2718_len(); + (hash, MorphPooledTransaction::new(recovered, len)) + }; + + let sender_blacklisted = Address::repeat_byte(0x01); + let sender_low_bal = Address::repeat_byte(0x02); + let sender_already_executed = Address::repeat_byte(0x03); + let sender_inactive = Address::repeat_byte(0x04); + + let (h_transfer_fail, tx_transfer_fail) = make_morph_tx(sender_blacklisted, 0, 0x11); + let (h_low_bal, tx_low_bal) = make_morph_tx(sender_low_bal, 0, 0x22); + let (h_exec_ok, tx_exec_ok) = make_eth_tx(sender_already_executed, 0, 0x33); + let (h_exec_then_fail, tx_exec_then_fail) = make_morph_tx(sender_already_executed, 1, 0x34); + let (h_inactive, tx_inactive) = make_morph_tx(sender_inactive, 0, 0x44); + + let mut outcomes = HashMap::new(); + outcomes.insert( + h_transfer_fail, + Err(MorphInvalidTransaction::TokenTransferFailed { + reason: "blacklisted".into(), + } + .into()), + ); + outcomes.insert( + h_low_bal, + Err(MorphInvalidTransaction::InsufficientTokenBalance { + required: U256::from(100), + available: U256::from(10), + } + .into()), + ); + outcomes.insert(h_exec_ok, Ok(21_000)); + outcomes.insert( + h_exec_then_fail, + Err(MorphInvalidTransaction::TokenTransferFailed { + reason: "post-tx state change".into(), + } + .into()), + ); + outcomes.insert( + h_inactive, + Err(MorphInvalidTransaction::TokenNotActive(1).into()), + ); + + let mut builder = ScriptedBlockBuilder::new(outcomes); + let mut info = ExecutionInfo::default(); + let mut executed_txs = Vec::new(); + let best_txs = ScriptedPoolTxs { + txs: VecDeque::from([ + tx_transfer_fail, + tx_low_bal, + tx_exec_ok, + tx_exec_then_fail, + tx_inactive, + ]), + marked_invalid: Vec::new(), + }; + // Post-Celadon timestamp so MorphTx hardfork gates pass. + let ctx = test_ctx_with_timestamp_and_txs(1_800_000_000, vec![]); + let breaker = ctx.builder_config.breaker(30_000_000); + let mut evicted = Vec::new(); + + ctx.execute_pool_transactions_with_evictor( + &mut builder, + &mut info, + &mut executed_txs, + best_txs, + &breaker, + |hash| evicted.push(hash), + ) + .expect("pool execution should complete"); + + // Only sender_blacklisted (TokenTransferFailed, unexecuted) and sender_inactive + // (TokenNotActive, unexecuted) should be evicted. + // - sender_low_bal (InsufficientTokenBalance) must NOT be evicted. + // - sender_already_executed nonce 1 (had nonce 0 succeed in this block) must NOT be evicted. + assert_eq!(evicted, vec![h_transfer_fail, h_inactive]); + assert_eq!(executed_txs.len(), 1); + } } diff --git a/crates/reference-index/src/lib.rs b/crates/reference-index/src/lib.rs index d6421c6d..bdeea202 100644 --- a/crates/reference-index/src/lib.rs +++ b/crates/reference-index/src/lib.rs @@ -23,7 +23,7 @@ mod tables; mod types; mod writer; -pub use reader::{ReferenceIndexHandle, ReferenceIndexPhase}; +pub use reader::{ReferenceIndexHandle, ReferenceIndexPhase, ReferenceIndexProgress}; pub use runtime::{ReferenceIndexConfig, ReferenceIndexRuntime}; pub use source::{CanonicalBlock, CanonicalChain}; pub use types::{ diff --git a/crates/reference-index/src/reader.rs b/crates/reference-index/src/reader.rs index b5093a2b..2dd3c8e6 100644 --- a/crates/reference-index/src/reader.rs +++ b/crates/reference-index/src/reader.rs @@ -13,6 +13,7 @@ use std::sync::{ Arc, atomic::{AtomicBool, AtomicU8, Ordering}, }; +use tokio::sync::watch; /// Runtime phase, exported for metrics and logs, and read by the RPC layer only /// to skip its bounded catch-up wait while `Deferred` or `PreJade`. @@ -57,6 +58,29 @@ impl ReferenceIndexPhase { } } +/// Snapshot of reference-index runtime progress published over a +/// [`tokio::sync::watch`] channel so async RPC callers wake on cursor commits, +/// phase transitions, or runtime shutdown without polling. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ReferenceIndexProgress { + /// Current runtime phase. + pub phase: ReferenceIndexPhase, + /// Latest durably committed `IndexedTo` block number observed by the runtime. + pub indexed_to: Option, + /// Whether the runtime has entered the terminal [`ReferenceIndexPhase::Unavailable`] state. + pub unavailable: bool, +} + +impl ReferenceIndexProgress { + const fn opening() -> Self { + Self { + phase: ReferenceIndexPhase::Opening, + indexed_to: None, + unavailable: false, + } + } +} + #[derive(Debug)] struct ReferenceIndexShared { db: RwLock>, @@ -67,6 +91,11 @@ struct ReferenceIndexShared { /// `IndexUnavailable` so clients stop retrying; in every other phase the /// tip comparison decides on its own (`IndexBehind` when the cursor lags). unavailable: AtomicBool, + /// Watch receiver cloned by RPC callers to wait asynchronously for cursor or + /// phase updates. The corresponding [`watch::Sender`] is owned exclusively by + /// [`crate::ReferenceIndexRuntime`] so runtime shutdown drops it and wakes + /// all waiters immediately. + progress_rx: watch::Receiver, metrics: ReferenceIndexMetrics, } @@ -84,17 +113,30 @@ pub struct ReferenceIndexHandle { } impl ReferenceIndexHandle { - /// Create a handle before the background runtime has opened the database. + /// Create a standalone handle without an attached background runtime. + /// + /// Its progress watch channel is immediately closed so async waiters do not + /// stall waiting for a nonexistent writer. pub fn new(jade_timestamp: u64) -> Self { - Self { + let (handle, _tx) = Self::new_with_progress(jade_timestamp); + handle + } + + pub(crate) fn new_with_progress( + jade_timestamp: u64, + ) -> (Self, watch::Sender) { + let (progress_tx, progress_rx) = watch::channel(ReferenceIndexProgress::opening()); + let handle = Self { shared: Arc::new(ReferenceIndexShared { db: RwLock::new(None), phase: AtomicU8::new(ReferenceIndexPhase::Opening as u8), unavailable: AtomicBool::new(false), + progress_rx, metrics: ReferenceIndexMetrics::default(), }), jade_timestamp, - } + }; + (handle, progress_tx) } /// Current in-memory runtime phase, exposed for logs and metrics. @@ -102,6 +144,21 @@ impl ReferenceIndexHandle { ReferenceIndexPhase::from_u8(self.shared.phase.load(Ordering::Acquire)) } + /// Latest runtime progress snapshot (phase, durable cursor height, and + /// unavailable flag). + pub fn progress(&self) -> ReferenceIndexProgress { + let mut progress = *self.shared.progress_rx.borrow(); + progress.phase = self.phase(); + progress.unavailable = self.shared.unavailable.load(Ordering::Acquire); + progress + } + + /// Subscribe to runtime progress updates (cursor commits, phase transitions, + /// `Unavailable`, and runtime shutdown). + pub fn subscribe_progress(&self) -> watch::Receiver { + self.shared.progress_rx.clone() + } + /// Whether a canonical tip at `timestamp` predates Jade. /// /// Before Jade no reference-carrying transaction can exist, so the complete diff --git a/crates/reference-index/src/runtime.rs b/crates/reference-index/src/runtime.rs index cfc83d8a..2ca29c67 100644 --- a/crates/reference-index/src/runtime.rs +++ b/crates/reference-index/src/runtime.rs @@ -2,7 +2,7 @@ use crate::{ CanonicalChain, DEFAULT_BACKFILL_BATCH_BLOCKS, LIVE_LAG_SLO, ReferenceIndexError, - ReferenceIndexHandle, ReferenceIndexPhase, + ReferenceIndexHandle, ReferenceIndexPhase, ReferenceIndexProgress, backfill::{commit_canonical_batch, resolve_jade_first_block}, db::ReferenceIndexDb, reconcile::rollback_suffix, @@ -15,9 +15,12 @@ use std::{ path::{Path, PathBuf}, time::{Duration, Instant}, }; -use tokio::sync::broadcast::{ - Receiver, - error::{RecvError, TryRecvError}, +use tokio::sync::{ + broadcast::{ + Receiver, + error::{RecvError, TryRecvError}, + }, + watch, }; use tokio::time::MissedTickBehavior; use tracing::{debug, info, warn}; @@ -134,22 +137,55 @@ pub struct ReferenceIndexRuntime { config: ReferenceIndexConfig, chain: C, handle: ReferenceIndexHandle, + progress_tx: watch::Sender, } impl ReferenceIndexRuntime { /// Create a single-writer runtime and its cloneable RPC query handle. pub fn new(config: ReferenceIndexConfig, chain: C) -> (Self, ReferenceIndexHandle) { - let handle = ReferenceIndexHandle::new(config.jade_timestamp); + let (handle, progress_tx) = ReferenceIndexHandle::new_with_progress(config.jade_timestamp); ( Self { config, chain, handle: handle.clone(), + progress_tx, }, handle, ) } + fn publish_progress(&self, phase: ReferenceIndexPhase, indexed_to: Option) { + self.handle.set_phase(phase); + let _ = self.progress_tx.send(ReferenceIndexProgress { + phase, + indexed_to, + unavailable: phase == ReferenceIndexPhase::Unavailable, + }); + } + + fn set_phase(&self, phase: ReferenceIndexPhase) { + let current = *self.progress_tx.borrow(); + let changed = current.phase != phase; + self.handle.set_phase(phase); + if changed { + let _ = self.progress_tx.send(ReferenceIndexProgress { + phase, + indexed_to: current.indexed_to, + unavailable: phase == ReferenceIndexPhase::Unavailable, + }); + } + } + + fn set_indexed_to(&self, indexed_to: Option) { + let phase = self.handle.phase(); + let _ = self.progress_tx.send(ReferenceIndexProgress { + phase, + indexed_to, + unavailable: phase == ReferenceIndexPhase::Unavailable, + }); + } + fn open_db(&self) -> Result { if let Some(db) = self.handle.db() { return Ok(db); @@ -159,7 +195,9 @@ impl ReferenceIndexRuntime { self.config.chain_id, self.config.genesis_hash, )?; + let indexed_to = db.indexed_to()?; self.handle.install_db(db.clone()); + self.set_indexed_to(indexed_to); Ok(db) } @@ -187,7 +225,7 @@ impl ReferenceIndexRuntime { return Ok(()); } - self.handle.set_phase(ReferenceIndexPhase::Repairing); + self.set_phase(ReferenceIndexPhase::Repairing); self.handle.metrics().reorgs_total.increment(1); // A finalized block can never be reorged, so the rewind never needs to // go below it — bounding the scan (and the retained `IndexedBlocks` @@ -218,7 +256,9 @@ impl ReferenceIndexRuntime { let ancestor = ancestor.ok_or(ReferenceIndexError::ManualRebuildRequired { jade_first_block })?; - rollback_suffix(db, Some(ancestor), DEFAULT_BACKFILL_BATCH_BLOCKS) + rollback_suffix(db, Some(ancestor), DEFAULT_BACKFILL_BATCH_BLOCKS)?; + self.set_indexed_to(Some(ancestor)); + Ok(()) } /// Perform one synchronous reconciliation/backfill turn. @@ -231,7 +271,7 @@ impl ReferenceIndexRuntime { // cursor-vs-tip comparison surface `IndexBehind` — which tells clients // to retry — instead of `IndexUnavailable`, which tells them to stop. if error.requires_manual_rebuild() { - self.handle.set_phase(ReferenceIndexPhase::Unavailable); + self.set_phase(ReferenceIndexPhase::Unavailable); } } result @@ -242,16 +282,16 @@ impl ReferenceIndexRuntime { let head = self.chain.head()?; if head.timestamp < self.config.jade_timestamp { self.handle.metrics().lag_blocks.set(0.0); - self.handle.set_phase(ReferenceIndexPhase::PreJade); + self.set_phase(ReferenceIndexPhase::PreJade); return Ok(()); } if defer { - let indexed_to = db.indexed_to()?.unwrap_or_default(); + let indexed_to = db.indexed_to()?; self.handle .metrics() .lag_blocks - .set(head.number.saturating_sub(indexed_to) as f64); - self.handle.set_phase(ReferenceIndexPhase::Deferred); + .set(head.number.saturating_sub(indexed_to.unwrap_or_default()) as f64); + self.publish_progress(ReferenceIndexPhase::Deferred, indexed_to); return Ok(()); } @@ -266,16 +306,15 @@ impl ReferenceIndexRuntime { }; let finalized = self.chain.finalized_block_number()?; self.reconcile_cursor(&db, jade_first_block, finalized, head)?; - let start = db - .indexed_to()? - .map_or(jade_first_block, |cursor| cursor.saturating_add(1)); + let indexed_to = db.indexed_to()?; + let start = indexed_to.map_or(jade_first_block, |cursor| cursor.saturating_add(1)); if start > head.number { self.handle.metrics().lag_blocks.set(0.0); - self.handle.set_phase(ReferenceIndexPhase::Live); + self.publish_progress(ReferenceIndexPhase::Live, indexed_to); return Ok(()); } - self.handle.set_phase(ReferenceIndexPhase::Backfill); + self.publish_progress(ReferenceIndexPhase::Backfill, indexed_to); let end = start .saturating_add(DEFAULT_BACKFILL_BATCH_BLOCKS - 1) .min(head.number); @@ -304,13 +343,16 @@ impl ReferenceIndexRuntime { if lag > LIVE_LAG_SLO { debug!(target: TARGET, lag, slo = LIVE_LAG_SLO, "reference index remains behind its live-lag SLO"); } - if end == current_head.number + let next_phase = if end == current_head.number && blocks .last() .is_some_and(|block| block.hash == current_head.hash) { - self.handle.set_phase(ReferenceIndexPhase::Live); - } + ReferenceIndexPhase::Live + } else { + ReferenceIndexPhase::Backfill + }; + self.publish_progress(next_phase, Some(end)); Ok(()) } @@ -867,4 +909,63 @@ mod tests { assert_eq!(handle.db().unwrap().indexed_to().unwrap(), None); assert_eq!(handle.db().unwrap().indexed_block_hash(0).unwrap(), None); } + + #[tokio::test] + async fn watch_progress_notifies_on_commit_phase_transition_unavailable_and_drop() { + let dir = tempfile::tempdir().unwrap(); + let chain = TestChain::linear(10, 200); + let config = ReferenceIndexConfig::new(dir.path(), 2818, B256::ZERO, 200); + let (mut runtime, handle) = ReferenceIndexRuntime::new(config, chain.clone()); + let mut rx = handle.subscribe_progress(); + + assert_eq!( + *rx.borrow(), + ReferenceIndexProgress { + phase: ReferenceIndexPhase::Opening, + indexed_to: None, + unavailable: false, + } + ); + + // Initial backfill + live commit notifies watchers with cursor height. + runtime.synchronize_once(false).unwrap(); + rx.changed().await.unwrap(); + assert_eq!( + *rx.borrow(), + ReferenceIndexProgress { + phase: ReferenceIndexPhase::Live, + indexed_to: Some(9), + unavailable: false, + } + ); + + // Transition to Deferred notifies watchers while preserving cursor height. + runtime.synchronize_once(true).unwrap(); + rx.changed().await.unwrap(); + assert_eq!( + *rx.borrow(), + ReferenceIndexProgress { + phase: ReferenceIndexPhase::Deferred, + indexed_to: Some(9), + unavailable: false, + } + ); + + // Unrecoverable reorg notifies watchers with Unavailable. + chain.replace_suffix(0); + let _ = runtime.synchronize_once(false).unwrap_err(); + rx.changed().await.unwrap(); + assert_eq!( + *rx.borrow(), + ReferenceIndexProgress { + phase: ReferenceIndexPhase::Unavailable, + indexed_to: Some(9), + unavailable: true, + } + ); + + // Dropping the runtime drops the exclusive watch sender and wakes waiters immediately. + drop(runtime); + assert!(rx.changed().await.is_err()); + } } diff --git a/crates/revm/src/handler.rs b/crates/revm/src/handler.rs index 01996ce1..c1d10e6f 100644 --- a/crates/revm/src/handler.rs +++ b/crates/revm/src/handler.rs @@ -350,6 +350,15 @@ fn validate_morph_tx_authorization_list(host: &MorphEvm<'_>, tx: &MorphTxEnv) -> return Ok(()); } + // Enforce the Celadon hardfork gate for MorphTx V2 during real execution + // (including V2 with an empty authorization list). When fee charging is + // disabled (`eth_call` / `eth_estimateGas` simulation), preserve pre-Celadon + // Prague simulation compatibility (matching morph-geth `transaction_args.go:234`). + let hardfork = host.config_spec_id(); + if host.feature(EvmFeatures::FEE_CHARGE) && !hardfork.is_celadon() { + return Err(MorphInvalidTransaction::Eip7702NotSupported.into()); + } + if tx.authorization_list.is_empty() { return Ok(()); } @@ -470,11 +479,15 @@ fn deduct_eth_fee( tx: &MorphTxEnv, caller: Address, ) -> HandlerResult { - let l1_data_fee = l1_data_fee(host, tx)?; + let fee_charge = host.feature(EvmFeatures::FEE_CHARGE); + let l1_data_fee = if fee_charge { + l1_data_fee(host, tx)? + } else { + U256::ZERO + }; validate_sender(host, caller, tx.nonce)?; let basefee = host.block().basefee.saturating_to::(); - let fee_charge = host.feature(EvmFeatures::FEE_CHARGE); let balance_check = host.feature(EvmFeatures::BALANCE_CHECK); let mut sender = host.state_mut().account(&caller)?; @@ -3652,4 +3665,258 @@ mod refund_rounding_tests { assert_eq!(token_balance(&mut evm, CALLER), expected_refund); } + + /// Post-Curie simulation (`!EvmFeatures::FEE_CHARGE`) must credit 0 ETH to + /// the beneficiary / FeeVault even when L1 oracle fees and gas price are + /// non-zero, and must not touch the beneficiary account in the state diff. + #[test] + fn disable_fee_charge_credits_zero_eth_to_beneficiary_post_curie() { + use crate::l1block::{ + GPO_BLOB_SCALAR_SLOT, GPO_COMMIT_SCALAR_SLOT, GPO_IS_CURIE_SLOT, GPO_L1_BASE_FEE_SLOT, + GPO_L1_BLOB_BASE_FEE_SLOT, L1_GAS_PRICE_ORACLE_ADDRESS, + }; + + let caller = address!("1000000000000000000000000000000000000011"); + let recipient = address!("2000000000000000000000000000000000000022"); + let fee_vault = address!("530000000000000000000000000000000000000a"); + let initial_caller_balance = U256::from(10_000_000_000_000_000u128); + let initial_vault_balance = U256::from(1_000u64); + let transfer_value = U256::from(123_456u64); + let gas_price = 2_000_000_000u128; // 2 gwei + let rlp_bytes = Bytes::from(vec![0xab; 256]); + + let build_db = || { + let mut db = InMemoryDB::default(); + db.insert_account_info( + &caller, + AccountInfo::default().with_balance(initial_caller_balance), + ); + db.insert_account_info( + &fee_vault, + AccountInfo::default().with_balance(initial_vault_balance), + ); + db.insert_account_info(&L1_GAS_PRICE_ORACLE_ADDRESS, AccountInfo::default()); + db.insert_account_storage( + &L1_GAS_PRICE_ORACLE_ADDRESS, + &GPO_L1_BASE_FEE_SLOT, + &U256::from(10_000_000_000u64), + ); + db.insert_account_storage( + &L1_GAS_PRICE_ORACLE_ADDRESS, + &GPO_L1_BLOB_BASE_FEE_SLOT, + &U256::from(5_000_000_000u64), + ); + db.insert_account_storage( + &L1_GAS_PRICE_ORACLE_ADDRESS, + &GPO_COMMIT_SCALAR_SLOT, + &U256::from(230_760_020_821u64), + ); + db.insert_account_storage( + &L1_GAS_PRICE_ORACLE_ADDRESS, + &GPO_BLOB_SCALAR_SLOT, + &U256::from(417_565_260u64), + ); + db.insert_account_storage( + &L1_GAS_PRICE_ORACLE_ADDRESS, + &GPO_IS_CURIE_SLOT, + &U256::from(1u64), + ); + db + }; + + let block = MorphBlockEnv { + beneficiary: fee_vault, + basefee: U256::from(1_000_000u64), + gas_limit: U256::from(30_000_000u64), + ..Default::default() + }; + + let make_tx = || MorphTxEnv { + tx_type: EIP1559_TX_TYPE, + chain_id: Some(1), + kind: TxKind::Call(recipient), + gas_limit: 50_000, + gas_price, + gas_priority_fee: Some(gas_price), + value: transfer_value, + data: Bytes::from(vec![0xaa; 64]), + rlp_bytes: Some(rlp_bytes.clone()), + ..Default::default() + }; + + // 1. With `FEE_CHARGE` disabled: beneficiary receives 0 ETH (and is not touched), + // caller pays only `transfer_value`, and `l1_data_fee` is 0. + let mut sim_env = morph_evm_env(MorphHardfork::Celadon, 1, 30_000_000, block); + sim_env.version.features.remove(EvmFeatures::FEE_CHARGE); + let mut sim_evm = morph_evm(build_db(), sim_env); + let sim_tx = Recovered::new_unchecked(make_tx(), caller); + let sim_exec = sim_evm.transact(&sim_tx).expect("sim tx must succeed"); + assert!(sim_exec.result().status); + assert_eq!(sim_exec.result().ext.l1_data_fee, U256::ZERO); + let sim_detached = sim_exec.detach(); + assert!( + sim_detached + .pending_state + .account_changes() + .all(|change| change.address != fee_vault), + "FeeVault must not be credited or touched when FEE_CHARGE is disabled" + ); + let caller_balance_after = sim_detached + .pending_state + .account_changes() + .find(|change| change.address == caller) + .expect("caller must be in state diff") + .current + .expect("caller account must exist") + .balance; + assert_eq!( + caller_balance_after, + initial_caller_balance - transfer_value, + "caller must only pay tx.value, not L1 or L2 fees" + ); + let recipient_balance_after = sim_detached + .pending_state + .account_changes() + .find(|change| change.address == recipient) + .expect("recipient must be in state diff") + .current + .expect("recipient account must exist") + .balance; + assert_eq!(recipient_balance_after, transfer_value); + + // 2. Sanity contrast: with `FEE_CHARGE` enabled, FeeVault receives exact + // `execution_fee + l1_data_fee`. + let mut real_evm = morph_evm( + build_db(), + morph_evm_env(MorphHardfork::Celadon, 1, 30_000_000, block), + ); + let real_tx = Recovered::new_unchecked(make_tx(), caller); + let real_exec = real_evm + .transact(&real_tx) + .expect("real tx must succeed") + .detach(); + assert!(real_exec.result.status); + let expected_l1_fee = real_exec.result.ext.l1_data_fee; + assert!(expected_l1_fee > U256::ZERO); + let expected_exec_fee = U256::from(gas_price) * U256::from(real_exec.result.tx_gas_used()); + let vault_after = real_exec + .pending_state + .account_changes() + .find(|change| change.address == fee_vault) + .expect("FeeVault must be credited when FEE_CHARGE is enabled") + .current + .expect("FeeVault account must exist") + .balance; + assert_eq!( + vault_after, + initial_vault_balance + expected_exec_fee + expected_l1_fee + ); + } + + /// Regression for PR #240 (M-H10): MorphTx V2 (even with an empty authorization list) + /// must be rejected before Celadon during real execution (`FEE_CHARGE` enabled), while + /// simulation (`!FEE_CHARGE`) preserves pre-Celadon Prague compatibility. + #[test] + fn validate_env_gates_morph_tx_v2_on_celadon_during_execution_only() { + let v2_tx = MorphTxEnv { + tx_type: MORPH_TX_TYPE_ID, + chain_id: Some(1), + kind: TxKind::Call(address!("2000000000000000000000000000000000000022")), + gas_limit: 50_000, + gas_price: 100, + gas_priority_fee: Some(10), + version: Some(MORPH_TX_VERSION_2), + ..Default::default() + }; + + // Pre-Celadon (Jade) with FEE_CHARGE enabled -> rejected. + let jade_evm = morph_evm( + InMemoryDB::default(), + morph_evm_env(MorphHardfork::Jade, 1, 30_000_000, block()), + ); + let err = validate_env(&jade_evm, &v2_tx) + .expect_err("pre-Celadon execution must reject MorphTx V2"); + assert_eq!( + err.external_ref::(), + Some(&MorphInvalidTransaction::Eip7702NotSupported) + ); + + // Pre-Celadon (Jade) with FEE_CHARGE disabled (simulation) -> allowed. + let mut jade_sim_env = morph_evm_env(MorphHardfork::Jade, 1, 30_000_000, block()); + jade_sim_env + .version + .features + .remove(EvmFeatures::FEE_CHARGE); + let jade_sim_evm = morph_evm(InMemoryDB::default(), jade_sim_env); + assert!( + validate_env(&jade_sim_evm, &v2_tx).is_ok(), + "pre-Celadon simulation should allow MorphTx V2" + ); + + // Celadon with FEE_CHARGE enabled -> allowed. + let celadon_evm = morph_evm( + InMemoryDB::default(), + morph_evm_env(MorphHardfork::Celadon, 1, 30_000_000, block()), + ); + assert!(validate_env(&celadon_evm, &v2_tx).is_ok()); + } + + /// Regression for PR #244: `validate_env` for MorphTx enforces `BASE_FEE_CHECK` and + /// `PRIORITY_FEE_CHECK` independently of `FEE_CHARGE`. + #[test] + fn validate_env_morph_tx_honors_base_fee_and_priority_fee_flags() { + let block_with_basefee = MorphBlockEnv { + basefee: U256::from(100u64), + gas_limit: U256::from(30_000_000u64), + ..Default::default() + }; + + // Case 1: max_fee < base_fee rejected even when FEE_CHARGE is disabled, + // and accepted only when BASE_FEE_CHECK is disabled. + let low_max_fee_tx = MorphTxEnv { + tx_type: MORPH_TX_TYPE_ID, + chain_id: Some(1), + kind: TxKind::Call(address!("2000000000000000000000000000000000000022")), + gas_limit: 50_000, + gas_price: 50, + gas_priority_fee: Some(10), + fee_token_id: Some(FEE_TOKEN_ID), + ..Default::default() + }; + let mut sim_env = morph_evm_env(MorphHardfork::Celadon, 1, 30_000_000, block_with_basefee); + sim_env.version.features.remove(EvmFeatures::FEE_CHARGE); + let sim_evm = morph_evm(InMemoryDB::default(), sim_env.clone()); + assert!( + validate_env(&sim_evm, &low_max_fee_tx).is_err(), + "BASE_FEE_CHECK must still reject low max_fee even when FEE_CHARGE is disabled" + ); + sim_env.version.features.remove(EvmFeatures::BASE_FEE_CHECK); + let no_base_fee_evm = morph_evm(InMemoryDB::default(), sim_env); + assert!(validate_env(&no_base_fee_evm, &low_max_fee_tx).is_ok()); + + // Case 2: priority_fee > max_fee rejected even when BASE_FEE_CHECK & FEE_CHARGE are disabled, + // and accepted only when PRIORITY_FEE_CHECK is disabled. + let high_tip_tx = MorphTxEnv { + tx_type: MORPH_TX_TYPE_ID, + chain_id: Some(1), + kind: TxKind::Call(address!("2000000000000000000000000000000000000022")), + gas_limit: 50_000, + gas_price: 100, + gas_priority_fee: Some(200), + fee_token_id: Some(FEE_TOKEN_ID), + ..Default::default() + }; + let mut env = morph_evm_env(MorphHardfork::Celadon, 1, 30_000_000, block_with_basefee); + env.version + .features + .remove(EvmFeatures::FEE_CHARGE | EvmFeatures::BASE_FEE_CHECK); + let evm_with_prio_check = morph_evm(InMemoryDB::default(), env.clone()); + assert!( + validate_env(&evm_with_prio_check, &high_tip_tx).is_err(), + "PRIORITY_FEE_CHECK must reject priority_fee > max_fee" + ); + env.version.features.remove(EvmFeatures::PRIORITY_FEE_CHECK); + let evm_no_prio_check = morph_evm(InMemoryDB::default(), env); + assert!(validate_env(&evm_no_prio_check, &high_tip_tx).is_ok()); + } } diff --git a/crates/rpc/Cargo.toml b/crates/rpc/Cargo.toml index 2b4d6fe8..fa8e54e0 100644 --- a/crates/rpc/Cargo.toml +++ b/crates/rpc/Cargo.toml @@ -33,6 +33,7 @@ reth-rpc-server-types.workspace = true reth-metrics.workspace = true metrics.workspace = true reth-evm = { workspace = true, features = ["std", "witness"] } +reth-execution-types.workspace = true reth-provider.workspace = true reth-storage-api.workspace = true reth-tasks.workspace = true @@ -59,6 +60,7 @@ serde.workspace = true derive_more.workspace = true tokio.workspace = true evm2 = { workspace = true, features = ["std"] } +evm2-inspectors = { workspace = true, features = ["std"] } # Error handling thiserror.workspace = true diff --git a/crates/rpc/src/eth/call.rs b/crates/rpc/src/eth/call.rs index 0fd9307a..06005ffb 100644 --- a/crates/rpc/src/eth/call.rs +++ b/crates/rpc/src/eth/call.rs @@ -1,4 +1,4 @@ -//! Morph `eth_call` / `eth_estimateGas` overrides. +//! Morph `eth_call` / `eth_estimateGas` / `eth_simulateV1` overrides. //! //! [`Call::caller_gas_allowance`] is overridden so `eth_estimateGas` caps //! gas by `balance − value − l1_fee` (ETH path) or the fee token balance @@ -16,42 +16,66 @@ //! 3. Retry at `max_gas_limit` on revert / gas-too-high whenever //! `highest_gas_limit < max_gas_limit`, covering EIP-1559 and MorphTx //! requests whose legacy `gasPrice` field is absent. +//! +//! [`EthCall::simulate_v1`] is overridden so `eth_simulateV1` disables fee +//! charging (including Morph's non-zero L1 data fee) when `validation: false` +//! and passes each transaction's real EIP-2718 encoding when `validation: true` +//! so Curie `commit + blob` (and pre-Curie calldata) L1 fees are accurately +//! charged and validated. use crate::MorphEthApiError; use crate::eth::{MorphEthApi, MorphNodeCore}; +use alloy_consensus::BlockHeader; +use alloy_eips::eip2718::{Encodable2718, WithEncoded}; use alloy_network::TransactionBuilder; -use alloy_primitives::{Address, TxKind, U256, U512}; -use alloy_rpc_types_eth::state::EvmOverrides; +use alloy_primitives::{Address, B256, TxKind, U256, U512}; +use alloy_rpc_types_eth::{ + BlockId, + simulate::{SimBlock, SimulatePayload, SimulatedBlock}, + state::EvmOverrides, +}; use evm2::{ EvmFeatures, TxResult, - evm::{CacheDB, Db}, - interpreter::InstrStop, + bytecode::Bytecode, + evm::{AccountInfo, CacheDB, Db}, + interpreter::{InstrStop, Word}, registry::HandlerError, }; +use evm2_inspectors::transfer::TransferInspector; use morph_chainspec::{MorphChainSpec, MorphHardforks}; use morph_revm::{L1BlockInfo, MorphEvmEnv, MorphTxExt, TokenFeeInfo}; -use reth_chainspec::MIN_TRANSACTION_GAS; -use reth_errors::ProviderError; +use reth_chainspec::{EthChainSpec, EthereumHardforks, MIN_TRANSACTION_GAS}; +use reth_errors::{ProviderError, RethError}; use reth_evm::{ - ConfigureEvm, Database, Evm, EvmEnv, EvmEnvFor, EvmTypesFor, TransactionEnvMut, TxEnvFor, + BlockExecutionError, BundleState, ConfigureEvm, Database, Evm, EvmEnv, EvmEnvFor, EvmTypesFor, + TransactionEnvMut, TxEnvFor, database::StateProviderDatabase, + execute::{ + BlockBuilder, BlockBuilderOutcome, BlockExecutor, BlockTransactionResult, + map_database_error, + }, }; +use reth_execution_types::BundleSource; +use reth_primitives_traits::NodePrimitives; use reth_provider::ChainSpecProvider; use reth_rpc_convert::{RpcConvert, RpcTxReq}; use reth_rpc_eth_api::{ - AsEthApiError, EthApiTypes, FromEthApiError, FromEvmError, IntoEthApiError, RpcNodeCore, + AsEthApiError, EthApiTypes, FromEthApiError, FromEvmError, IntoEthApiError, RpcBlock, + RpcNodeCore, helpers::{ - Call, EthCall, + Call, EthCall, LoadBlock, LoadPendingBlock, SpawnBlocking, + call::SimulatedBlocksResult, estimate::{EstimateCall, update_estimated_gas_range}, }, }; use reth_rpc_eth_types::{ EthApiError, RpcInvalidTransactionError, - cache::db::{apply_block_overrides, apply_state_overrides}, + cache::db::{apply_block_overrides, apply_state_overrides, apply_state_overrides_with_state}, error::api::{FromEvmHalt, FromRevert}, + simulate::{self, EthSimulateError, SimulatedState}, }; use reth_rpc_server_types::constants::gas_oracle::{CALL_STIPEND_GAS, ESTIMATE_GAS_ERROR_RATIO}; -use reth_storage_api::EvmStateProvider; +use reth_storage_api::{EvmStateProvider, StateProvider, noop::NoopProvider}; use reth_tasks::cancel::is_cancelled; use tracing::trace; @@ -63,6 +87,396 @@ where reth_rpc_convert::RpcConvert, MorphEthApiError: reth_rpc_eth_types::error::FromEvmError, { + async fn simulate_v1( + &self, + payload: SimulatePayload::Network>>, + block: Option, + ) -> SimulatedBlocksResult { + if payload.block_state_calls.len() > self.max_simulate_blocks() as usize { + return Err(EthApiError::other(EthSimulateError::TooManyBlocks).into()); + } + + let block = block.unwrap_or_default(); + + let SimulatePayload { + block_state_calls, + trace_transfers, + validation, + return_full_transactions, + } = payload; + + if block_state_calls.is_empty() { + return Err(EthApiError::InvalidParams(String::from("calls are empty.")).into()); + } + + let permit = self + .acquire_owned_blocking_io() + .await + .map_err(|_| EthApiError::InternalEthError)?; + + let base_block = self + .recovered_block(block) + .await? + .ok_or_else(|| EthApiError::other(EthSimulateError::BlockNotFound { block }))?; + let parent = base_block.sealed_header().clone(); + let max_simulate_blocks = self.max_simulate_blocks(); + let state_at = if block.is_pending() { + block + } else { + parent.hash().into() + }; + + self.spawn_with_state_at_block(state_at, move |this, db| { + let _permit = permit; + let state_provider = db.db.into_inner().into_inner().0; + let mut db = CacheDB::new(Db::new(StateProviderDatabase::new( + (&state_provider).into_evm_state_provider(), + ))); + let mut parent = parent; + let mut simulation_state = this + .compute_state_root_for_eth_simulate() + .then(SimulatedState::default); + + let chain_id = this.provider().chain_spec().chain_id(); + + let block_state_calls = simulate::sanitize_chain( + block_state_calls, + &parent, + chain_id, + max_simulate_blocks, + )?; + + let mut blocks: Vec>> = + Vec::with_capacity(block_state_calls.len()); + + let call_gas_limit = this.call_gas_limit(); + let mut remaining_call_gas_limit = (call_gas_limit > 0).then_some(call_gas_limit); + + for block in block_state_calls { + let SimBlock { + block_overrides, + state_overrides, + calls, + } = block; + + let attributes = this + .pending_env_builder() + .pending_env_attributes(&parent, block_overrides.as_ref()) + .map_err(Self::Error::from_eth_err)?; + + let mut evm_env = this + .evm_config() + .next_evm_env(&parent, &attributes) + .map_err(RethError::other) + .map_err(Self::Error::from_eth_err)?; + + // Always disable EIP-3607 + evm_env.version_mut().features.remove(EvmFeatures::EIP3607); + + if !validation || !evm_env.version().feature(EvmFeatures::EIP8037) { + evm_env.version_mut().tx_gas_limit_cap = u64::MAX; + } + + if !validation { + // If not explicitly required, disable nonce check, basefee check, and + // fee charging (including Morph's non-zero L1 data fee and token fees) + // so zero-balance callers succeed and no phantom fees are debited/credited. + evm_env + .version_mut() + .features + .remove(EvmFeatures::NONCE_CHECK); + evm_env + .version_mut() + .features + .remove(EvmFeatures::BASE_FEE_CHECK); + evm_env + .version_mut() + .features + .remove(EvmFeatures::FEE_CHARGE); + evm_env.block_env_mut().basefee = U256::ZERO; + } + + evm_env.block_env_mut().prevrandao = U256::ZERO; + if !this + .provider() + .chain_spec() + .is_paris_active_at_block(evm_env.block_env().number.to()) + { + evm_env.block_env_mut().difficulty = parent.difficulty(); + } + + if let Some(block_overrides) = block_overrides { + if let Some(gas_limit_override) = block_overrides.gas_limit + && gas_limit_override > evm_env.block_env().gas_limit.to::() + && gas_limit_override > this.call_gas_limit() + { + return Err(EthApiError::other(EthSimulateError::GasLimitReached).into()); + } + apply_block_overrides(block_overrides, &mut db, &mut evm_env); + } + if let Some(ref state_overrides) = state_overrides { + let mut changes = simulation_state.as_ref().map(|_| BundleState::default()); + apply_state_overrides_with_state( + state_overrides.clone(), + &mut db, + changes.as_mut(), + ) + .map_err(Self::Error::from_eth_err)?; + if let Some(simulation_state) = simulation_state.as_mut() + && let Some(changes) = changes + { + simulation_state + .extend(&state_provider, &changes) + .map_err(Self::Error::from_eth_err)?; + } + } + + let chain_id = evm_env.chain_id(); + let build_bal = this + .provider() + .chain_spec() + .is_amsterdam_active_at_timestamp(evm_env.block_env().timestamp.to::()); + + let ctx = this + .evm_config() + .context_for_next_block(&parent, attributes) + .map_err(RethError::other) + .map_err(Self::Error::from_eth_err)?; + let map_err = |e: EthApiError| -> Self::Error { + match e.as_simulate_error() { + Some(sim_err) => Self::Error::from_eth_err(EthApiError::other(sim_err)), + None => Self::Error::from_eth_err(e), + } + }; + + // EIP-7708 already emits transfer logs: https://eips.ethereum.org/EIPS/eip-7708 + let trace_transfers = + trace_transfers && !evm_env.version().feature(EvmFeatures::EIP7708); + let mut evm = this.evm_config().evm_with_env(&mut db, evm_env.clone()); + if trace_transfers { + evm.set_inspector(TransferInspector::new(false).with_logs(true)); + } + let mut builder = this + .evm_config() + .create_block_builder(evm, evm_env, &parent, ctx); + if build_bal { + builder.executor_mut().enable_block_access_list_builder(); + } + + if let Some(ref state_overrides) = state_overrides { + simulate::apply_precompile_overrides(state_overrides, builder.evm_mut()) + .map_err(|e| Self::Error::from_eth_err(EthApiError::other(e)))?; + } + + let (result, results) = execute_simulated_transactions( + builder, + &*state_provider, + calls, + &mut remaining_call_gas_limit, + chain_id, + validation, + simulation_state.as_mut(), + this.converter(), + ) + .map_err(map_err)?; + + db.commit_source(&BundleSource(&result.execution_state)); + let simulated_header = result.block.clone_sealed_header(); + db.insert_block_hash( + &U256::from(simulated_header.number()), + &simulated_header.hash(), + ); + parent = simulated_header; + + let block = + simulate::build_simulated_block::>( + result.block, + results, + return_full_transactions.into(), + this.converter(), + )?; + + blocks.push(block); + } + + Ok(blocks) + }) + .await + } +} + +/// Adapter exposing [`Evm::account_info`] as a [`Database`] for [`simulate::resolve_transaction`]. +struct EvmAccountDb<'a, E>(&'a mut E); + +impl Database for EvmAccountDb<'_, E> { + type Error = BlockExecutionError; + + fn get_account(&mut self, address: &Address) -> Result, Self::Error> { + self.0.account_info(address) + } + + fn get_code_by_hash(&mut self, code_hash: &B256) -> Result { + self.0 + .state_db_mut() + .get_code_by_hash(code_hash) + .map_err(map_database_error) + } + + fn get_storage(&mut self, address: &Address, key: &Word) -> Result { + self.0 + .state_db_mut() + .get_storage(address, key) + .map_err(map_database_error) + } + + fn get_block_hash(&mut self, number: &Word) -> Result { + self.0 + .state_db_mut() + .get_block_hash(number) + .map_err(map_database_error) + } +} + +/// Executes simulated transactions, matching upstream `reth_rpc_eth_types::simulate::execute_transactions` +/// while preserving each transaction's real EIP-2718 encoding when `validation == true` so Morph charges +/// full Curie `commit + blob` (or pre-Curie calldata) L1 data fees. +#[expect(clippy::too_many_arguments, clippy::type_complexity)] +fn execute_simulated_transactions( + mut builder: S, + state_provider: impl StateProvider, + calls: Vec>, + remaining_call_gas_limit: &mut Option, + chain_id: u64, + validation: bool, + simulation_state: Option<&mut SimulatedState>, + converter: &T, +) -> Result<(BlockBuilderOutcome, Vec>), EthApiError> +where + S: BlockBuilder< + Primitives: NodePrimitives, + Executor: BlockExecutor>, + >, + T: RpcConvert, + EvmTypes: evm2::EvmTypes, +{ + if is_cancelled() { + return Err(EthApiError::InternalEthError); + } + builder.apply_pre_execution_changes()?; + + let mut results = Vec::with_capacity(calls.len()); + let mut cumulative_tx_gas_used: u64 = 0; + let mut block_regular_gas_used: u64 = 0; + let mut block_state_gas_used: u64 = 0; + let block_gas_limit = builder.evm_env().block_env().gas_limit.to::(); + let is_amsterdam = builder.evm_env().version().feature(EvmFeatures::EIP8037); + let tx_gas_limit_cap = builder.evm_env().version().tx_gas_limit_cap; + for mut call in calls { + if is_cancelled() { + return Err(EthApiError::InternalEthError); + } + let block_gas_remaining = if is_amsterdam { + let regular_available_gas = block_gas_limit.saturating_sub(block_regular_gas_used); + let state_available_gas = block_gas_limit.saturating_sub(block_state_gas_used); + if regular_available_gas >= tx_gas_limit_cap { + state_available_gas + } else { + regular_available_gas.min(state_available_gas) + } + } else { + block_gas_limit.saturating_sub(cumulative_tx_gas_used) + }; + let mut default_gas_limit = block_gas_remaining; + + if let Some(gas_limit) = call.as_ref().gas_limit() + && gas_limit > block_gas_remaining + { + return Err(EthApiError::other(EthSimulateError::BlockGasLimitExceeded)); + } + + if let Some(remaining_call_gas_limit) = *remaining_call_gas_limit { + if let Some(gas_limit) = call.as_ref().gas_limit() { + if gas_limit > remaining_call_gas_limit { + call.as_mut().set_gas_limit(remaining_call_gas_limit); + } + } else { + default_gas_limit = default_gas_limit.min(remaining_call_gas_limit); + } + } + + let block_base_fee = builder.evm_env().block_base_fee(); + let disable_nonce_check = !builder + .evm_env() + .version() + .feature(EvmFeatures::NONCE_CHECK); + let mut account_db = EvmAccountDb(builder.evm_mut()); + let tx = simulate::resolve_transaction( + call, + default_gas_limit, + block_base_fee, + chain_id, + disable_nonce_check, + &mut account_db, + converter, + )?; + // When `validation == true`, pass the real EIP-2718 encoding so Morph's L1 + // fee calculation charges the full commit + blob (Curie) or calldata + // (pre-Curie) fee. When `validation == false`, fee charging is disabled + // (`!EvmFeatures::FEE_CHARGE`), so an empty envelope avoids wasted encoding. + let encoded = if validation { + tx.encoded_2718().into() + } else { + Default::default() + }; + let tx = WithEncoded::new(encoded, tx); + + let mut tx_regular_gas_used = 0; + let gas_output = builder.execute_transaction_with_result_closure(tx, |output| { + let output = &output.result().result; + tx_regular_gas_used = output.execution_gas_spent(); + results.push(output.clone()) + })?; + + // The transfer tracer keeps the transaction's logs, with the synthetic transfer logs + // among them, outside the EVM's own logs. + // SAFETY: `TransferInspector` has no lifetime parameters. + if let Some(logs) = unsafe { + builder + .evm_mut() + .with_inspector(|inspector: &mut TransferInspector| inspector.take_logs()) + } && let Some(result) = results.last_mut() + { + result.logs = logs; + } + + let gas_used = gas_output.tx_gas_used(); + if let Some(remaining_call_gas_limit) = remaining_call_gas_limit.as_mut() { + if gas_used > *remaining_call_gas_limit { + return Err(EthApiError::other(EthSimulateError::GasLimitReached)); + } + *remaining_call_gas_limit -= gas_used; + } + + cumulative_tx_gas_used = cumulative_tx_gas_used.saturating_add(gas_used); + block_regular_gas_used = block_regular_gas_used.saturating_add(tx_regular_gas_used); + block_state_gas_used = block_state_gas_used.saturating_add(gas_output.state_gas_used()); + } + + let result = if let Some(simulation_state) = simulation_state { + builder.finish_with_state_root(&state_provider, |output| { + simulation_state + .extend(&state_provider, &output.state) + .map_err(BlockExecutionError::other)?; + state_provider + .state_root_with_updates(simulation_state.hashed_state().clone()) + .map(Some) + .map_err(BlockExecutionError::other) + })? + } else { + builder.finish(NoopProvider::default(), None)? + }; + + Ok((result, results)) } impl EstimateCall for MorphEthApi diff --git a/crates/rpc/src/eth/mod.rs b/crates/rpc/src/eth/mod.rs index 04d3dce5..efc0f983 100644 --- a/crates/rpc/src/eth/mod.rs +++ b/crates/rpc/src/eth/mod.rs @@ -3,9 +3,10 @@ use crate::MorphEthApiError; use crate::eth::receipt::MorphReceiptConverter; use crate::types::{MorphRpcReceipt, MorphRpcTransaction, MorphTransactionRequest}; +use alloy_primitives::U256; use alloy_rpc_types_eth::Header as RpcHeader; use eyre::Result; -use morph_chainspec::MorphChainSpec; +use morph_chainspec::{MORPH_DEFAULT_PRIORITY_FEE, MorphChainSpec}; use morph_evm::MorphEvmConfig; use morph_primitives::{MorphHeader, MorphPrimitives}; use reth_node_api::{FullNodeComponents, NodeTypes}; @@ -14,7 +15,7 @@ use reth_provider::ChainSpecProvider; use reth_rpc::EthApi; use reth_rpc_convert::{RpcConvert, RpcConverter, RpcTypes}; use reth_rpc_eth_api::{ - EthApiTypes, RpcNodeCore, RpcNodeCoreExt, + EthApiTypes, FromEthApiError, RpcNodeCore, RpcNodeCoreExt, helpers::{ EthApiSpec, EthBlocks, EthFees, EthState, EthSubscriptions, EthTransactions, LoadBlock, LoadFee, LoadPendingBlock, LoadState, LoadTransaction, SpawnBlocking, Trace, @@ -257,6 +258,32 @@ where fn fee_history_cache(&self) -> &FeeHistoryCache> { self.inner.eth_api.fee_history_cache() } + + /// Suggests a priority fee using the single-sequencer L2 algorithm + /// ([`GasPriceOracle::op_suggest_tip_cap`]). + /// + /// Upstream `GasPriceOracle::suggest_tip_cap` pushes `U256::ZERO` for every empty block + /// and scans up to `2 * max_block_history` (2,048) blocks against a 1,024-entry LRU cache. + /// On Morph L2, where empty blocks are frequent, that caused `eth_maxPriorityFeePerGas` to + /// collapse to `0x0` (making `MORPH_DEFAULT_PRIORITY_FEE` dead code) and risked full LRU + /// thrashing on quiet networks. Inspecting only the latest block keeps suggestions O(1), + /// skips L1 message transactions, enforces the configured floor (defaulting to + /// [`MORPH_DEFAULT_PRIORITY_FEE`]), and scales up by 10% above the median tip when a block + /// reaches gas capacity. + async fn suggested_priority_fee(&self) -> Result + where + Self: 'static, + { + let min_suggested_fee = self + .gas_oracle() + .config() + .default_suggested_fee + .unwrap_or_else(|| U256::from(MORPH_DEFAULT_PRIORITY_FEE)); + self.gas_oracle() + .op_suggest_tip_cap(min_suggested_fee) + .await + .map_err(Self::Error::from_eth_err) + } } impl LoadPendingBlock for MorphEthApi diff --git a/crates/rpc/src/eth/transaction.rs b/crates/rpc/src/eth/transaction.rs index ee8779ea..5113449c 100644 --- a/crates/rpc/src/eth/transaction.rs +++ b/crates/rpc/src/eth/transaction.rs @@ -13,7 +13,7 @@ use reth_rpc_convert::{ }; use reth_rpc_eth_types::EthApiError; -use morph_primitives::{MorphTxEnvelope, TxMorph}; +use morph_primitives::{MorphTxEnvelope, TxMorph, transaction::morph_transaction::MAX_MEMO_LENGTH}; use morph_revm::{MorphAuthorization, MorphEvmEnv, MorphTxEnv}; use reth_evm::EvmEnv; @@ -130,6 +130,18 @@ impl TryIntoTxEnv, MorphEvmEnv> for MorphTransactionReques || is_nonzero_reference(reference.as_ref()) || memo.as_ref().is_some_and(|m| !m.is_empty()); + // Match geth's `ToMessage` / `DoEstimateGas`: when `maxFeePerGas` is omitted and + // `maxPriorityFeePerGas` is explicitly `0` (with no legacy `gasPrice`), treat the + // request as zero-priced — identical to omitting both or passing `(0, 0)` — rather + // than letting `normalize_transaction_request` price it at `base_fee + 0` and + // reject zero-balance callers with `insufficient funds for l1 fee`. + if inner.gas_price.is_none() + && inner.max_fee_per_gas.is_none() + && inner.max_priority_fee_per_gas == Some(0) + { + inner.max_fee_per_gas = Some(0); + } + let tx_type = inner.minimal_tx_type(); let fees = normalize_transaction_request(&mut inner, evm_env).map_err(EthApiError::from)?; let kind = inner.to.unwrap_or(TxKind::Create); @@ -178,13 +190,26 @@ impl TryIntoTxEnv, MorphEvmEnv> for MorphTransactionReques ..Default::default() }; if is_morph_tx { - tx_env.fee_token_id = match fee_token_id { + let parsed_fee_token_id = match fee_token_id { Some(id) => Some( u16::try_from(id.to::()) .map_err(|_| EthApiError::InvalidParams("invalid token".to_string()))?, ), None => None, }; + if memo.as_ref().is_some_and(|m| m.len() > MAX_MEMO_LENGTH) { + return Err(EthApiError::InvalidParams( + "memo exceeds maximum length of 64 bytes".to_string(), + )); + } + if parsed_fee_token_id.unwrap_or(0) == 0 + && fee_limit.is_some_and(|limit| limit > U256::ZERO) + { + return Err(EthApiError::InvalidParams( + "MorphTx cannot have FeeLimit when FeeTokenID is 0".to_string(), + )); + } + tx_env.fee_token_id = parsed_fee_token_id; tx_env.fee_limit = fee_limit; tx_env.reference = reference; tx_env.memo = memo; @@ -1653,4 +1678,105 @@ mod tests { // = 500_000_000 + 1_000_000_000 = 1_500_000_000 assert_eq!(rpc_tx.effective_gas_price, Some(1_500_000_000)); } + + #[test] + fn try_into_tx_env_zero_tip_without_max_fee_is_zero_priced() { + let evm_env = create_evm_env(true); + + // Omitting `maxFeePerGas` while passing `maxPriorityFeePerGas: 0` must produce + // a zero-priced EIP-1559 TxEnv (matching geth's `ToMessage` / `DoEstimateGas`). + let req = MorphTransactionRequest { + inner: TransactionRequest { + from: Some(address!("0000000000000000000000000000000000000001")), + to: Some(address!("0000000000000000000000000000000000000002").into()), + max_priority_fee_per_gas: Some(0), + ..Default::default() + }, + ..Default::default() + }; + let tx_env = req.try_into_tx_env(&evm_env).unwrap(); + assert_eq!(tx_env.gas_price, 0); + assert_eq!(tx_env.gas_priority_fee, Some(0)); + + // Explicit positive `maxFeePerGas` with `maxPriorityFeePerGas: 0` must keep the cap. + let req_with_cap = MorphTransactionRequest { + inner: TransactionRequest { + from: Some(address!("0000000000000000000000000000000000000001")), + to: Some(address!("0000000000000000000000000000000000000002").into()), + max_fee_per_gas: Some(2_000_000_000), + max_priority_fee_per_gas: Some(0), + ..Default::default() + }, + ..Default::default() + }; + let tx_env_with_cap = req_with_cap.try_into_tx_env(&evm_env).unwrap(); + assert_eq!(tx_env_with_cap.gas_price, 2_000_000_000); + assert_eq!(tx_env_with_cap.gas_priority_fee, Some(0)); + } + + #[test] + fn try_into_tx_env_rejects_oversized_morph_tx_memo() { + let evm_env = create_evm_env(true); + + // Exactly MAX_MEMO_LENGTH (64) bytes is accepted. + let ok_req = MorphTransactionRequest { + inner: create_morph_transaction_request(), + fee_token_id: None, + fee_limit: None, + reference: None, + memo: Some(Bytes::from(vec![0xaa; MAX_MEMO_LENGTH])), + }; + assert!(ok_req.try_into_tx_env(&evm_env).is_ok()); + + // MAX_MEMO_LENGTH + 1 (65) bytes is rejected. + let bad_req = MorphTransactionRequest { + inner: create_morph_transaction_request(), + fee_token_id: None, + fee_limit: None, + reference: None, + memo: Some(Bytes::from(vec![0xaa; MAX_MEMO_LENGTH + 1])), + }; + let err = bad_req.try_into_tx_env(&evm_env).unwrap_err(); + match err { + EthApiError::InvalidParams(msg) => { + assert!(msg.contains("64 bytes"), "unexpected error: {msg}"); + } + other => panic!("expected InvalidParams, got {other:?}"), + } + } + + #[test] + fn try_into_tx_env_rejects_fee_limit_with_zero_fee_token_id() { + let evm_env = create_evm_env(true); + + for fee_token_id in [None, Some(U64::ZERO)] { + let bad_req = MorphTransactionRequest { + inner: create_morph_transaction_request(), + fee_token_id, + fee_limit: Some(U256::from(100)), + reference: Some(B256::repeat_byte(0x11)), + memo: None, + }; + let err = bad_req.try_into_tx_env(&evm_env).unwrap_err(); + match err { + EthApiError::InvalidParams(msg) => { + assert!( + msg.contains("FeeLimit") && msg.contains("FeeTokenID"), + "unexpected error: {msg}" + ); + } + other => panic!("expected InvalidParams, got {other:?}"), + } + } + + // Zero fee_limit with fee_token_id == 0 is permitted. + let ok_req = MorphTransactionRequest { + inner: create_morph_transaction_request(), + fee_token_id: Some(U64::ZERO), + fee_limit: Some(U256::ZERO), + reference: Some(B256::repeat_byte(0x11)), + memo: None, + }; + assert!(ok_req.try_into_tx_env(&evm_env).is_ok()); + } } diff --git a/crates/rpc/src/morph/handler.rs b/crates/rpc/src/morph/handler.rs index acef6045..d655cf61 100644 --- a/crates/rpc/src/morph/handler.rs +++ b/crates/rpc/src/morph/handler.rs @@ -7,11 +7,11 @@ use jsonrpsee::{ types::{ErrorCode, ErrorObjectOwned}, }; use morph_reference_index::{ - CanonicalTip, ReferenceIndexError, ReferenceIndexHandle, ReferenceIndexPhase, ReferenceQuery, - ReferenceTransactionResult, + CanonicalTip, ReferenceIndexError, ReferenceIndexHandle, ReferenceIndexPhase, + ReferenceIndexProgress, ReferenceQuery, ReferenceTransactionResult, }; use reth_storage_api::{BlockNumReader, HeaderProvider}; -use std::time::{Duration, Instant}; +use std::time::Duration; use tracing; const TARGET: &str = "morph::reference_index_rpc"; @@ -22,12 +22,90 @@ const TARGET: &str = "morph::reference_index_rpc"; /// this budget and return real data instead of forcing the client to retry. const INDEX_WAIT_TIMEOUT: Duration = Duration::from_millis(300); -/// Poll cadence while waiting for the index cursor to reach the canonical tip. -const INDEX_WAIT_POLL_INTERVAL: Duration = Duration::from_millis(5); +/// Maximum block lag for which the RPC handler waits asynchronously for the +/// reference index to catch up. When the durable cursor lags further behind the +/// canonical tip (for example during large historical backfill), the handler +/// fails fast with `IndexBehind` instead of holding an async waiter open. +const MAX_STEADY_STATE_LAG: u64 = 2; + +fn should_fail_fast(progress: ReferenceIndexProgress, canonical_tip_number: u64) -> bool { + if matches!( + progress.phase, + ReferenceIndexPhase::Deferred + | ReferenceIndexPhase::PreJade + | ReferenceIndexPhase::Repairing + ) { + return true; + } + + if let Some(indexed_to) = progress.indexed_to + && canonical_tip_number.saturating_sub(indexed_to) > MAX_STEADY_STATE_LAG + { + return true; + } -fn next_poll_delay(now: Instant, deadline: Instant) -> Option { - let remaining = deadline.saturating_duration_since(now); - (!remaining.is_zero()).then(|| INDEX_WAIT_POLL_INTERVAL.min(remaining)) + false +} + +enum QueryAttempt { + Ready(Vec), + TipChanged, + Behind { tip_number: u64 }, +} + +fn query_once( + ctx: &MorphRpc, + query: ReferenceQuery, +) -> Result +where + Provider: BlockNumReader + HeaderProvider, +{ + let before = ctx.provider.chain_info()?; + let header = ctx + .provider + .header(before.best_hash)? + .ok_or(ReferenceIndexError::IndexBehind)?; + if header.number() != before.best_number { + return Err(ReferenceIndexError::IndexBehind); + } + let canonical_tip = CanonicalTip { + number: before.best_number, + hash: before.best_hash, + timestamp: header.timestamp(), + }; + + // Pre-Jade is a complete, terminal empty answer: no reference-carrying + // transaction can exist before Jade, so return `[]` without touching + // the index. This must not be `IndexBehind` (which instructs clients + // to retry) — before Jade there is nothing to wait for. + if ctx.reference_index.is_pre_jade(canonical_tip.timestamp) { + let after = ctx.provider.chain_info()?; + if after == before { + return Ok(QueryAttempt::Ready(Vec::new())); + } + // The pre-Jade snapshot changed while it was bracketed. Do not + // query the index with the stale tip: rebuild a fresh canonical + // snapshot on the next iteration. + return Ok(QueryAttempt::TipChanged); + } + + match ctx.reference_index.query_at(query, canonical_tip) { + Ok(result) => { + let after = ctx.provider.chain_info()?; + if after == before { + Ok(QueryAttempt::Ready(result)) + } else { + // The tip advanced while we read; this snapshot no longer + // matches a stable head. Retry against the new tip while the + // wait budget allows, otherwise report behind. + Ok(QueryAttempt::TipChanged) + } + } + Err(ReferenceIndexError::IndexBehind) => Ok(QueryAttempt::Behind { + tip_number: canonical_tip.number, + }), + Err(other) => Err(other), + } } // ── Context ────────────────────────────────────────────────────────────────── @@ -111,10 +189,6 @@ impl<'a, Provider> RpcWaitGuard<'a, Provider> { } } - const fn has_waited(&self) -> bool { - self.waited - } - const fn begin_wait(&mut self) { self.waited = true; } @@ -132,11 +206,12 @@ impl Drop for RpcWaitGuard<'_, Provider> { } } +#[async_trait::async_trait] impl MorphRpcServer for MorphRpcHandler where Provider: BlockNumReader + HeaderProvider + Clone + Send + Sync + 'static, { - fn get_transaction_hashes_by_reference( + async fn get_transaction_hashes_by_reference( &self, args: ReferenceQueryArgs, ) -> RpcResult> { @@ -145,105 +220,96 @@ where // The index runtime is asynchronous (PR #141 decoupled it from block // execution), so for a few milliseconds after a new block becomes the - // canonical tip the durable cursor still lags it. Rather than returning - // `IndexBehind` immediately — forcing the client into a retry loop — - // wait a bounded amount for the runtime to catch up. This is a - // `blocking` RPC handler, so the sleep only occupies a blocking-pool - // thread (never the async reactor) and is strictly bounded by - // `INDEX_WAIT_TIMEOUT`. - let deadline = Instant::now() + INDEX_WAIT_TIMEOUT; + // canonical tip the durable cursor still lags it. Run each synchronous + // provider + MDBX read on Tokio's blocking pool, and park asynchronously + // on the runtime's `watch` progress channel when waiting for steady-state + // catch-up — holding zero OS blocking threads and opening zero MDBX read + // transactions while waiting. + let deadline = tokio::time::Instant::now() + INDEX_WAIT_TIMEOUT; let mut wait = RpcWaitGuard::new(self); + let mut progress_rx = self.ctx.reference_index.subscribe_progress(); + let mut watch_closed = false; loop { - if wait.has_waited() && Instant::now() >= deadline { - wait.mark_timed_out(); - return Err(to_rpc_error(ReferenceIndexError::IndexBehind)); - } - - let before = self - .ctx - .provider - .chain_info() - .map_err(ReferenceIndexError::from) - .map_err(to_rpc_error)?; - let header = self - .ctx - .provider - .header(before.best_hash) - .map_err(ReferenceIndexError::from) - .map_err(to_rpc_error)? - .ok_or(ReferenceIndexError::IndexBehind) + // Mark the latest published progress as seen BEFORE running the + // blocking read attempt so any commit/phase change occurring while + // `query_once` executes immediately wakes `progress_rx.changed()`. + let _ = *progress_rx.borrow_and_update(); + + let ctx = self.ctx.clone(); + let attempt = tokio::task::spawn_blocking(move || query_once(&ctx, query)) + .await + .map_err(|err| { + to_rpc_error(ReferenceIndexError::Other(eyre::eyre!( + "reference index query task failed: {err}" + ))) + })? .map_err(to_rpc_error)?; - if header.number() != before.best_number { - return Err(to_rpc_error(ReferenceIndexError::IndexBehind)); - } - let canonical_tip = CanonicalTip { - number: before.best_number, - hash: before.best_hash, - timestamp: header.timestamp(), - }; - - // Pre-Jade is a complete, terminal empty answer: no reference-carrying - // transaction can exist before Jade, so return `[]` without touching - // the index. This must not be `IndexBehind` (which instructs clients - // to retry) — before Jade there is nothing to wait for. - if self - .ctx - .reference_index - .is_pre_jade(canonical_tip.timestamp) - { - let after = self - .ctx - .provider - .chain_info() - .map_err(ReferenceIndexError::from) - .map_err(to_rpc_error)?; - if after == before { - return Ok(Vec::new()); + + match attempt { + QueryAttempt::Ready(results) => return Ok(results), + QueryAttempt::TipChanged => { + if tokio::time::Instant::now() >= deadline { + wait.begin_wait(); + wait.mark_timed_out(); + return Err(to_rpc_error(ReferenceIndexError::IndexBehind)); + } + wait.begin_wait(); + tokio::task::yield_now().await; } - // The pre-Jade snapshot changed while it was bracketed. Do not - // query the index with the stale tip: wait once, then rebuild a - // fresh canonical snapshot on the next iteration. - } else { - match self.ctx.reference_index.query_at(query, canonical_tip) { - Ok(result) => { - let after = self - .ctx - .provider - .chain_info() - .map_err(ReferenceIndexError::from) - .map_err(to_rpc_error)?; - if after == before { - return Ok(result); - } - // The tip advanced while we read; this snapshot no longer - // matches a stable head. Retry against the new tip while the - // wait budget allows, otherwise report behind. + QueryAttempt::Behind { tip_number } => { + let progress = self.ctx.reference_index.progress(); + if progress.unavailable { + return Err(to_rpc_error(ReferenceIndexError::IndexUnavailable)); } - Err(ReferenceIndexError::IndexBehind) => { - // Waiting only pays off for the steady-state per-block lag - // (phase oscillates Live<->Backfill for the newest block and - // catches up in a few ms). Rapid-sync `Deferred` (indexing - // intentionally paused) and the one-time `PreJade` activation - // boundary catch up on a much coarser timescale, so fail fast - // instead of burning the whole budget. - if matches!( - self.ctx.reference_index.phase(), - ReferenceIndexPhase::Deferred | ReferenceIndexPhase::PreJade - ) { - return Err(to_rpc_error(ReferenceIndexError::IndexBehind)); + if should_fail_fast(progress, tip_number) || watch_closed { + return Err(to_rpc_error(ReferenceIndexError::IndexBehind)); + } + + wait.begin_wait(); + loop { + match tokio::time::timeout_at(deadline, progress_rx.changed()).await { + Ok(Ok(())) => { + let updated = self.ctx.reference_index.progress(); + if updated.unavailable { + return Err(to_rpc_error( + ReferenceIndexError::IndexUnavailable, + )); + } + if matches!( + updated.phase, + ReferenceIndexPhase::Deferred | ReferenceIndexPhase::Repairing + ) || updated.indexed_to.is_some_and(|cur| { + tip_number.saturating_sub(cur) > MAX_STEADY_STATE_LAG + }) { + return Err(to_rpc_error(ReferenceIndexError::IndexBehind)); + } + // Entering `Backfill` notifies before the batch commits; if + // the durable cursor is still strictly below `tip_number`, + // keep waiting for the actual commit instead of opening a + // doomed MDBX read transaction. + if updated.phase == ReferenceIndexPhase::Backfill + && updated.indexed_to.is_some_and(|cur| cur < tip_number) + { + continue; + } + break; + } + Ok(Err(_closed)) => { + // Runtime shut down (watch sender dropped): perform one + // final recheck in case a terminal commit or `Unavailable` + // transition happened immediately before shutdown, then exit. + watch_closed = true; + break; + } + Err(_elapsed) => { + wait.mark_timed_out(); + return Err(to_rpc_error(ReferenceIndexError::IndexBehind)); + } } } - Err(other) => return Err(to_rpc_error(other)), } } - - wait.begin_wait(); - let Some(delay) = next_poll_delay(Instant::now(), deadline) else { - wait.mark_timed_out(); - return Err(to_rpc_error(ReferenceIndexError::IndexBehind)); - }; - std::thread::sleep(delay); } } } @@ -410,19 +476,11 @@ mod tests { } } - #[derive(Debug)] - struct ChainInfoGate { - call: usize, - calls: AtomicUsize, - reached: Arc, - released: Arc, - } - #[derive(Clone, Debug)] struct TestProvider { chain_info: Arc>>, headers: Arc>, - gate: Option>, + chain_info_calls: Arc, } impl TestProvider { @@ -433,30 +491,16 @@ mod tests { Self { chain_info: Arc::new(Mutex::new(chain_info.into_iter().collect())), headers: Arc::new(headers), - gate: None, + chain_info_calls: Arc::new(AtomicUsize::new(0)), } } - fn gate_chain_info_call(mut self, call: usize) -> (Self, Arc, Arc) { - let reached = Arc::new(Barrier::new(2)); - let released = Arc::new(Barrier::new(2)); - self.gate = Some(Arc::new(ChainInfoGate { - call, - calls: AtomicUsize::new(0), - reached: reached.clone(), - released: released.clone(), - })); - (self, reached, released) + fn chain_info_calls(&self) -> usize { + self.chain_info_calls.load(Ordering::Acquire) } fn info(&self) -> ChainInfo { - if let Some(gate) = &self.gate { - let call = gate.calls.fetch_add(1, Ordering::Relaxed) + 1; - if call == gate.call { - gate.reached.wait(); - gate.released.wait(); - } - } + self.chain_info_calls.fetch_add(1, Ordering::AcqRel); let mut infos = self.chain_info.lock().unwrap(); if infos.len() > 1 { infos.pop_front().unwrap() @@ -580,8 +624,8 @@ mod tests { } } - #[test] - fn rejects_results_if_canonical_head_changes_during_query() { + #[tokio::test] + async fn rejects_results_if_canonical_head_changes_during_query() { let indexed_hash = B256::repeat_byte(0x11); let changed_hash = B256::repeat_byte(0x22); let (_dir, handle) = synced_handle(0, 100, indexed_hash); @@ -602,14 +646,15 @@ mod tests { let error = handler .get_transaction_hashes_by_reference(args()) + .await .unwrap_err(); assert_eq!(error.code(), -32000); assert_eq!(error.message(), "reference index is behind"); } - #[test] - fn passes_the_exact_head_timestamp_to_the_index() { + #[tokio::test] + async fn passes_the_exact_head_timestamp_to_the_index() { let hash = B256::repeat_byte(0x11); let (_dir, handle) = synced_handle(200, 199, hash); let provider = TestProvider::new( @@ -623,14 +668,15 @@ mod tests { let error = handler .get_transaction_hashes_by_reference(args()) + .await .unwrap_err(); assert_eq!(error.code(), -32000); assert_eq!(error.message(), "reference index is behind"); } - #[test] - fn pre_jade_empty_result_is_rejected_if_head_crosses_jade() { + #[tokio::test] + async fn pre_jade_empty_result_is_rejected_if_head_crosses_jade() { let pre_jade_hash = B256::repeat_byte(0x11); let jade_hash = B256::repeat_byte(0x22); let (_dir, handle) = synced_handle(200, 199, pre_jade_hash); @@ -651,14 +697,15 @@ mod tests { let error = handler .get_transaction_hashes_by_reference(args()) + .await .expect_err("a head change across Jade must invalidate the empty snapshot"); assert_eq!(error.code(), -32000); assert_eq!(error.message(), "reference index is behind"); } - #[test] - fn changed_pre_jade_snapshot_retries_without_querying_the_opening_index() { + #[tokio::test] + async fn changed_pre_jade_snapshot_retries_without_querying_the_opening_index() { let first_hash = B256::repeat_byte(0x11); let second_hash = B256::repeat_byte(0x22); let handle = ReferenceIndexHandle::new(200); @@ -681,15 +728,18 @@ mod tests { ); let handler = MorphRpcHandler::new(MorphRpc::new(handle, provider)); - let results = handler.get_transaction_hashes_by_reference(args()).unwrap(); + let results = handler + .get_transaction_hashes_by_reference(args()) + .await + .unwrap(); assert!(results.is_empty()); } - #[test] - fn rapid_sync_deferred_fails_fast_without_burning_the_wait_budget() { + #[tokio::test] + async fn rapid_sync_deferred_fails_fast_without_burning_the_wait_budget() { // Rapid-sync `Deferred`: a post-Jade query must return `IndexBehind` - // promptly rather than sleeping out the full `INDEX_WAIT_TIMEOUT`, since + // promptly rather than waiting out the full `INDEX_WAIT_TIMEOUT`, since // the runtime will not catch up while indexing is intentionally paused. let dir = tempfile::tempdir().unwrap(); let hash = B256::repeat_byte(0x11); @@ -713,35 +763,90 @@ mod tests { }], BTreeMap::from([(hash, header(0, 100))]), ); - let handler = MorphRpcHandler::new(MorphRpc::new(handle, provider)); + let outcomes = Arc::new(Mutex::new(Vec::new())); + let observed = outcomes.clone(); + let handler = MorphRpcHandler::new(MorphRpc::new(handle, provider.clone())) + .with_wait_observer(move |timed_out| { + observed.lock().unwrap().push(timed_out); + }); + let started = std::time::Instant::now(); let error = handler .get_transaction_hashes_by_reference(args()) + .await .unwrap_err(); + drop(runtime); assert_eq!(error.message(), "reference index is behind"); + assert!(started.elapsed() < Duration::from_millis(100)); + assert!(outcomes.lock().unwrap().is_empty()); + assert_eq!(provider.chain_info_calls(), 1); } #[test] - fn poll_delay_never_exceeds_the_remaining_budget() { - let now = Instant::now(); + fn should_fail_fast_classifies_phases_and_steady_state_lag() { + let progress = |phase, indexed_to| ReferenceIndexProgress { + phase, + indexed_to, + unavailable: phase == ReferenceIndexPhase::Unavailable, + }; - assert_eq!(next_poll_delay(now, now), None); - assert_eq!( - next_poll_delay(now, now + Duration::from_millis(2)), - Some(Duration::from_millis(2)) - ); - assert_eq!( - next_poll_delay(now, now + Duration::from_millis(10)), - Some(INDEX_WAIT_POLL_INTERVAL) - ); + assert!(should_fail_fast( + progress(ReferenceIndexPhase::Deferred, Some(10)), + 10 + )); + assert!(should_fail_fast( + progress(ReferenceIndexPhase::PreJade, None), + 10 + )); + assert!(should_fail_fast( + progress(ReferenceIndexPhase::Repairing, Some(10)), + 10 + )); + + // Steady-state lag <= MAX_STEADY_STATE_LAG (2) is allowed to wait. + assert!(!should_fail_fast( + progress(ReferenceIndexPhase::Live, Some(10)), + 11 + )); + assert!(!should_fail_fast( + progress(ReferenceIndexPhase::Backfill, Some(10)), + 12 + )); + assert!(!should_fail_fast( + progress(ReferenceIndexPhase::Backfill, None), + 1 + )); + + // Lag > MAX_STEADY_STATE_LAG (2) fails fast. + assert!(should_fail_fast( + progress(ReferenceIndexPhase::Backfill, Some(10)), + 13 + )); + assert!(should_fail_fast( + progress(ReferenceIndexPhase::Live, Some(10)), + 13 + )); } - #[test] - fn live_lag_wait_eventually_returns_behind() { + #[tokio::test] + async fn live_lag_wait_eventually_returns_behind_without_polling() { + let dir = tempfile::tempdir().unwrap(); let indexed_hash = B256::repeat_byte(0x11); let head_hash = B256::repeat_byte(0x22); - let (_dir, handle) = synced_handle(0, 100, indexed_hash); + let chain = TestChain { + block: CanonicalBlock { + number: 0, + hash: indexed_hash, + timestamp: 100, + transactions: Vec::new(), + }, + }; + let config = ReferenceIndexConfig::new(dir.path(), 2818, B256::ZERO, 0); + // Keep `runtime` alive so the watch sender stays open and the wait hits the deadline. + let (mut runtime, handle) = ReferenceIndexRuntime::new(config, chain); + runtime.synchronize_once(false).unwrap(); + let provider = TestProvider::new( [ChainInfo { best_hash: head_hash, @@ -749,17 +854,27 @@ mod tests { }], BTreeMap::from([(head_hash, header(1, 101))]), ); - let handler = MorphRpcHandler::new(MorphRpc::new(handle, provider)); + let outcomes = Arc::new(Mutex::new(Vec::new())); + let observed = outcomes.clone(); + let handler = MorphRpcHandler::new(MorphRpc::new(handle, provider.clone())) + .with_wait_observer(move |timed_out| { + observed.lock().unwrap().push(timed_out); + }); let error = handler .get_transaction_hashes_by_reference(args()) + .await .unwrap_err(); + drop(runtime); assert_eq!(error.message(), "reference index is behind"); + assert_eq!(*outcomes.lock().unwrap(), [true]); + // Only the initial read occurred; no polling reads during the 300ms wait. + assert_eq!(provider.chain_info_calls(), 1); } - #[test] - fn live_lag_wait_returns_from_the_same_request_after_runtime_catches_up() { + #[tokio::test] + async fn live_lag_wait_returns_from_the_same_request_after_runtime_catches_up() { let dir = tempfile::tempdir().unwrap(); let indexed_hash = B256::repeat_byte(0x11); let head_hash = B256::repeat_byte(0x22); @@ -786,22 +901,325 @@ mod tests { }], BTreeMap::from([(head_hash, header(1, 101))]), ); - let (provider, second_attempt, catch_up_complete) = provider.gate_chain_info_call(2); - let catch_up = std::thread::spawn(move || { - second_attempt.wait(); - runtime.synchronize_once(false).unwrap(); - catch_up_complete.wait(); + let catch_up = tokio::spawn(async move { + tokio::time::sleep(Duration::from_millis(40)).await; + tokio::task::spawn_blocking(move || { + runtime.synchronize_once(false).unwrap(); + runtime + }) + .await + .unwrap() }); - let handler = MorphRpcHandler::new(MorphRpc::new(handle, provider)); + let handler = MorphRpcHandler::new(MorphRpc::new(handle, provider.clone())); - let results = handler.get_transaction_hashes_by_reference(args()).unwrap(); - catch_up.join().unwrap(); + let results = handler + .get_transaction_hashes_by_reference(args()) + .await + .unwrap(); + let _runtime = catch_up.await.unwrap(); assert!(results.is_empty()); + // Attempt 1 (`before`) + Attempt 2 (`before` + `after`) = 3 calls; zero polling. + assert_eq!(provider.chain_info_calls(), 3); } - #[test] - fn live_lag_wait_covers_a_200ms_catch_up() { + #[tokio::test] + async fn steady_state_lag_of_two_waits_and_succeeds_without_polling() { + let dir = tempfile::tempdir().unwrap(); + let hash0 = B256::repeat_byte(0x10); + let hash1 = B256::repeat_byte(0x11); + let hash2 = B256::repeat_byte(0x12); + let chain = GrowingTestChain::new(CanonicalBlock { + number: 0, + hash: hash0, + timestamp: 100, + transactions: Vec::new(), + }); + let config = ReferenceIndexConfig::new(dir.path(), 2818, B256::ZERO, 0); + let (mut runtime, handle) = ReferenceIndexRuntime::new(config, chain.clone()); + runtime.synchronize_once(false).unwrap(); + chain.push(CanonicalBlock { + number: 1, + hash: hash1, + timestamp: 101, + transactions: Vec::new(), + }); + chain.push(CanonicalBlock { + number: 2, + hash: hash2, + timestamp: 102, + transactions: Vec::new(), + }); + + let provider = TestProvider::new( + [ChainInfo { + best_hash: hash2, + best_number: 2, + }], + BTreeMap::from([(hash2, header(2, 102))]), + ); + let catch_up = tokio::spawn(async move { + tokio::time::sleep(Duration::from_millis(40)).await; + tokio::task::spawn_blocking(move || { + runtime.synchronize_once(false).unwrap(); + runtime + }) + .await + .unwrap() + }); + let handler = MorphRpcHandler::new(MorphRpc::new(handle, provider.clone())); + + let results = handler + .get_transaction_hashes_by_reference(args()) + .await + .unwrap(); + let _runtime = catch_up.await.unwrap(); + + assert!(results.is_empty()); + assert_eq!(provider.chain_info_calls(), 3); + } + + #[tokio::test] + async fn backfill_lag_above_two_fails_fast_without_waiting() { + let dir = tempfile::tempdir().unwrap(); + let hash0 = B256::repeat_byte(0x10); + let hash3 = B256::repeat_byte(0x13); + let chain = TestChain { + block: CanonicalBlock { + number: 0, + hash: hash0, + timestamp: 100, + transactions: Vec::new(), + }, + }; + let config = ReferenceIndexConfig::new(dir.path(), 2818, B256::ZERO, 0); + let (mut runtime, handle) = ReferenceIndexRuntime::new(config, chain); + runtime.synchronize_once(false).unwrap(); + + let provider = TestProvider::new( + [ChainInfo { + best_hash: hash3, + best_number: 3, + }], + BTreeMap::from([(hash3, header(3, 103))]), + ); + let outcomes = Arc::new(Mutex::new(Vec::new())); + let observed = outcomes.clone(); + let handler = MorphRpcHandler::new(MorphRpc::new(handle, provider.clone())) + .with_wait_observer(move |timed_out| { + observed.lock().unwrap().push(timed_out); + }); + + let started = std::time::Instant::now(); + let error = handler + .get_transaction_hashes_by_reference(args()) + .await + .unwrap_err(); + drop(runtime); + + assert_eq!(error.message(), "reference index is behind"); + assert!( + started.elapsed() < Duration::from_millis(100), + "lag > 2 must fail fast without waiting" + ); + assert!(outcomes.lock().unwrap().is_empty()); + assert_eq!(provider.chain_info_calls(), 1); + } + + #[tokio::test] + async fn repairing_phase_fails_fast_without_waiting() { + #[derive(Clone, Debug)] + struct PausingReorgChain { + blocks: Arc>>, + pause_on_hash_of: Arc>>, + entered_repair: Arc, + release_repair: Arc, + } + + impl CanonicalChain for PausingReorgChain { + fn head(&self) -> Result { + let blocks = self.blocks.lock().unwrap(); + let block = blocks.last().unwrap(); + Ok(CanonicalTip { + number: block.number, + hash: block.hash, + timestamp: block.timestamp, + }) + } + + fn canonical_hash(&self, number: u64) -> Result, ReferenceIndexError> { + let should_pause = { + let mut target = self.pause_on_hash_of.lock().unwrap(); + if *target == Some(number) { + *target = None; + true + } else { + false + } + }; + if should_pause { + self.entered_repair.wait(); + self.release_repair.wait(); + } + Ok(self + .blocks + .lock() + .unwrap() + .iter() + .find_map(|block| (block.number == number).then_some(block.hash))) + } + + fn block_timestamp(&self, number: u64) -> Result, ReferenceIndexError> { + Ok(self + .blocks + .lock() + .unwrap() + .iter() + .find_map(|block| (block.number == number).then_some(block.timestamp))) + } + + fn finalized_block_number(&self) -> Result, ReferenceIndexError> { + Ok(None) + } + + fn canonical_blocks( + &self, + range: RangeInclusive, + ) -> Result, ReferenceIndexError> { + Ok(self + .blocks + .lock() + .unwrap() + .iter() + .filter(|block| range.contains(&block.number)) + .cloned() + .collect()) + } + } + + let dir = tempfile::tempdir().unwrap(); + let entered_repair = Arc::new(Barrier::new(2)); + let release_repair = Arc::new(Barrier::new(2)); + let reorg_hash = B256::repeat_byte(0x99); + let chain = PausingReorgChain { + blocks: Arc::new(Mutex::new(vec![ + CanonicalBlock { + number: 0, + hash: B256::repeat_byte(0x10), + timestamp: 100, + transactions: Vec::new(), + }, + CanonicalBlock { + number: 1, + hash: B256::repeat_byte(0x11), + timestamp: 101, + transactions: Vec::new(), + }, + ])), + pause_on_hash_of: Arc::new(Mutex::new(None)), + entered_repair: entered_repair.clone(), + release_repair: release_repair.clone(), + }; + let config = ReferenceIndexConfig::new(dir.path(), 2818, B256::ZERO, 0); + let (mut runtime, handle) = ReferenceIndexRuntime::new(config, chain.clone()); + runtime.synchronize_once(false).unwrap(); + + // Trigger a reorg on block 1 and pause inside `reconcile_cursor` after + // `ReferenceIndexPhase::Repairing` has been published. + chain.blocks.lock().unwrap()[1].hash = reorg_hash; + *chain.pause_on_hash_of.lock().unwrap() = Some(1); + let repair_thread = std::thread::spawn(move || { + runtime.synchronize_once(false).unwrap(); + runtime + }); + entered_repair.wait(); + assert_eq!(handle.phase(), ReferenceIndexPhase::Repairing); + + let provider = TestProvider::new( + [ChainInfo { + best_hash: reorg_hash, + best_number: 1, + }], + BTreeMap::from([(reorg_hash, header(1, 101))]), + ); + let outcomes = Arc::new(Mutex::new(Vec::new())); + let observed = outcomes.clone(); + let handler = MorphRpcHandler::new(MorphRpc::new(handle, provider.clone())) + .with_wait_observer(move |timed_out| { + observed.lock().unwrap().push(timed_out); + }); + + let started = std::time::Instant::now(); + let error = handler + .get_transaction_hashes_by_reference(args()) + .await + .unwrap_err(); + release_repair.wait(); + let _runtime = repair_thread.join().unwrap(); + + assert_eq!(error.message(), "reference index is behind"); + assert!(started.elapsed() < Duration::from_millis(100)); + assert!(outcomes.lock().unwrap().is_empty()); + assert_eq!(provider.chain_info_calls(), 1); + } + + #[tokio::test] + async fn watch_sender_drop_wakes_waiter_and_exits_immediately() { + let dir = tempfile::tempdir().unwrap(); + let indexed_hash = B256::repeat_byte(0x11); + let head_hash = B256::repeat_byte(0x22); + let chain = TestChain { + block: CanonicalBlock { + number: 0, + hash: indexed_hash, + timestamp: 100, + transactions: Vec::new(), + }, + }; + let config = ReferenceIndexConfig::new(dir.path(), 2818, B256::ZERO, 0); + let (mut runtime, handle) = ReferenceIndexRuntime::new(config, chain); + runtime.synchronize_once(false).unwrap(); + + let provider = TestProvider::new( + [ChainInfo { + best_hash: head_hash, + best_number: 1, + }], + BTreeMap::from([(head_hash, header(1, 101))]), + ); + let outcomes = Arc::new(Mutex::new(Vec::new())); + let observed = outcomes.clone(); + let handler = MorphRpcHandler::new(MorphRpc::new(handle, provider.clone())) + .with_wait_observer(move |timed_out| { + observed.lock().unwrap().push(timed_out); + }); + + // Drop the runtime while the RPC call is awaiting `progress_rx.changed()`. + let shutdown = tokio::spawn(async move { + tokio::time::sleep(Duration::from_millis(40)).await; + drop(runtime); + }); + + let started = std::time::Instant::now(); + let error = handler + .get_transaction_hashes_by_reference(args()) + .await + .unwrap_err(); + shutdown.await.unwrap(); + + assert_eq!(error.message(), "reference index is behind"); + assert!( + started.elapsed() < Duration::from_millis(180), + "dropped watch sender must wake and exit before the 300ms timeout (elapsed {:?})", + started.elapsed() + ); + assert_eq!(*outcomes.lock().unwrap(), [false]); + // Initial read + one final recheck after sender drop. + assert_eq!(provider.chain_info_calls(), 2); + } + + #[tokio::test] + async fn live_lag_wait_covers_a_200ms_catch_up() { let dir = tempfile::tempdir().unwrap(); let indexed_hash = B256::repeat_byte(0x11); let head_hash = B256::repeat_byte(0x22); @@ -828,23 +1246,29 @@ mod tests { }], BTreeMap::from([(head_hash, header(1, 101))]), ); - let catch_up = std::thread::spawn(move || { - std::thread::sleep(Duration::from_millis(200)); - runtime.synchronize_once(false).unwrap(); + let catch_up = tokio::spawn(async move { + tokio::time::sleep(Duration::from_millis(200)).await; + tokio::task::spawn_blocking(move || { + runtime.synchronize_once(false).unwrap(); + runtime + }) + .await + .unwrap() }); - let handler = MorphRpcHandler::new(MorphRpc::new(handle, provider)); + let handler = MorphRpcHandler::new(MorphRpc::new(handle, provider.clone())); - let result = handler.get_transaction_hashes_by_reference(args()); - catch_up.join().unwrap(); + let result = handler.get_transaction_hashes_by_reference(args()).await; + let _runtime = catch_up.await.unwrap(); assert!( result.is_ok(), "a live query should wait for a 200ms index catch-up: {result:?}" ); + assert_eq!(provider.chain_info_calls(), 3); } - #[test] - fn deferred_transition_after_wait_is_not_counted_as_a_timeout() { + #[tokio::test] + async fn deferred_transition_after_wait_is_not_counted_as_a_timeout() { let dir = tempfile::tempdir().unwrap(); let indexed_hash = B256::repeat_byte(0x11); let head_hash = B256::repeat_byte(0x22); @@ -871,33 +1295,38 @@ mod tests { }], BTreeMap::from([(head_hash, header(1, 101))]), ); - let (provider, second_attempt, transition_complete) = provider.gate_chain_info_call(2); - let transition = std::thread::spawn(move || { - second_attempt.wait(); - runtime.synchronize_once(true).unwrap(); - transition_complete.wait(); + let transition = tokio::spawn(async move { + tokio::time::sleep(Duration::from_millis(40)).await; + tokio::task::spawn_blocking(move || { + runtime.synchronize_once(true).unwrap(); + runtime + }) + .await + .unwrap() }); let phase = handle.clone(); let outcomes = Arc::new(Mutex::new(Vec::new())); let observed_outcomes = outcomes.clone(); - let handler = MorphRpcHandler::new(MorphRpc::new(handle, provider)).with_wait_observer( - move |timed_out| { + let handler = MorphRpcHandler::new(MorphRpc::new(handle, provider.clone())) + .with_wait_observer(move |timed_out| { observed_outcomes.lock().unwrap().push(timed_out); - }, - ); + }); let error = handler .get_transaction_hashes_by_reference(args()) + .await .unwrap_err(); - transition.join().unwrap(); + let _runtime = transition.await.unwrap(); assert_eq!(error.message(), "reference index is behind"); assert_eq!(phase.phase(), ReferenceIndexPhase::Deferred); assert_eq!(*outcomes.lock().unwrap(), [false]); + // Woke on watch transition to `Deferred` and exited without another blocking read. + assert_eq!(provider.chain_info_calls(), 1); } - #[test] - fn provider_failure_after_wait_is_observed_without_a_timeout() { + #[tokio::test] + async fn provider_failure_after_wait_is_observed_without_a_timeout() { let indexed_hash = B256::repeat_byte(0x11); let head_hash = B256::repeat_byte(0x22); let missing_header_hash = B256::repeat_byte(0x33); @@ -925,6 +1354,7 @@ mod tests { let error = handler .get_transaction_hashes_by_reference(args()) + .await .unwrap_err(); assert_eq!(error.message(), "reference index is behind"); diff --git a/crates/rpc/src/morph/rpc.rs b/crates/rpc/src/morph/rpc.rs index a888ab30..2e5d542d 100644 --- a/crates/rpc/src/morph/rpc.rs +++ b/crates/rpc/src/morph/rpc.rs @@ -41,9 +41,12 @@ pub trait MorphRpc { /// non-recoverable index error makes the runtime unavailable. A repair in /// progress is reported as `"reference index is behind"`. /// - /// Marked `blocking` because the handler runs synchronous MDBX reads. - #[method(name = "getTransactionHashesByReference", blocking)] - fn get_transaction_hashes_by_reference( + /// Runs asynchronously: each MDBX/provider read executes on Tokio's + /// blocking pool, while any bounded steady-state catch-up wait parks on + /// the index runtime's `watch` progress channel without holding a blocking + /// thread or polling MDBX. + #[method(name = "getTransactionHashesByReference")] + async fn get_transaction_hashes_by_reference( &self, args: ReferenceQueryArgs, ) -> RpcResult>; diff --git a/crates/txpool/src/maintain.rs b/crates/txpool/src/maintain.rs index 2bbb571c..5802ab15 100644 --- a/crates/txpool/src/maintain.rs +++ b/crates/txpool/src/maintain.rs @@ -507,7 +507,12 @@ mod tests { } } - fn token_fee_tx(nonce: u64, token_id: u16, value: U256, gas_limit: u64) -> MorphPooledTransaction { + fn token_fee_tx( + nonce: u64, + token_id: u16, + value: U256, + gas_limit: u64, + ) -> MorphPooledTransaction { let tx = TxMorph { chain_id: 2818, nonce, @@ -520,13 +525,19 @@ mod tests { fee_limit: U256::ZERO, ..Default::default() }; - let envelope = MorphTxEnvelope::Morph(Signed::new_unhashed(tx, Signature::test_signature())); + let envelope = + MorphTxEnvelope::Morph(Signed::new_unhashed(tx, Signature::test_signature())); let recovered = Recovered::new_unchecked(envelope, SIGNER); let len = recovered.encode_2718_len(); MorphPooledTransaction::new(recovered, len) } - fn legacy_tx(nonce: u64, gas_limit: u64, gas_price: u128, value: U256) -> MorphPooledTransaction { + fn legacy_tx( + nonce: u64, + gas_limit: u64, + gas_price: u128, + value: U256, + ) -> MorphPooledTransaction { let tx = TxLegacy { chain_id: Some(2818), nonce, @@ -536,7 +547,8 @@ mod tests { value, input: Bytes::new(), }; - let envelope = MorphTxEnvelope::Legacy(Signed::new_unhashed(tx, Signature::test_signature())); + let envelope = + MorphTxEnvelope::Legacy(Signed::new_unhashed(tx, Signature::test_signature())); let recovered = Recovered::new_unchecked(envelope, SIGNER); let len = recovered.encode_2718_len(); MorphPooledTransaction::new(recovered, len) @@ -561,11 +573,14 @@ mod tests { } db.insert_account_info( &token, - AccountInfo::default().with_code(Bytecode::new_legacy(Bytes::from_static( - BALANCE_OF_RUNTIME, - ))), + AccountInfo::default() + .with_code(Bytecode::new_legacy(Bytes::from_static(BALANCE_OF_RUNTIME))), + ); + db.insert_account_storage( + &token, + &token_balance_key(SIGNER), + &U256::from(token_balance), ); - db.insert_account_storage(&token, &token_balance_key(SIGNER), &U256::from(token_balance)); } #[test] @@ -750,7 +765,7 @@ mod tests { let p_initial = make_provider(3 * TX_TOKEN_BUDGET, &head0); let validator = crate::MorphTransactionValidator::new( EthTransactionValidatorBuilder::new( - p_initial.clone(), + p_initial, MorphEvmConfig::new_with_default_factory(MORPH_MAINNET.clone()), ) .disable_balance_check() @@ -784,7 +799,8 @@ mod tests { // At judged block (head0) balance dropped to 0, but at canonical head (head1) balance // recovered to 1*budget: tx0 must be removed, tx1 must survive parked in queued! struct TwoBlockSource { - states: HashMap>, + states: + HashMap>, head: SealedHeader, } impl FeeStateSource for TwoBlockSource { @@ -813,7 +829,7 @@ mod tests { }; let sealed_block0 = reth_primitives_traits::RecoveredBlock::new_unhashed( - morph_primitives::Block::new(head0.clone(), Default::default()), + morph_primitives::Block::new(head0, Default::default()), Vec::new(), ); let chain = Arc::new(reth_provider::Chain::new( @@ -847,13 +863,20 @@ mod tests { } impl Database for CountingDb { type Error = std::convert::Infallible; - fn get_account(&mut self, address: &Address) -> Result, Self::Error> { + fn get_account( + &mut self, + address: &Address, + ) -> Result, Self::Error> { Ok(DynDatabase::get_account(&mut self.inner, address).unwrap()) } fn get_code_by_hash(&mut self, code_hash: &B256) -> Result { Ok(DynDatabase::get_code_by_hash(&mut self.inner, code_hash).unwrap()) } - fn get_storage(&mut self, address: &Address, index: &U256) -> Result { + fn get_storage( + &mut self, + address: &Address, + index: &U256, + ) -> Result { *self.reads.entry(*address).or_default() += 1; Ok(DynDatabase::get_storage(&mut self.inner, address, index).unwrap()) } diff --git a/crates/txpool/src/morph_tx_validation.rs b/crates/txpool/src/morph_tx_validation.rs index 5b87d5f7..3e8edac4 100644 --- a/crates/txpool/src/morph_tx_validation.rs +++ b/crates/txpool/src/morph_tx_validation.rs @@ -262,10 +262,7 @@ pub(crate) mod tests { } /// Registry storage entries for an active 1:1 call-mode fee token (`balance_slot == 0`). - pub(crate) fn call_mode_registry_storage( - token_id: u16, - token: Address, - ) -> [(U256, U256); 5] { + pub(crate) fn call_mode_registry_storage(token_id: u16, token: Address) -> [(U256, U256); 5] { let mut key = [0u8; 32]; key[30..32].copy_from_slice(&token_id.to_be_bytes()); let base = compute_mapping_slot(U256::from(151), &key); @@ -472,7 +469,10 @@ pub(crate) mod tests { let mut db = EmptyDB::default(); let err = validate_morph_tx(&mut db, &input).unwrap_err(); - assert_eq!(err, MorphTxValidationError::Invalid(MorphTxError::InvalidTokenId)); + assert_eq!( + err, + MorphTxValidationError::Invalid(MorphTxError::InvalidTokenId) + ); } #[test] @@ -560,7 +560,8 @@ pub(crate) mod tests { assert_eq!( err, MorphTxValidationError::Invalid(MorphTxError::ForkNotActive { - reason: "MorphTx version 2 is not yet active (celadon fork not reached)".to_string(), + reason: "MorphTx version 2 is not yet active (celadon fork not reached)" + .to_string(), }) ); diff --git a/crates/txpool/src/validator.rs b/crates/txpool/src/validator.rs index fd73cc83..66ddbadc 100644 --- a/crates/txpool/src/validator.rs +++ b/crates/txpool/src/validator.rs @@ -27,7 +27,9 @@ use reth_primitives_traits::{ BlockTy, GotExpected, HeaderTy, SealedBlock, SealedHeader, transaction::error::InvalidTransactionError, }; -use reth_storage_api::{BlockReaderIdExt, StateProvider as _, StateProviderBox, StateProviderFactory}; +use reth_storage_api::{ + BlockReaderIdExt, StateProvider as _, StateProviderBox, StateProviderFactory, +}; use reth_transaction_pool::{ EthPoolTransaction, EthTransactionValidator, PoolTransaction, TransactionOrigin, TransactionValidationOutcome, TransactionValidator, error::InvalidPoolTransactionError, @@ -459,7 +461,9 @@ where // MorphTx payloads are rejected without paying for DB / account / authority reads. if is_morph_tx { let stateless_res = match transaction.consensus_ref().into_inner() { - MorphTxEnvelope::Morph(signed) => validate_morph_tx_stateless(signed.tx(), hardfork), + MorphTxEnvelope::Morph(signed) => { + validate_morph_tx_stateless(signed.tx(), hardfork) + } _ => Err(MorphTxError::InvalidTokenId), }; if let Err(err) = stateless_res { @@ -707,12 +711,7 @@ where transactions .into_iter() .map(|(origin, tx)| { - self.validate_one_with_snapshot( - origin, - tx, - &snapshot, - Some(&mut token_validator), - ) + self.validate_one_with_snapshot(origin, tx, &snapshot, Some(&mut token_validator)) }) .collect() } @@ -781,9 +780,10 @@ fn morph_tx_validation_outcome( err: MorphTxValidationError, ) -> TransactionValidationOutcome { match err { - MorphTxValidationError::State(err) => { - TransactionValidationOutcome::Error(*transaction.hash(), Box::new(std::io::Error::other(err))) - } + MorphTxValidationError::State(err) => TransactionValidationOutcome::Error( + *transaction.hash(), + Box::new(std::io::Error::other(err)), + ), MorphTxValidationError::Invalid(err) => { TransactionValidationOutcome::Invalid(transaction, err.into()) } @@ -865,7 +865,10 @@ mod tests { let token_account = ExtendedAccount::new(0, U256::ZERO) .with_bytecode(Bytes::copy_from_slice(runtime)) .extend_storage([(storage_key(token_balance_key(payer)), token_balance)]); - [(L2_TOKEN_REGISTRY_ADDRESS, registry), (token, token_account)] + [ + (L2_TOKEN_REGISTRY_ADDRESS, registry), + (token, token_account), + ] } fn head_at(number: u64, timestamp: u64, gas_limit: u64) -> MorphHeader { @@ -1044,13 +1047,15 @@ mod tests { client.add_account(SIGNER, ExtendedAccount::new(0, U256::ZERO)); // Cap at 1_000_000 wei; tx budget is 21_000 * 100 = 2_100_000 wei > cap. - let validator = - validator_at_head(client, head_at(1, 2_000_000_000, 30_000_000), 1_000_000); + let validator = validator_at_head(client, head_at(1, 2_000_000_000, 30_000_000), 1_000_000); let tx = pooled_morph_tx(0, 1, 21_000, 100, U256::ZERO, U256::ZERO); let outcome = validator.validate_one(TransactionOrigin::Local, tx); assert!(matches!( outcome, - TransactionValidationOutcome::Invalid(_, InvalidPoolTransactionError::ExceedsFeeCap { .. }) + TransactionValidationOutcome::Invalid( + _, + InvalidPoolTransactionError::ExceedsFeeCap { .. } + ) )); } From 35bd40bf71ec734b3232c2f2ab15ecef0ae8bfab Mon Sep 17 00:00:00 2001 From: panos-xyz Date: Fri, 27 Nov 2026 15:34:57 +0800 Subject: [PATCH 09/16] fix(txpool): run MorphTx format checks after inner stateless validation --- crates/txpool/src/morph_tx_validation.rs | 31 +++++++-- crates/txpool/src/validator.rs | 83 ++++++++++++++++++++++-- 2 files changed, 102 insertions(+), 12 deletions(-) diff --git a/crates/txpool/src/morph_tx_validation.rs b/crates/txpool/src/morph_tx_validation.rs index 3e8edac4..fba0fe6c 100644 --- a/crates/txpool/src/morph_tx_validation.rs +++ b/crates/txpool/src/morph_tx_validation.rs @@ -70,12 +70,11 @@ pub fn validate_morph_tx( }) } -/// Validates stateless MorphTx fork gates and structural invariants without any DB access. +/// Validates MorphTx hardfork version gates (Jade V1 / Celadon V2) without any DB access. /// -/// Called early in [`MorphTransactionValidator`](crate::MorphTransactionValidator) before -/// state lookups, and again inside [`validate_morph_tx_with`] so background revalidation -/// enforces the exact same rules. -pub(crate) fn validate_morph_tx_stateless( +/// Runs before `EthTransactionValidator::validate_stateless` so peers one block ahead across +/// a hardfork boundary always receive non-penalizing [`MorphTxError::ForkNotActive`]. +pub(crate) fn validate_morph_tx_fork_gate( morph_tx: &TxMorph, hardfork: MorphHardfork, ) -> Result<(), MorphTxError> { @@ -96,6 +95,16 @@ pub(crate) fn validate_morph_tx_stateless( }); } + Ok(()) +} + +/// Validates MorphTx-specific structural invariants (`TxMorph::validate`) without any DB access. +/// +/// Runs after `EthTransactionValidator::validate_stateless` (so shared checks like +/// `max_priority_fee_per_gas > max_fee_per_gas` return upstream `TipAboveFeeCap` with +/// `is_bad_transaction() == false`, matching EIP-1559/EIP-7702) and before +/// `EthTransactionValidator::validate_stateful` (so malformed payloads skip DB lookups). +pub(crate) fn validate_morph_tx_format(morph_tx: &TxMorph) -> Result<(), MorphTxError> { if let Err(reason) = morph_tx.validate() { return Err(MorphTxError::InvalidFormat { reason: reason.to_string(), @@ -105,6 +114,18 @@ pub(crate) fn validate_morph_tx_stateless( Ok(()) } +/// Validates stateless MorphTx fork gates and structural invariants without any DB access. +/// +/// Used inside [`validate_morph_tx_with`] so background revalidation enforces the exact +/// same rules as initial admission. +pub(crate) fn validate_morph_tx_stateless( + morph_tx: &TxMorph, + hardfork: MorphHardfork, +) -> Result<(), MorphTxError> { + validate_morph_tx_fork_gate(morph_tx, hardfork)?; + validate_morph_tx_format(morph_tx) +} + /// Validates a MorphTx transaction using a caller-supplied fee-token resolver. /// /// Structural rules, ETH `value` coverage, and `fee_token_id == 0` ETH-fee checks run before diff --git a/crates/txpool/src/validator.rs b/crates/txpool/src/validator.rs index 66ddbadc..373064b8 100644 --- a/crates/txpool/src/validator.rs +++ b/crates/txpool/src/validator.rs @@ -11,7 +11,9 @@ use crate::{ MorphTxError, MorphTxValidationError, - morph_tx_validation::{validate_morph_tx_stateless, validate_morph_tx_with}, + morph_tx_validation::{ + validate_morph_tx_fork_gate, validate_morph_tx_format, validate_morph_tx_with, + }, state_cache::{StateCache, StateCacheDb, TokenFeeValidator}, }; use alloy_consensus::{BlockHeader, Sealable, Transaction}; @@ -456,17 +458,17 @@ where let hardfork = head.evm_env.spec; - // Run stateless MorphTx fork gates (Jade V1 / Celadon V2) and structural checks - // (`TxMorph::validate`) BEFORE `inner.validate_stateful` so malformed or pre-fork - // MorphTx payloads are rejected without paying for DB / account / authority reads. + // Run MorphTx hardfork version gates (Jade V1 / Celadon V2) before upstream + // stateless validation so peers one block ahead across a fork boundary always + // get non-penalizing `ForkNotActive`. if is_morph_tx { - let stateless_res = match transaction.consensus_ref().into_inner() { + let fork_gate_res = match transaction.consensus_ref().into_inner() { MorphTxEnvelope::Morph(signed) => { - validate_morph_tx_stateless(signed.tx(), hardfork) + validate_morph_tx_fork_gate(signed.tx(), hardfork) } _ => Err(MorphTxError::InvalidTokenId), }; - if let Err(err) = stateless_res { + if let Err(err) = fork_gate_res { return TransactionValidationOutcome::Invalid(transaction, err.into()); } } @@ -520,6 +522,22 @@ where if let Err(err) = self.inner.validate_stateless(origin, &transaction) { return TransactionValidationOutcome::Invalid(transaction, err); } + + // Run MorphTx-specific structural checks (`TxMorph::validate`) AFTER + // `inner.validate_stateless` — so shared checks like `tip > feeCap` keep + // upstream `InvalidTransactionError::TipAboveFeeCap` (`is_bad_transaction() == false`, + // standard RPC error, and metrics) — and BEFORE `inner.validate_stateful` so + // malformed MorphTx payloads never pay for DB / account / authority reads. + if is_morph_tx { + let format_res = match transaction.consensus_ref().into_inner() { + MorphTxEnvelope::Morph(signed) => validate_morph_tx_format(signed.tx()), + _ => Err(MorphTxError::InvalidTokenId), + }; + if let Err(err) = format_res { + return TransactionValidationOutcome::Invalid(transaction, err.into()); + } + } + let outcome = self .inner .validate_stateful(origin, transaction, &state.provider); @@ -1032,6 +1050,57 @@ mod tests { ); } + #[test] + fn morph_tx_tip_above_fee_cap_returns_standard_non_penalizing_error() { + use alloy_primitives::TxHash; + use reth_transaction_pool::error::PoolError; + + let client = new_mock_provider(); + let validator = validator_at_head(client, head_at(1, 2_000_000_000, 30_000_000), 0); + + let tx = TxMorph { + chain_id: MORPH_MAINNET.chain().id(), + nonce: 0, + gas_limit: 21_000, + max_fee_per_gas: 100, + max_priority_fee_per_gas: 200, + to: TxKind::Call(address!("0000000000000000000000000000000000000002")), + value: U256::ZERO, + access_list: Default::default(), + version: 1, + fee_token_id: 0, + fee_limit: U256::ZERO, + reference: None, + memo: None, + authorization_list: Vec::new(), + input: Bytes::new(), + }; + let envelope = MorphTxEnvelope::Morph(Signed::new_unchecked( + tx, + Signature::test_signature(), + B256::ZERO, + )); + let recovered = Recovered::new_unchecked(envelope, SIGNER); + let len = recovered.encode_2718_len(); + let pooled = MorphPooledTransaction::new(recovered, len); + + let outcome = validator.validate_one(TransactionOrigin::External, pooled); + let TransactionValidationOutcome::Invalid(_, err) = outcome else { + panic!("expected tip > feeCap MorphTx to be rejected"); + }; + assert!( + matches!( + err, + InvalidPoolTransactionError::Consensus(InvalidTransactionError::TipAboveFeeCap) + ), + "expected upstream TipAboveFeeCap error, got: {err:?}" + ); + assert!( + !PoolError::new(TxHash::ZERO, err).is_bad_transaction(), + "MorphTx tip > feeCap must match EIP-1559 and not penalize peers" + ); + } + #[test] fn local_token_fee_morph_tx_still_enforces_tx_fee_cap() { let client = new_mock_provider(); From 448ef270d5384b2d26289c56e58f2d98cff7d984 Mon Sep 17 00:00:00 2001 From: panos-xyz Date: Fri, 4 Dec 2026 11:39:32 +0800 Subject: [PATCH 10/16] feat(v2.0.0): align PR #229 with v1.6.0 finals and close remaining audit items - Sync finalized semantics of PRs #237, #238, #239, #240, #241, #244, #247, #248, and #249 natively on reth v2.11.0 + evm2: - Proofs ExEx revert retry state machine, zeroed-slot storage pruning, and Reference Index batch parent linkage & async RPC polling - Safe validation exemptions (is_safe + safe_blocks FIFO), tree_headers cache, pre/post-Jade next_l1_msg_index & unhashed header checks, synchronized pool eviction, and no_tx_pool forward skip - Delegate eth_simulateV1 to upstream with 65B placeholder-sig Curie L1 fee encoding (validation:true), zero L1 fee (validation:false), and normalize_simulate_call - Enforce --rpc.gascap (0 = unlimited) across eth_call/eth_callMany/eth_estimateGas and honor blockOverrides.gasLimit above header gas_limit ([MR-10], [MR-12]) - Close unfixed audit items: - [MR-03]: Reload live (token_address, balance_slot) from L2TokenRegistry during post-execution token fee reimbursement while keeping deduction-time rates - [MR-14]: Rewind orphaned safe block tag to canonical finalized (or genesis) on engine_newL2BlockV2 reorgs and warm BlockTagTracker on startup - TxPool Option A: Enforce U256 price bump uniformly on priority_fee_or_price() across Legacy and dynamic-fee replacements - Restore SP1 zkVM quanta-free dependency graph on morph-revm and morph-evm - Bump workspace version to 2.0.0, resolve RUSTSEC advisories, and clear CodeQL test false positives --- Cargo.lock | 96 +- Cargo.toml | 6 +- bin/morph-reth/Cargo.toml | 2 +- crates/consensus/Cargo.toml | 2 +- crates/consensus/src/validation.rs | 467 ++++- crates/engine-api/src/builder.rs | 187 +- crates/evm/Cargo.toml | 19 +- crates/evm/src/block/mod.rs | 13 +- crates/evm/src/block/simulate.rs | 90 + crates/evm/src/config.rs | 7 +- crates/node/src/add_ons.rs | 4 +- crates/node/src/components/pool.rs | 6 +- crates/node/src/test_utils.rs | 83 +- crates/node/src/validator.rs | 464 +++-- crates/node/tests/it/engine.rs | 435 +++++ .../node/tests/it/invalid_payload_recovery.rs | 215 ++- crates/node/tests/it/morph_tx.rs | 230 +++ crates/node/tests/it/rpc.rs | 1640 ++++++++++++----- crates/node/tests/it/txpool.rs | 72 +- crates/payload/builder/Cargo.toml | 4 +- crates/payload/builder/src/builder.rs | 327 +++- crates/payload/types/src/lib.rs | 40 +- crates/proofs-exex/Cargo.toml | 2 +- crates/proofs-exex/src/lib.rs | 110 +- crates/proofs/src/db/store.rs | 84 +- crates/reference-index/src/backfill.rs | 20 +- crates/reference-index/src/lib.rs | 2 +- crates/reference-index/src/reader.rs | 77 +- crates/reference-index/src/runtime.rs | 312 ++-- crates/reference-index/src/source.rs | 4 + crates/revm/src/handler.rs | 324 +++- crates/revm/src/lib.rs | 2 +- crates/revm/src/token_fee.rs | 31 + crates/revm/src/tx.rs | 216 ++- crates/rpc/Cargo.toml | 2 - crates/rpc/src/eth/call.rs | 758 +++----- crates/rpc/src/eth/transaction.rs | 135 ++ crates/rpc/src/morph/handler.rs | 673 +++---- crates/rpc/src/morph/rpc.rs | 5 +- crates/txpool/Cargo.toml | 4 +- crates/txpool/src/transaction.rs | 45 +- crates/txpool/src/validator.rs | 28 +- deny.toml | 6 + 43 files changed, 5070 insertions(+), 2179 deletions(-) create mode 100644 crates/evm/src/block/simulate.rs diff --git a/Cargo.lock b/Cargo.lock index 9576c9eb..cb0fb300 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1362,6 +1362,12 @@ dependencies = [ "rand 0.8.6", ] +[[package]] +name = "array-const-fn-init" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8bcb85e548c05d407fa6faff46b750ba287714ef32afc0f5e15b4641ffd6affb" + [[package]] name = "arrayref" version = "0.3.9" @@ -2216,16 +2222,6 @@ dependencies = [ "unicode-segmentation", ] -[[package]] -name = "core-foundation" -version = "0.9.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" -dependencies = [ - "core-foundation-sys", - "libc", -] - [[package]] name = "core-foundation" version = "0.10.1" @@ -3287,9 +3283,9 @@ checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" [[package]] name = "form_urlencoded" -version = "1.2.2" +version = "1.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" dependencies = [ "percent-encoding", ] @@ -3704,9 +3700,9 @@ dependencies = [ [[package]] name = "hickory-net" -version = "0.26.3" +version = "0.26.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c480823ed7c2c5d0f09c41020cb6b7c28029ce60ec42dc942158dcf22f8e0a4d" +checksum = "ea9b43710d47761c90da994eeec7e1bee50095f2b4bcdfd42acd67ca5f814e47" dependencies = [ "async-trait", "cfg-if", @@ -3728,9 +3724,9 @@ dependencies = [ [[package]] name = "hickory-proto" -version = "0.26.3" +version = "0.26.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12b92608f679a6fa515dd1d15c1ff89443026e391200a2c840c7afcba482893d" +checksum = "927c672dc4fd1e4b7cfcb7b751fe1d5766638080b8d243b78165ef660c2061e7" dependencies = [ "data-encoding", "idna", @@ -3749,9 +3745,9 @@ dependencies = [ [[package]] name = "hickory-resolver" -version = "0.26.3" +version = "0.26.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f3da5255c95d5a716857d54b5b8f4e8d67c3484d3beaaaae2ce25063b3ba981" +checksum = "e847eb9a1b4e6bd038c2ff9400aff8ba02b450baa7f691bc56359c9af0418145" dependencies = [ "cfg-if", "futures-util", @@ -4893,9 +4889,9 @@ dependencies = [ [[package]] name = "libz-sys" -version = "1.1.31" +version = "1.1.33" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff20308ecabd635a2dc1dd5834a86c462cca20efba1d5d3ddab1f8aea3455cb2" +checksum = "fee3f59f4321dab0c78d828942e7aa09d0bd8ad6e78a501977e6bf3d02938045" dependencies = [ "cc", "libc", @@ -5273,7 +5269,7 @@ checksum = "1fafa6961cabd9c63bcd77a45d7e3b7f3b552b70417831fb0f56db717e72407e" [[package]] name = "morph-chainspec" -version = "1.5.0" +version = "2.0.0" dependencies = [ "alloy-chains", "alloy-consensus", @@ -5296,7 +5292,7 @@ dependencies = [ [[package]] name = "morph-consensus" -version = "1.5.0" +version = "2.0.0" dependencies = [ "alloy-consensus", "alloy-eips", @@ -5315,7 +5311,7 @@ dependencies = [ [[package]] name = "morph-engine-api" -version = "1.5.0" +version = "2.0.0" dependencies = [ "alloy-consensus", "alloy-eips", @@ -5344,7 +5340,7 @@ dependencies = [ [[package]] name = "morph-evm" -version = "1.5.0" +version = "2.0.0" dependencies = [ "alloy-consensus", "alloy-eip7928", @@ -5372,7 +5368,7 @@ dependencies = [ [[package]] name = "morph-node" -version = "1.5.0" +version = "2.0.0" dependencies = [ "alloy-consensus", "alloy-eip7928", @@ -5443,7 +5439,7 @@ dependencies = [ [[package]] name = "morph-payload-builder" -version = "1.5.0" +version = "2.0.0" dependencies = [ "alloy-consensus", "alloy-eips", @@ -5477,7 +5473,7 @@ dependencies = [ [[package]] name = "morph-payload-types" -version = "1.5.0" +version = "2.0.0" dependencies = [ "alloy-consensus", "alloy-eips", @@ -5497,7 +5493,7 @@ dependencies = [ [[package]] name = "morph-primitives" -version = "1.5.0" +version = "2.0.0" dependencies = [ "alloy-consensus", "alloy-eips", @@ -5517,7 +5513,7 @@ dependencies = [ [[package]] name = "morph-proofs" -version = "1.5.0" +version = "2.0.0" dependencies = [ "alloy-eips", "alloy-primitives", @@ -5549,7 +5545,7 @@ dependencies = [ [[package]] name = "morph-proofs-exex" -version = "1.5.0" +version = "2.0.0" dependencies = [ "alloy-consensus", "alloy-eips", @@ -5572,7 +5568,7 @@ dependencies = [ [[package]] name = "morph-reference-index" -version = "1.5.0" +version = "2.0.0" dependencies = [ "alloy-consensus", "alloy-primitives", @@ -5600,7 +5596,7 @@ dependencies = [ [[package]] name = "morph-reth" -version = "1.5.0" +version = "2.0.0" dependencies = [ "alloy-consensus", "alloy-primitives", @@ -5629,7 +5625,7 @@ dependencies = [ [[package]] name = "morph-revm" -version = "1.5.0" +version = "2.0.0" dependencies = [ "alloy-consensus", "alloy-eips", @@ -5647,7 +5643,7 @@ dependencies = [ [[package]] name = "morph-rpc" -version = "1.5.0" +version = "2.0.0" dependencies = [ "alloy-consensus", "alloy-eips", @@ -5659,7 +5655,6 @@ dependencies = [ "async-trait", "derive_more", "evm2", - "evm2-inspectors", "eyre", "futures", "jsonrpsee", @@ -5674,7 +5669,6 @@ dependencies = [ "reth-chainspec", "reth-errors", "reth-evm", - "reth-execution-types", "reth-metrics", "reth-node-api", "reth-node-builder", @@ -5700,7 +5694,7 @@ dependencies = [ [[package]] name = "morph-statetest" -version = "1.5.0" +version = "2.0.0" dependencies = [ "alloy-consensus", "alloy-eips", @@ -5722,7 +5716,7 @@ dependencies = [ [[package]] name = "morph-txpool" -version = "1.5.0" +version = "2.0.0" dependencies = [ "alloy-consensus", "alloy-eips", @@ -6378,13 +6372,15 @@ dependencies = [ [[package]] name = "prefix-trie" -version = "0.8.4" +version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4cf6e3177f0684016a5c209b00882e15f8bdd3f3bb48f0491df10cd102d0c6e7" +checksum = "77fe9ec8fb906114b52bc2e9aa142ac11817d0fcd33a32fb2feb94d823ad9a4d" dependencies = [ + "array-const-fn-init", "either", "ipnet", "num-traits", + "smallvec", ] [[package]] @@ -10049,7 +10045,7 @@ version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "19787cda76408ec5404443dc8b31795c87cd8fec49762dc75fa727740d34acc1" dependencies = [ - "core-foundation 0.10.1", + "core-foundation", "core-foundation-sys", "jni 0.21.1", "log", @@ -10070,7 +10066,7 @@ version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "26d1e2536ce4f35f4846aa13bff16bd0ff40157cdb14cc056c7b14ba41233ba0" dependencies = [ - "core-foundation 0.10.1", + "core-foundation", "core-foundation-sys", "jni 0.22.4", "log", @@ -10288,7 +10284,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" dependencies = [ "bitflags 2.13.2", - "core-foundation 0.10.1", + "core-foundation", "core-foundation-sys", "libc", "security-framework-sys", @@ -10668,9 +10664,9 @@ checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" [[package]] name = "smallvec" -version = "1.15.1" +version = "1.16.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" dependencies = [ "arbitrary", "serde", @@ -10872,12 +10868,12 @@ dependencies = [ [[package]] name = "system-configuration" -version = "0.7.0" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a13f3d0daba03132c0aa9767f98351b3488edc2c100cda2d2ec2b04f3d8d3c8b" +checksum = "501336eb7ba9e417300a6a0fa985721065467aa83a6dcf0422a8e43e4c0328fa" dependencies = [ "bitflags 2.13.2", - "core-foundation 0.9.4", + "core-foundation", "system-configuration-sys", ] @@ -11622,9 +11618,9 @@ checksum = "6d49784317cd0d1ee7ec5c716dd598ec5b4483ea832a2dced265471cc0f690ae" [[package]] name = "url" -version = "2.5.8" +version = "2.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" dependencies = [ "form_urlencoded", "idna", diff --git a/Cargo.toml b/Cargo.toml index 2ad1bafa..6830c847 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,5 +1,5 @@ [workspace.package] -version = "1.5.0" +version = "2.0.0" edition = "2024" rust-version = "1.96" license = "MIT OR Apache-2.0" @@ -146,8 +146,8 @@ reth-ethereum-consensus = { git = "https://github.com/paradigmxyz/reth", tag = " reth-ethereum-engine-primitives = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } reth-ethereum-primitives = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0", default-features = false } reth-evm = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0", default-features = false } -reth-evm-ethereum = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } -reth-execution-types = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } +reth-evm-ethereum = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0", default-features = false } +reth-execution-types = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0", default-features = false } reth-metrics = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } reth-network = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } reth-network-peers = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } diff --git a/bin/morph-reth/Cargo.toml b/bin/morph-reth/Cargo.toml index 4947ffc0..697757fd 100644 --- a/bin/morph-reth/Cargo.toml +++ b/bin/morph-reth/Cargo.toml @@ -18,7 +18,7 @@ workspace = true # Morph crates morph-chainspec = { workspace = true, features = ["cli"] } morph-consensus.workspace = true -morph-evm.workspace = true +morph-evm = { workspace = true, features = ["std"] } morph-node.workspace = true morph-proofs.workspace = true morph-proofs-exex.workspace = true diff --git a/crates/consensus/Cargo.toml b/crates/consensus/Cargo.toml index dfb20a82..96146443 100644 --- a/crates/consensus/Cargo.toml +++ b/crates/consensus/Cargo.toml @@ -19,7 +19,7 @@ morph-primitives = { workspace = true, features = ["serde-bincode-compat", "reth # Reth reth-consensus.workspace = true reth-consensus-common.workspace = true -reth-execution-types.workspace = true +reth-execution-types = { workspace = true, features = ["std"] } reth-primitives-traits.workspace = true # Alloy diff --git a/crates/consensus/src/validation.rs b/crates/consensus/src/validation.rs index 5aaff8b3..a1889ee0 100644 --- a/crates/consensus/src/validation.rs +++ b/crates/consensus/src/validation.rs @@ -116,50 +116,32 @@ impl MorphConsensus { pub fn chain_spec(&self) -> &MorphChainSpec { &self.chain_spec } -} - -// ============================================================================ -// HeaderValidator Implementation -// ============================================================================ -impl HeaderValidator for MorphConsensus { - /// Validates a block header according to Morph L2 consensus rules. - /// - /// # Validation Steps - /// - /// 1. **Extra Data**: Must be empty (Morph L2 specific) - /// 2. **Nonce**: Must be 0 (post-merge Ethereum) - /// 3. **Ommers Hash**: Must be empty ommer root hash (post-merge) - /// 4. **Difficulty**: Must be 0 (post-merge) - /// 5. **Coinbase**: Must be zero address if FeeVault is enabled - /// 6. **Timestamp**: Must not be in the future - /// 7. **Gas Limit**: Must be <= MAX_GAS_LIMIT - /// 8. **Gas Used**: Must be <= gas limit - /// 9. **Base Fee**: Must always be set (EIP-1559 is always active) and <= 10 Gwei - fn validate_header(&self, header: &SealedHeader) -> Result<(), ConsensusError> { - // Extra data must be empty (Morph L2 specific - stricter than max length) + /// Validates structural header invariants that apply even to locally built and + /// L1-derived safe blocks (exempting wall-clock `TimestampIsInFuture`, `MAX_GAS_LIMIT`, + /// and `MORPH_MAXIMUM_BASE_FEE`). + pub fn validate_header_structural( + &self, + header: &SealedHeader, + ) -> Result<(), ConsensusError> { if !header.extra_data().is_empty() { return Err(ConsensusError::ExtraDataExceedsMax { len: header.extra_data().len(), }); } - // Nonce must be 0 (same as post-merge Ethereum) if !header.nonce().is_some_and(|nonce| nonce.is_zero()) { return Err(ConsensusError::TheMergeNonceIsNotZero); } - // Ommers hash must be empty (same as post-merge Ethereum) if header.ommers_hash() != EMPTY_OMMER_ROOT_HASH { return Err(ConsensusError::TheMergeOmmerRootIsNotEmpty); } - // Difficulty must be 0 (same as post-merge Ethereum) if !header.difficulty().is_zero() { return Err(ConsensusError::TheMergeDifficultyIsNotZero); } - // Coinbase must be zero if FeeVault is enabled (Morph L2 specific) if self.chain_spec.is_fee_vault_enabled() && header.beneficiary() != alloy_primitives::Address::ZERO { @@ -168,6 +150,236 @@ impl HeaderValidator for MorphConsensus { ))); } + if header.gas_used() > header.gas_limit() { + return Err(ConsensusError::HeaderGasUsedExceedsGasLimit { + gas_used: header.gas_used(), + gas_limit: header.gas_limit(), + }); + } + + if header.base_fee_per_gas().is_none() { + return Err(ConsensusError::BaseFeeMissing); + } + + Ok(()) + } + + /// Validates structural parent-header continuity (`parent_hash`, `number == parent + 1`, + /// and from Jade onward L1 message index monotonicity), exempting timestamp and 1/1024 + /// gas-limit bounds. + pub fn validate_header_against_parent_structural( + &self, + header: &SealedHeader, + parent: &SealedHeader, + ) -> Result<(), ConsensusError> { + validate_against_parent_hash_number(header.header(), parent)?; + + // From Jade onward, `next_l1_msg_index` must never decrease across blocks. + // Pre-Jade historical blocks without L1 messages are permitted to carry an older/zero + // `next_l1_msg_index` (matching morph-geth's `blockchain_l2.go` pre-Jade skip and + // `MorphConsensus::validate_l1_msg_index_against_parent`); pre-Jade blocks that DO + // contain L1 messages remain constrained by `first_queue_index >= parent.next` and + // `header.next >= last_queue_index + 1`. + if self + .chain_spec + .is_jade_active_at_timestamp(header.timestamp()) + && header.next_l1_msg_index < parent.next_l1_msg_index + { + return Err(ConsensusError::other( + MorphConsensusError::InvalidNextL1MessageIndex { + expected: parent.next_l1_msg_index, + actual: header.next_l1_msg_index, + }, + )); + } + + Ok(()) + } + + /// Validates cross-block L1 message queue invariants against `parent`: + /// + /// 1. Across **all** hardforks (pre-Jade and post-Jade), if the block contains leading L1 + /// messages, the first message's `queue_index` must be `>= parent.next_l1_msg_index`. + /// Violations are cross-block replays and return cacheable + /// [`MorphConsensusError::L1MessagesNotInOrder`] (since transactions are committed by the + /// block hash). Forward skips (`first_queue_index > parent.next_l1_msg_index`) are allowed. + /// 2. From Jade onward, `header.next_l1_msg_index` must equal the exact derived index + /// (`parent.next_l1_msg_index` when no L1 messages are present, or `last_queue_index + 1` + /// otherwise). Mismatches return transient [`MorphConsensusError::InvalidNextL1MessageIndex`] + /// so an unhashed header field cannot poison `invalid_headers`. + pub fn validate_l1_msg_index_against_parent( + &self, + block: &SealedBlock, + parent: &MorphHeader, + ) -> Result<(), ConsensusError> { + let mut expected = parent.next_l1_msg_index; + let mut first_l1_msg = true; + for tx in block.body().transactions() { + if !tx.is_l1_msg() { + break; + } + let queue_index = tx.queue_index().ok_or_else(|| { + ConsensusError::msg("L1 message transaction is missing queue index") + })?; + if first_l1_msg { + first_l1_msg = false; + if queue_index < parent.next_l1_msg_index { + return Err(ConsensusError::other( + MorphConsensusError::L1MessagesNotInOrder { + expected: parent.next_l1_msg_index, + actual: queue_index, + }, + )); + } + } + expected = queue_index.checked_add(1).ok_or_else(|| { + ConsensusError::other(MorphConsensusError::InvalidNextL1MessageIndex { + expected: u64::MAX, + actual: block.header().next_l1_msg_index, + }) + })?; + } + + if !self + .chain_spec + .is_jade_active_at_timestamp(block.header().timestamp()) + { + return Ok(()); + } + + let actual = block.header().next_l1_msg_index; + if actual != expected { + return Err(ConsensusError::other( + MorphConsensusError::InvalidNextL1MessageIndex { expected, actual }, + )); + } + Ok(()) + } + + /// Validates only the unhashed `header.next_l1_msg_index` field against `parent`. + /// + /// Called during payload conversion so `AlreadySeen` hits cannot bypass an unhashed + /// `next_l1_msg_index` tamper without poisoning `invalid_headers`. Malformed or replayed L1 + /// messages are committed by the block hash and left to full validation. + pub fn validate_unhashed_next_l1_msg_index( + &self, + block: &SealedBlock, + parent: &MorphHeader, + ) -> Result<(), MorphConsensusError> { + let mut expected = parent.next_l1_msg_index; + let mut first_l1_msg = true; + for tx in block.body().transactions() { + if !tx.is_l1_msg() { + break; + } + let Some(queue_index) = tx.queue_index() else { + return Ok(()); + }; + if first_l1_msg { + first_l1_msg = false; + if queue_index < parent.next_l1_msg_index { + return Ok(()); + } + } + expected = queue_index.checked_add(1).ok_or( + MorphConsensusError::InvalidNextL1MessageIndex { + expected: u64::MAX, + actual: block.header().next_l1_msg_index, + }, + )?; + } + + let has_l1_msgs = !first_l1_msg; + let actual = block.header().next_l1_msg_index; + let is_jade = self + .chain_spec + .is_jade_active_at_timestamp(block.header().timestamp()); + let invalid = if is_jade { + actual != expected + } else { + has_l1_msgs && actual < expected + }; + if invalid { + return Err(MorphConsensusError::InvalidNextL1MessageIndex { expected, actual }); + } + + Ok(()) + } + + /// Validates pre-execution body invariants except the local per-block DA byte limit + /// (`max_tx_payload_bytes_per_block`), matching morph-geth's `NewSafeL2Block` (`safe = true`) + /// exemption. + pub fn validate_block_pre_execution_without_da_limit( + &self, + block: &SealedBlock, + ) -> Result<(), ConsensusError> { + let ommers_len = block.body().ommers().map(|o| o.len()).unwrap_or_default(); + if ommers_len > 0 { + return Err(ConsensusError::msg("uncles not allowed")); + } + + if block.ommers_hash() != EMPTY_OMMER_ROOT_HASH { + return Err(ConsensusError::BodyOmmersHashDiff( + GotExpected { + got: block.ommers_hash(), + expected: EMPTY_OMMER_ROOT_HASH, + } + .into(), + )); + } + + if let Err(error) = block.ensure_transaction_root_valid() { + return Err(ConsensusError::BodyTransactionRootDiff(error.into())); + } + + if block.body().withdrawals().is_some() { + return Err(ConsensusError::other( + MorphConsensusError::WithdrawalsNonEmpty, + )); + } + + let is_emerald = self + .chain_spec + .is_emerald_active_at_timestamp(block.header().timestamp()); + let is_jade = self + .chain_spec + .is_jade_active_at_timestamp(block.header().timestamp()); + let is_celadon = self + .chain_spec + .is_celadon_active_at_timestamp(block.header().timestamp()); + validate_morph_txs(&block.body().transactions, is_emerald, is_jade, is_celadon)?; + + validate_l1_messages_in_block( + &block.body().transactions, + block.header().next_l1_msg_index, + is_jade, + )?; + + Ok(()) + } +} + +// ============================================================================ +// HeaderValidator Implementation +// ============================================================================ + +impl HeaderValidator for MorphConsensus { + /// Validates a block header according to Morph L2 consensus rules. + /// + /// # Validation Steps + /// + /// 1. **Extra Data**: Must be empty (Morph L2 specific) + /// 2. **Nonce**: Must be 0 (post-merge Ethereum) + /// 3. **Ommers Hash**: Must be empty ommer root hash (post-merge) + /// 4. **Difficulty**: Must be 0 (post-merge) + /// 5. **Coinbase**: Must be zero address if FeeVault is enabled + /// 6. **Timestamp**: Must not be in the future + /// 7. **Gas Limit**: Must be <= MAX_GAS_LIMIT + /// 8. **Gas Used**: Must be <= gas limit + /// 9. **Base Fee**: Must always be set (EIP-1559 is always active) and <= 10 Gwei + fn validate_header(&self, header: &SealedHeader) -> Result<(), ConsensusError> { + self.validate_header_structural(header)?; + // Check timestamp is not in the future let now = std::time::SystemTime::now() .duration_since(std::time::SystemTime::UNIX_EPOCH) @@ -188,15 +400,7 @@ impl HeaderValidator for MorphConsensus { }); } - // Gas used must be <= gas limit - if header.gas_used() > header.gas_limit() { - return Err(ConsensusError::HeaderGasUsedExceedsGasLimit { - gas_used: header.gas_used(), - gas_limit: header.gas_limit(), - }); - } - - // Validate base fee (always required, EIP-1559 is always active) + // Validate base fee upper bound (presence is checked in validate_header_structural) let base_fee = header .base_fee_per_gas() .ok_or(ConsensusError::BaseFeeMissing)?; @@ -216,14 +420,14 @@ impl HeaderValidator for MorphConsensus { /// 2. **Block Number**: Header's number must be parent's number + 1 /// 3. **Timestamp**: Header's timestamp must be > parent's timestamp (>= from Emerald onward) /// 4. **Gas Limit**: Change must be within 1/1024 of parent's limit - /// 5. **L1 Message Index**: `next_l1_msg_index` must not decrease relative to the parent + /// 5. **L1 Message Index**: `next_l1_msg_index` must not decrease relative to the parent (post-Jade) fn validate_header_against_parent( &self, header: &SealedHeader, parent: &SealedHeader, ) -> Result<(), ConsensusError> { - // Validate parent hash and block number - validate_against_parent_hash_number(header.header(), parent)?; + // Validate parent hash, block number, and (from Jade onward) L1 message index monotonicity + self.validate_header_against_parent_structural(header, parent)?; // Validate timestamp against parent (pre-Emerald: strict >, post-Emerald: >=) let is_emerald = self @@ -234,18 +438,6 @@ impl HeaderValidator for MorphConsensus { // Validate gas limit change validate_against_parent_gas_limit(header.header(), parent.header())?; - // Cross-block L1 message index monotonicity: next_l1_msg_index must never - // decrease across blocks. This is the header-only half of L1 message - // validation; the body-level half is in validate_block_pre_execution. - if header.next_l1_msg_index < parent.next_l1_msg_index { - return Err(ConsensusError::other( - MorphConsensusError::InvalidNextL1MessageIndex { - expected: parent.next_l1_msg_index, - actual: header.next_l1_msg_index, - }, - )); - } - Ok(()) } } @@ -282,34 +474,8 @@ impl Consensus for MorphConsensus { &self, block: &SealedBlock, ) -> Result<(), ConsensusError> { - // Check no uncles allowed (Morph L2 has no uncle blocks) - let ommers_len = block.body().ommers().map(|o| o.len()).unwrap_or_default(); - if ommers_len > 0 { - return Err(ConsensusError::msg("uncles not allowed")); - } - - // Check ommers hash must be empty root hash - if block.ommers_hash() != EMPTY_OMMER_ROOT_HASH { - return Err(ConsensusError::BodyOmmersHashDiff( - GotExpected { - got: block.ommers_hash(), - expected: EMPTY_OMMER_ROOT_HASH, - } - .into(), - )); - } - - // Check transaction root - if let Err(error) = block.ensure_transaction_root_valid() { - return Err(ConsensusError::BodyTransactionRootDiff(error.into())); - } - - // Check withdrawals are empty - if block.body().withdrawals().is_some() { - return Err(ConsensusError::other( - MorphConsensusError::WithdrawalsNonEmpty, - )); - } + // Check no uncles, ommers hash, tx root, withdrawals, MorphTx, and L1 message rules. + self.validate_block_pre_execution_without_da_limit(block)?; // Matches go-ethereum's BlockValidator.ValidateBody() → IsValidBlockSize(). validate_l2_tx_payload_size( @@ -317,30 +483,6 @@ impl Consensus for MorphConsensus { self.chain_spec.max_tx_payload_bytes_per_block(), )?; - // Validate MorphTx activation, version and field constraints. - // Matches go-ethereum's BlockValidator.ValidateBody() → ValidateMorphTxVersion(). - let is_emerald = self - .chain_spec - .is_emerald_active_at_timestamp(block.header().timestamp()); - let is_jade = self - .chain_spec - .is_jade_active_at_timestamp(block.header().timestamp()); - let is_celadon = self - .chain_spec - .is_celadon_active_at_timestamp(block.header().timestamp()); - validate_morph_txs(&block.body().transactions, is_emerald, is_jade, is_celadon)?; - - // Validate L1 messages ordering and internal consistency with header. - // This is the body-level half of L1 validation; it verifies that the L1 - // messages within this block are internally consistent with the header's - // next_l1_msg_index. The cross-block monotonicity check (ensuring - // next_l1_msg_index >= parent's value) is in validate_header_against_parent. - validate_l1_messages_in_block( - &block.body().transactions, - block.header().next_l1_msg_index, - is_jade, - )?; - Ok(()) } @@ -2491,4 +2633,127 @@ mod tests { Err(ConsensusError::BlockGasUsed { .. }) )); } + + #[test] + fn test_structural_exemptions_preserve_hard_invariants() { + let consensus = MorphConsensus::new(create_test_chainspec_with_payload_limit(64)); + + let parent = SealedHeader::seal_slow(create_valid_morph_header(1000, 30_000_000, 100)); + + // Future timestamp, doubled gas_limit (> 1/1024), and base_fee > MORPH_MAXIMUM_BASE_FEE: + // full validation rejects each, while structural (Safe) validation exempts them. + let future_ts = u64::MAX - 10; + let mut child = create_valid_morph_header(future_ts, 60_000_000, 101); + child.inner.parent_hash = parent.hash(); + child.inner.base_fee_per_gas = Some(MORPH_MAXIMUM_BASE_FEE + 1); + let child_sealed = SealedHeader::seal_slow(child.clone()); + + assert!(matches!( + consensus.validate_header(&child_sealed), + Err(ConsensusError::TimestampIsInFuture { .. }) + )); + assert!(consensus.validate_header_structural(&child_sealed).is_ok()); + + assert!(matches!( + consensus.validate_header_against_parent(&child_sealed, &parent), + Err(ConsensusError::GasLimitInvalidIncrease { .. }) + )); + assert!( + consensus + .validate_header_against_parent_structural(&child_sealed, &parent) + .is_ok() + ); + + // Timestamp behind parent: rejected by full validation, exempted for Safe (structural). + let mut past_child = child; + past_child.inner.timestamp = 999; + let past_sealed = SealedHeader::seal_slow(past_child); + assert!(matches!( + consensus.validate_header_against_parent(&past_sealed, &parent), + Err(ConsensusError::TimestampIsInPast { .. }) + )); + assert!( + consensus + .validate_header_against_parent_structural(&past_sealed, &parent) + .is_ok() + ); + + // Structural violations (e.g. non-empty extra_data or gas_used > gas_limit) still fail. + let mut bad_extra = create_valid_morph_header(1001, 30_000_000, 101); + bad_extra.inner.extra_data = Bytes::from_static(b"bad"); + assert!( + consensus + .validate_header_structural(&SealedHeader::seal_slow(bad_extra)) + .is_err() + ); + + // Oversized L2 payload: rejected by full pre-execution, accepted by without_da_limit. + let oversized_tx = create_legacy_tx_with_input(Bytes::from(vec![0xab; 256])); + let oversized_block = create_sealed_block(0, vec![oversized_tx]); + assert!( + consensus + .validate_block_pre_execution(&oversized_block) + .is_err() + ); + assert!( + consensus + .validate_block_pre_execution_without_da_limit(&oversized_block) + .is_ok() + ); + } + + #[test] + fn test_validate_header_against_parent_allows_pre_jade_decreased_l1_msg_index() { + let genesis_json = serde_json::json!({ + "config": { + "chainId": 1337, + "homesteadBlock": 0, + "eip150Block": 0, + "eip155Block": 0, + "eip158Block": 0, + "byzantiumBlock": 0, + "constantinopleBlock": 0, + "petersburgBlock": 0, + "istanbulBlock": 0, + "berlinBlock": 0, + "londonBlock": 0, + "bernoulliBlock": 0, + "curieBlock": 0, + "morph203Time": 0, + "viridianTime": 0, + "emeraldTime": 0, + "jadeForkTime": 2000, + "morph": {} + }, + "alloc": {} + }); + let genesis: Genesis = serde_json::from_value(genesis_json).unwrap(); + let consensus = MorphConsensus::new(Arc::new(MorphChainSpec::from(genesis))); + + let mut parent = create_valid_morph_header(1000, 30_000_000, 100); + parent.next_l1_msg_index = 10; + let parent_sealed = SealedHeader::seal_slow(parent); + + // Pre-Jade (timestamp 1001 < 2000): decreased next_l1_msg_index is allowed on headers. + let mut pre_jade_child = create_valid_morph_header(1001, 30_000_000, 101); + pre_jade_child.inner.parent_hash = parent_sealed.hash(); + pre_jade_child.next_l1_msg_index = 0; + let pre_jade_sealed = SealedHeader::seal_slow(pre_jade_child); + assert!( + consensus + .validate_header_against_parent(&pre_jade_sealed, &parent_sealed) + .is_ok() + ); + + // Post-Jade (timestamp 2000 >= 2000): decreased next_l1_msg_index is rejected. + let mut post_jade_child = create_valid_morph_header(2000, 30_000_000, 101); + post_jade_child.inner.parent_hash = parent_sealed.hash(); + post_jade_child.next_l1_msg_index = 0; + let post_jade_sealed = SealedHeader::seal_slow(post_jade_child); + assert!( + consensus + .validate_header_against_parent(&post_jade_sealed, &parent_sealed) + .is_err() + ); + } } diff --git a/crates/engine-api/src/builder.rs b/crates/engine-api/src/builder.rs index 979ddd09..211be35a 100644 --- a/crates/engine-api/src/builder.rs +++ b/crates/engine-api/src/builder.rs @@ -368,23 +368,6 @@ where } }; - // 2b. Validate `next_l1_message_index` before calling `new_payload`: the field is not - // covered by the block hash, so an `AlreadySeen` hit in the engine tree would - // otherwise return `Valid` without re-running `validate_payload`. - if let Err(err) = self.validate_next_l1_message_index(payload.block.as_ref()) { - tracing::warn!( - target: "morph::engine", - block_hash = %data.hash, - error = %err, - "invalid next_l1_message_index during validate_l2_block" - ); - self.metrics.validate_l2_block_failures_total.increment(1); - self.metrics - .validate_l2_block_duration_seconds - .record(validate_started.elapsed()); - return Ok(GenericResponse { success: false }); - } - let status = match self.engine_handle.new_payload(payload).await { Ok(status) => status, Err(err) => { @@ -488,7 +471,7 @@ where let block_hash = data.hash; let block_number = data.number; let block_timestamp = data.timestamp; - self.import_l2_block_via_engine(data, B256::ZERO) + self.import_l2_block_via_engine(data, B256::ZERO, false) .await .inspect_err(|_| { self.metrics.new_l2_block_failures_total.increment(1); @@ -556,7 +539,7 @@ where // FCU advances or reorgs the canonical head onto data.hash. let block_timestamp = data.timestamp; let header = self - .import_l2_block_via_engine(data, B256::ZERO) + .import_l2_block_via_engine(data, B256::ZERO, false) .await .inspect_err(|_| { self.metrics.new_l2_block_failures_total.increment(1); @@ -623,12 +606,11 @@ where let block_hash = executable_data.hash; // 3. Import the block through reth engine tree, marking the imported block safe - // in the same FCU. Do not mark it finalized: L1 derivation can still reorg this - // block, and finalized is only authoritative when supplied by BlockTagService via - // set_block_tags. Return the in-path header (do not rely on immediate DB - // visibility after FCU). + // in the same FCU. Pass `is_safe = true` to match morph-geth's `NewSafeL2Block` + // (`safe = true`), exempting `VerifyHeader` and `ValidateBody` DA byte-limit checks + // so follower clock skew or L1 batch parameter updates cannot stall L1 derivation. let header = self - .import_l2_block_via_engine(executable_data, block_hash) + .import_l2_block_via_engine(executable_data, block_hash, true) .await .inspect_err(|_| { self.metrics.new_safe_l2_block_failures_total.increment(1); @@ -943,87 +925,22 @@ impl RealMorphL2EngineApi { }) } - /// Validates the unhashed `next_l1_message_index` header field against the parent header - /// and the block's leading L1 messages before calling `engine_handle.new_payload`. - /// - /// Because `next_l1_msg_index` is not part of the block hash, reth's `AlreadySeen` - /// short-circuit would otherwise return `Valid` for a tampered `next_l1_message_index` - /// whenever the block hash is already in `tree_state` (e.g., pre-inserted by - /// `assembleL2Block`) or in the DB. Checking it here rejects the tampered request - /// without invoking `new_payload` (so `invalid_headers` is never poisoned). - fn validate_next_l1_message_index(&self, block: &SealedBlock) -> EngineApiResult<()> - where - Provider: HeaderProvider
, - { - let Some(parent) = self - .provider - .sealed_header_by_hash(block.parent_hash()) - .map_err(|e| MorphEngineApiError::Database(e.to_string()))? - else { - return Ok(()); - }; - - let mut expected = parent.next_l1_msg_index; - let mut first_l1_msg = true; - for tx in block.body().transactions() { - if !tx.is_l1_msg() { - break; - } - let Some(queue_index) = tx.queue_index() else { - // Malformed L1 message is committed by the block hash; let the engine - // validator reject and cache it. - return Ok(()); - }; - if first_l1_msg { - first_l1_msg = false; - if queue_index < parent.next_l1_msg_index { - // Cross-block L1 replay is committed by the block hash; let the engine - // validator reject and cache it with `L1MessagesNotInOrder`. - return Ok(()); - } - } - expected = match queue_index.checked_add(1) { - Some(next) => next, - None => { - return Err(MorphEngineApiError::ValidationFailed(format!( - "invalid block.NextL1MsgIndex: expected {}, got {}", - u64::MAX, - block.header().next_l1_msg_index - ))); - } - }; - } - - let actual = block.header().next_l1_msg_index; - let is_jade = self - .chain_spec - .is_jade_active_at_timestamp(block.header().timestamp()); - let invalid = if is_jade { - actual != expected - } else { - actual < expected - }; - if invalid { - return Err(MorphEngineApiError::ValidationFailed(format!( - "invalid block.NextL1MsgIndex: expected {expected}, got {actual}" - ))); - } - - Ok(()) - } - async fn import_l2_block_via_engine( &self, data: ExecutableL2Data, safe_block_hash: B256, + is_safe: bool, ) -> EngineApiResult where Provider: HeaderProvider
+ BlockNumReader + + BlockReaderIdExt
+ CanonChainTracker
, { - let (payload, header) = self.execution_payload_from_executable_data(&data)?; - self.validate_next_l1_message_index(payload.block.as_ref())?; + let (mut payload, header) = self.execution_payload_from_executable_data(&data)?; + if is_safe { + payload = payload.with_safe_validation(); + } let payload_status = self .engine_handle @@ -1036,17 +953,23 @@ impl RealMorphL2EngineApi { // and this FCU observes any newly recorded L1 finalized hash. let _fcu_guard = self.fcu_lock.lock().await; + let finalized_block_hash = match self.block_tag_tracker.l1_finalized_hash() { + Some(hash) => hash, + None => self + .provider + .finalized_block_hash() + .map_err(|e| MorphEngineApiError::Database(e.to_string()))? + .unwrap_or_default(), + }; + // FCU safe/finalized must be canonical ancestors. Unsafe imports pass safe zero; // new_safe_l2_block passes the imported block itself, never a cached old safe. - // Forward only the L1-derived finalized tag; zero is a no-op when it is absent, - // and reth still cleans changesets/canonical memory without finalized. + // Forward only the L1-derived (or persisted post-restart) finalized tag; zero is a + // no-op when it is absent, and reth still cleans changesets/canonical memory without it. let forkchoice = alloy_rpc_types_engine::ForkchoiceState { head_block_hash: data.hash, safe_block_hash, - finalized_block_hash: self - .block_tag_tracker - .l1_finalized_hash() - .unwrap_or_default(), + finalized_block_hash, }; self.provider.on_forkchoice_update_received(&forkchoice); @@ -1058,6 +981,68 @@ impl RealMorphL2EngineApi { .map_err(|e| MorphEngineApiError::ExecutionFailed(e.to_string()))?; ensure_payload_status_valid(&fcu_result.payload_status, "forkchoiceUpdated")?; + // [MR-14] Reth's `update_safe_block` treats `safe_block_hash == B256::ZERO` as a no-op, + // leaving `CanonicalInMemoryState.safe` untouched. If an unsafe import (`new_l2_block_v2`) + // reorgs past an earlier `safe` block so that block is no longer on the canonical chain, + // rewind `safe` through FCU to the current canonical `finalized` block (or genesis when no + // block has been finalized yet) so `"safe"` RPC queries never serve an orphaned fork. + if safe_block_hash.is_zero() + && let Some(existing_safe) = self + .provider + .safe_block_num_hash() + .map_err(|e| MorphEngineApiError::Database(e.to_string()))? + { + let safe_still_canonical = existing_safe.number <= data.number + && self + .provider + .block_hash(existing_safe.number) + .map_err(|e| MorphEngineApiError::Database(e.to_string()))? + == Some(existing_safe.hash); + if !safe_still_canonical { + let fallback_safe_hash = + match self + .provider + .finalized_block_num_hash() + .map_err(|e| MorphEngineApiError::Database(e.to_string()))? + { + Some(finalized) + if finalized.number <= data.number + && self.provider.block_hash(finalized.number).map_err(|e| { + MorphEngineApiError::Database(e.to_string()) + })? == Some(finalized.hash) => + { + finalized.hash + } + _ => self + .provider + .block_hash(0) + .map_err(|e| MorphEngineApiError::Database(e.to_string()))? + .unwrap_or_default(), + }; + if !fallback_safe_hash.is_zero() { + let repair_fcu = alloy_rpc_types_engine::ForkchoiceState { + head_block_hash: data.hash, + safe_block_hash: fallback_safe_hash, + finalized_block_hash, + }; + self.provider.on_forkchoice_update_received(&repair_fcu); + let repair_res = self + .engine_handle + .fork_choice_updated(repair_fcu, None) + .await + .map_err(|e| MorphEngineApiError::ExecutionFailed(e.to_string()))?; + ensure_payload_status_valid(&repair_res.payload_status, "forkchoiceUpdated")?; + tracing::info!( + target: "morph::engine", + orphaned_safe_number = existing_safe.number, + orphaned_safe_hash = %existing_safe.hash, + fallback_safe_hash = %fallback_safe_hash, + "rewound orphaned safe block tag after canonical reorg" + ); + } + } + } + Ok(header) } diff --git a/crates/evm/Cargo.toml b/crates/evm/Cargo.toml index d48bf80e..a484b6a9 100644 --- a/crates/evm/Cargo.toml +++ b/crates/evm/Cargo.toml @@ -45,11 +45,16 @@ rayon.workspace = true default = [] serde-bincode-compat = [ "morph-primitives/serde-bincode-compat", + "reth-execution-types/serde-bincode-compat", ] -# Engine-API payload execution (the `engine` module) requires `reth-evm/std` -# (`ConfigureEngineEvm`) and `morph-payload-types`; both transitively pull in -# `reth-primitives-traits/quanta`, which does not compile for SP1's zkvm -# target. Kept off by default so zkvm guest builds stay quanta-free; node -# compositions enable it (see `morph-node`). -engine = ["dep:morph-payload-types", "reth-evm/std"] -rpc = ["dep:reth-rpc-eth-api", "morph-primitives/reth-codec"] +# Host-only `ConfigureEvm` methods (`BlockAssembler`, `block_executor_factory`) and +# `reth-ethereum-primitives/std` pull in `reth-primitives-traits/quanta`, which does +# not compile for SP1's zkvm target. Kept off by default so zkvm guest builds stay +# quanta-free; host crates enable `std`, `engine`, or `rpc`. +std = [ + "reth-evm/std", + "reth-evm-ethereum/std", + "reth-execution-types/std", +] +engine = ["std", "dep:morph-payload-types"] +rpc = ["std", "dep:reth-rpc-eth-api", "morph-primitives/reth-codec"] diff --git a/crates/evm/src/block/mod.rs b/crates/evm/src/block/mod.rs index 1c2a384c..66bfaa3b 100644 --- a/crates/evm/src/block/mod.rs +++ b/crates/evm/src/block/mod.rs @@ -5,6 +5,7 @@ //! - [`MorphReceiptBuilder`]: Receipt construction for transactions mod receipt; +mod simulate; pub(crate) use receipt::{ DefaultMorphReceiptBuilder, MorphReceiptBuilder, MorphReceiptBuilderCtx, MorphReceiptTxFields, @@ -18,6 +19,7 @@ use evm2::{AnyError, TxResultWithState, evm::Bal, registry::HandlerError}; use morph_primitives::{MorphReceipt, MorphTxEnvelope, MorphTxType}; use morph_revm::{ L1_GAS_PRICE_ORACLE_ADDRESS, MorphEvmTypes, MorphInvalidTransaction, TokenFeeInfo, + encode_simulated_tx_for_l1_fee, }; use reth_evm::{ BlockExecutionError, BlockExecutionOutput, BlockExecutor, BlockTransactionResult, @@ -377,9 +379,14 @@ impl<'a> BlockExecutor for MorphBlockExecutor<'a> { &mut self, transaction: impl ExecutorTx, ) -> Result { - let (transaction, tx) = transaction.into_parts(); + let (mut transaction, tx) = transaction.into_parts(); self.validate_transaction_gas_limit(tx.tx().gas_limit())?; + if simulate::needs_simulated_l1_encoding(self.evm.version(), transaction.rlp_bytes.as_ref()) + { + transaction.inner_mut().rlp_bytes = Some(encode_simulated_tx_for_l1_fee(tx.tx())); + } + let input = TxReceiptInput { tx_type: tx.tx().tx_type(), is_l1_msg: tx.tx().is_l1_msg(), @@ -536,11 +543,11 @@ mod tests { } } - fn legacy_tx(nonce: u64, gas_limit: u64) -> MorphTxEnvelope { + fn legacy_tx(tx_seq: u64, gas_limit: u64) -> MorphTxEnvelope { MorphTxEnvelope::Legacy(Signed::new_unhashed( TxLegacy { chain_id: Some(1337), - nonce, + nonce: tx_seq, gas_price: 1, gas_limit, to: TxKind::Call(TARGET), diff --git a/crates/evm/src/block/simulate.rs b/crates/evm/src/block/simulate.rs new file mode 100644 index 00000000..56a0899b --- /dev/null +++ b/crates/evm/src/block/simulate.rs @@ -0,0 +1,90 @@ +//! L1 data fee encoding for `eth_simulateV1` calls executed by [`super::MorphBlockExecutor`]. + +use alloy_primitives::Bytes; +use evm2::{EvmFeatures, Version}; + +/// Whether a simulated transaction must be priced with a placeholder-signature encoding. +/// +/// Upstream `eth_simulateV1` (`simulate::execute_transactions`) wraps resolved calls in an empty +/// `WithEncoded` envelope with a zero signature on the recovered transaction. A +/// `validation: true` simulation (EIP-3607 disabled, nonce checks and fee charging on) is +/// priced like a real signed transaction, so the executor encodes a copy with a full-size +/// placeholder signature for Morph's L1 data fee without touching the recovered transaction. +/// A `validation: false` simulation keeps the empty envelope, which the handler prices at zero +/// L1 fee as upstream does for L2s. Consensus execution never disables EIP-3607, so a real +/// transaction is never given a fabricated encoding. +pub(super) fn needs_simulated_l1_encoding(version: &Version, rlp_bytes: Option<&Bytes>) -> bool { + !version.feature(EvmFeatures::EIP3607) + && version.feature(EvmFeatures::NONCE_CHECK) + && version.feature(EvmFeatures::FEE_CHARGE) + && rlp_bytes.is_none_or(|bytes| bytes.is_empty()) +} + +#[cfg(test)] +mod tests { + use super::needs_simulated_l1_encoding; + use alloy_primitives::Bytes; + use evm2::{EvmFeatures, Version}; + use morph_chainspec::MorphHardfork; + use morph_revm::morph_version; + + fn version_with( + eip3607_disabled: bool, + nonce_check_disabled: bool, + fee_charge_disabled: bool, + ) -> Version { + let mut version = morph_version(MorphHardfork::Celadon, 2818, 30_000_000); + if eip3607_disabled { + version.features.remove(EvmFeatures::EIP3607); + } + if nonce_check_disabled { + version.features.remove(EvmFeatures::NONCE_CHECK); + } + if fee_charge_disabled { + version.features.remove(EvmFeatures::FEE_CHARGE); + } + version + } + + #[test] + fn consensus_execution_never_gets_a_placeholder_encoding() { + let consensus = version_with(false, false, false); + assert!(!needs_simulated_l1_encoding(&consensus, None)); + assert!(!needs_simulated_l1_encoding( + &consensus, + Some(&Bytes::new()) + )); + } + + #[test] + fn only_validating_simulations_get_a_placeholder_encoding() { + // `eth_simulateV1` with `validation: true`. + assert!(needs_simulated_l1_encoding( + &version_with(true, false, false), + Some(&Bytes::new()) + )); + assert!(needs_simulated_l1_encoding( + &version_with(true, false, false), + None + )); + // `validation: false` keeps the empty envelope, priced at zero L1 fee by the handler. + assert!(!needs_simulated_l1_encoding( + &version_with(true, true, false), + Some(&Bytes::new()) + )); + // Fee charging disabled (`eth_call`-style) never computes an L1 fee. + assert!(!needs_simulated_l1_encoding( + &version_with(true, false, true), + Some(&Bytes::new()) + )); + } + + #[test] + fn real_encoding_is_never_replaced() { + let encoded = Bytes::from_static(&[0x02, 0xc0]); + assert!(!needs_simulated_l1_encoding( + &version_with(true, false, false), + Some(&encoded) + )); + } +} diff --git a/crates/evm/src/config.rs b/crates/evm/src/config.rs index a19b096d..ba989534 100644 --- a/crates/evm/src/config.rs +++ b/crates/evm/src/config.rs @@ -1,4 +1,6 @@ -use crate::{MorphBlockAssembler, MorphEvmConfig, MorphEvmError, MorphNextBlockEnvAttributes}; +#[cfg(feature = "std")] +use crate::MorphBlockAssembler; +use crate::{MorphEvmConfig, MorphEvmError, MorphNextBlockEnvAttributes}; use alloy_consensus::BlockHeader; use alloy_primitives::{B256, U256}; use morph_chainspec::hardfork::MorphHardforks; @@ -16,12 +18,15 @@ impl ConfigureEvm for MorphEvmConfig { type Error = MorphEvmError; type NextBlockEnvCtx = MorphNextBlockEnvAttributes; type BlockExecutorFactory = Self; + #[cfg(feature = "std")] type BlockAssembler = MorphBlockAssembler; + #[cfg(feature = "std")] fn block_executor_factory(&self) -> &Self::BlockExecutorFactory { self } + #[cfg(feature = "std")] fn block_assembler(&self) -> &Self::BlockAssembler { &self.block_assembler } diff --git a/crates/node/src/add_ons.rs b/crates/node/src/add_ons.rs index 5b10637f..292d4297 100644 --- a/crates/node/src/add_ons.rs +++ b/crates/node/src/add_ons.rs @@ -27,7 +27,8 @@ use reth_node_builder::{ }, }; use reth_provider::{ - BlockWriter, CanonChainTracker, ChainSpecProvider, DBProvider, DatabaseProviderFactory, + BlockIdReader, BlockWriter, CanonChainTracker, ChainSpecProvider, DBProvider, + DatabaseProviderFactory, }; use reth_prune_types::PruneMode; use reth_rpc_builder::{Identity, RethRpcModule}; @@ -148,6 +149,7 @@ where let beacon_engine_handle = ctx.beacon_engine_handle.clone(); let task_executor = ctx.node.task_executor().clone(); let block_tag_tracker = std::sync::Arc::new(morph_engine_api::BlockTagTracker::default()); + block_tag_tracker.record_finalized_hash(provider.finalized_block_hash()?); // The reference index backfills directly from canonical block bodies. Read the // effective modes from the provider so both CLI arguments and reth.toml are covered. diff --git a/crates/node/src/components/pool.rs b/crates/node/src/components/pool.rs index 4fdf85c0..7d3e9f10 100644 --- a/crates/node/src/components/pool.rs +++ b/crates/node/src/components/pool.rs @@ -43,7 +43,7 @@ where // Initialize both the pool's and validator's block gas limit from the current // canonical tip (falling back to genesis on a fresh DB) so transactions with gas // above Ethereum's default 30M are not rejected during the startup window before - // the first `set_block_info` update. + // the first `set_block_info` update, while preserving an explicit `--txpool.gas-limit`. let tip_gas_limit = ctx .provider() .best_block_number() @@ -51,7 +51,9 @@ where .and_then(|num| ctx.provider().header_by_number(num).ok().flatten()) .map(|header| header.gas_limit()) .unwrap_or_else(|| ctx.chain_spec().inner.genesis().gas_limit); - pool_config.gas_limit = tip_gas_limit; + if pool_config.gas_limit == reth_transaction_pool::PoolConfig::default().gas_limit { + pool_config.gas_limit = tip_gas_limit; + } // Use in-memory blob store (Morph doesn't support EIP-4844 blobs) let blob_store = InMemoryBlobStore::default(); diff --git a/crates/node/src/test_utils.rs b/crates/node/src/test_utils.rs index 6c83086c..77d3a130 100644 --- a/crates/node/src/test_utils.rs +++ b/crates/node/src/test_utils.rs @@ -277,9 +277,14 @@ impl TestNodeBuilder { .get_mut("alloc") .and_then(serde_json::Value::as_object_mut) .expect("test genesis alloc must be an object"); - let address = address.to_string().to_ascii_lowercase(); + let address_lower = address.to_string().to_ascii_lowercase(); + let key = alloc + .keys() + .find(|existing| existing.eq_ignore_ascii_case(&address_lower)) + .cloned() + .unwrap_or(address_lower); let entry = alloc - .entry(address) + .entry(key) .or_insert_with(|| serde_json::json!({ "balance": "0x0" })); let entry = entry .as_object_mut() @@ -288,6 +293,48 @@ impl TestNodeBuilder { self } + /// Override a storage slot for an account in the test genesis. + pub fn with_account_storage( + mut self, + address: Address, + slot: impl Into, + value: impl Into, + ) -> Self { + let slot: B256 = slot.into(); + let value: B256 = value.into(); + let alloc = self + .genesis_json + .get_mut("alloc") + .and_then(serde_json::Value::as_object_mut) + .expect("test genesis alloc must be an object"); + let address_lower = address.to_string().to_ascii_lowercase(); + let key = alloc + .keys() + .find(|existing| existing.eq_ignore_ascii_case(&address_lower)) + .cloned() + .unwrap_or(address_lower); + let entry = alloc + .entry(key) + .or_insert_with(|| serde_json::json!({ "balance": "0x0" })); + let entry = entry + .as_object_mut() + .expect("test genesis account entry must be an object"); + let storage = entry + .entry("storage".to_string()) + .or_insert_with(|| serde_json::json!({})) + .as_object_mut() + .expect("test genesis account storage must be an object"); + storage.insert(slot.to_string(), serde_json::json!(value.to_string())); + self + } + + /// Override `config.morph.maxTxPayloadBytesPerBlock` in the test genesis. + pub fn with_genesis_max_tx_payload_bytes(mut self, max_bytes: u64) -> Self { + self.genesis_json["config"]["morph"]["maxTxPayloadBytesPerBlock"] = + serde_json::json!(max_bytes); + self + } + /// Set the number of nodes to start. /// /// When `num_nodes > 1`, all nodes are interconnected via a simulated P2P network. @@ -322,38 +369,6 @@ impl TestNodeBuilder { self } - /// Override an account's storage slot in the test genesis. - pub fn with_account_storage(mut self, address: Address, slot: U256, value: U256) -> Self { - let alloc = self - .genesis_json - .get_mut("alloc") - .and_then(serde_json::Value::as_object_mut) - .expect("test genesis alloc must be an object"); - let address_lower = address.to_string().to_ascii_lowercase(); - let key = alloc - .keys() - .find(|existing| existing.eq_ignore_ascii_case(&address_lower)) - .cloned() - .unwrap_or(address_lower); - let entry = alloc - .entry(key) - .or_insert_with(|| serde_json::json!({ "balance": "0x0" })); - let entry = entry - .as_object_mut() - .expect("test genesis account entry must be an object"); - let storage = entry - .entry("storage") - .or_insert_with(|| serde_json::json!({})); - let storage = storage - .as_object_mut() - .expect("test genesis account storage must be an object"); - storage.insert( - format!("{slot:#066x}"), - serde_json::json!(format!("{value:#066x}")), - ); - self - } - /// Override the configured HTTP RPC modules (`--http.api`). pub fn with_http_api(mut self, http_api: RpcModuleSelection) -> Self { self.http_api = Some(http_api); diff --git a/crates/node/src/validator.rs b/crates/node/src/validator.rs index 2665cfcb..eab534df 100644 --- a/crates/node/src/validator.rs +++ b/crates/node/src/validator.rs @@ -7,13 +7,15 @@ use morph_chainspec::{ L2_MESSAGE_QUEUE_ADDRESS, L2_MESSAGE_QUEUE_WITHDRAW_TRIE_ROOT_SLOT, MorphChainSpec, MorphHardforks, }; -use morph_consensus::MorphConsensusError; +use morph_consensus::{MorphConsensus, MorphConsensusError}; use morph_payload_types::{MorphExecutionData, MorphPayloadTypes}; -use morph_primitives::{MorphHeader, MorphPrimitives, MorphTxEnvelope}; +use morph_primitives::{ + Block, BlockBody, MorphHeader, MorphPrimitives, MorphReceipt, MorphTxEnvelope, +}; use parking_lot::Mutex; use reth_chain_state::ExecutedBlock; use reth_chainspec::EthChainSpec; -use reth_consensus::{Consensus, FullConsensus, HeaderValidator}; +use reth_consensus::{Consensus, FullConsensus, HeaderValidator, ReceiptRootBloom}; use reth_engine_tree::tree::payload_validator::TreeCtx; use reth_engine_tree::tree::{ BasicEngineValidator, CacheWaitDurations, EngineApiTreeState, EngineValidator, @@ -36,10 +38,10 @@ use reth_node_builder::{ rpc::{EngineValidatorBuilder, PayloadValidatorBuilder}, }; use reth_payload_primitives::BuiltPayloadExecutedBlock; -use reth_primitives_traits::{RecoveredBlock, SealedBlock, SealedBlockWith}; +use reth_primitives_traits::{RecoveredBlock, SealedBlock, SealedBlockWith, SealedHeader}; use reth_provider::{ - BlockExecutionOutput, BlockNumReader, BlockReader, ChainSpecProvider, ChangeSetReader, - DatabaseProviderFactory, DatabaseProviderROFactory, PruneCheckpointReader, + BlockExecutionOutput, BlockExecutionResult, BlockNumReader, BlockReader, ChainSpecProvider, + ChangeSetReader, DatabaseProviderFactory, DatabaseProviderROFactory, PruneCheckpointReader, StageCheckpointReader, StateProviderFactory, StateReader, StateRootProvider, StorageChangeSetReader, StorageSettingsCache, }; @@ -130,12 +132,14 @@ where let post_execution_validator = validator.clone(); let provider = ctx.node.provider().clone(); - let consensus: Arc> = - Arc::new(ctx.node.consensus().clone()); + let engine_consensus = Arc::new(MorphEngineConsensus::new(MorphConsensus::new( + chain_spec.clone(), + ))); + let consensus: Arc> = engine_consensus.clone(); let state_root_strategy: Arc< dyn StateRootStrategy, > = Arc::new(MorphStateRootStrategy::new( - chain_spec.clone(), + chain_spec, provider.clone(), overlay_manager.clone(), )); @@ -143,7 +147,7 @@ where let txpool_prewarming = tree_config.txpool_prewarming(); let mut validator = BasicEngineValidator::new( provider.clone(), - consensus.clone(), + consensus, ctx.node.evm_config().clone(), validator, tree_config, @@ -161,8 +165,7 @@ where Ok(MorphTreeEngineValidator::new( validator, provider, - chain_spec, - consensus, + engine_consensus, post_execution_validator, )) } @@ -229,6 +232,156 @@ fn strict_morph_tree_config(tree_config: reth_node_api::TreeConfig) -> reth_node tree_config.with_skip_state_root(false) } +/// Bounded FIFO map used for validator-internal in-memory caches. +#[derive(Debug)] +struct BoundedFifoMap { + entries: HashMap, + order: VecDeque, + max_entries: usize, +} + +impl BoundedFifoMap +where + K: Eq + std::hash::Hash + Copy, +{ + fn new(max_entries: usize) -> Self { + Self { + entries: HashMap::new(), + order: VecDeque::new(), + max_entries, + } + } + + fn insert(&mut self, key: K, value: V) { + let is_new = self.entries.insert(key, value).is_none(); + if is_new { + self.order.push_back(key); + while self.entries.len() > self.max_entries { + let Some(evicted) = self.order.pop_front() else { + break; + }; + self.entries.remove(&evicted); + } + } + } + + fn get(&self, key: &K) -> Option<&V> { + self.entries.get(key) + } + + fn contains_key(&self, key: &K) -> bool { + self.entries.contains_key(key) + } + + fn remove(&mut self, key: &K) -> Option { + let removed = self.entries.remove(key); + if removed.is_some() { + self.order.retain(|existing| existing != key); + } + removed + } +} + +/// Engine-tree consensus adapter that applies L1-derived safe-block (`engine_newSafeL2Block`) +/// exemptions per block hash when `BasicEngineValidator` validates safe payloads, while +/// enforcing full [`MorphConsensus`] validation for all untrusted blocks. +#[derive(Debug)] +struct MorphEngineConsensus { + inner: MorphConsensus, + safe_blocks: Mutex>, +} + +impl MorphEngineConsensus { + const MAX_SAFE_BLOCKS: usize = 1024; + + fn new(inner: MorphConsensus) -> Self { + Self { + inner, + safe_blocks: Mutex::new(BoundedFifoMap::new(Self::MAX_SAFE_BLOCKS)), + } + } + + const fn inner(&self) -> &MorphConsensus { + &self.inner + } + + /// Records `block_hash` as an L1-derived safe block. Never downgrades an existing mark + /// because buffered safe payloads later pass through `validate_block` without `is_safe`. + fn mark_safe(&self, block_hash: B256) { + self.safe_blocks.lock().insert(block_hash, ()); + } + + fn is_safe(&self, block_hash: B256) -> bool { + self.safe_blocks.lock().contains_key(&block_hash) + } +} + +impl HeaderValidator for MorphEngineConsensus { + fn validate_header(&self, header: &SealedHeader) -> Result<(), ConsensusError> { + if self.is_safe(header.hash()) { + self.inner.validate_header_structural(header) + } else { + self.inner.validate_header(header) + } + } + + fn validate_header_against_parent( + &self, + header: &SealedHeader, + parent: &SealedHeader, + ) -> Result<(), ConsensusError> { + if self.is_safe(header.hash()) { + self.inner + .validate_header_against_parent_structural(header, parent) + } else { + self.inner.validate_header_against_parent(header, parent) + } + } +} + +impl Consensus for MorphEngineConsensus { + fn validate_body_against_header( + &self, + body: &BlockBody, + header: &SealedHeader, + ) -> Result<(), ConsensusError> { + self.inner.validate_body_against_header(body, header) + } + + fn validate_block_pre_execution( + &self, + block: &SealedBlock, + ) -> Result<(), ConsensusError> { + if self.is_safe(block.hash()) { + self.inner + .validate_block_pre_execution_without_da_limit(block) + } else { + self.inner.validate_block_pre_execution(block) + } + } + + fn is_transient_error(&self, error: &ConsensusError) -> bool { + self.inner.is_transient_error(error) + } +} + +impl FullConsensus for MorphEngineConsensus { + fn validate_block_post_execution( + &self, + block: &RecoveredBlock, + result: &BlockExecutionResult, + receipt_root_bloom: Option, + block_access_list_hash: Option, + ) -> Result<(), ConsensusError> { + self.inner.validate_block_post_execution( + block, + result, + receipt_root_bloom, + block_access_list_hash, + ) + } +} + /// Upstream engine validator plus Morph-specific validation hooks. /// /// State execution, caching and trie maintenance remain entirely upstream. This @@ -245,30 +398,37 @@ where { inner: BasicEngineValidator, provider: P, - chain_spec: Arc, - consensus: Arc>, + engine_consensus: Arc, post_execution_validator: MorphEngineValidator, + /// Bounded cache of validated in-memory `tree_state` headers so `convert_payload_to_block` + /// and `on_inserted_executed_block` can resolve unpersisted side-branch parents. + tree_headers: Mutex>>, } impl MorphTreeEngineValidator where Evm: ConfigureEvm, { - const fn new( + const MAX_TREE_HEADERS: usize = 8192; + + fn new( inner: BasicEngineValidator, provider: P, - chain_spec: Arc, - consensus: Arc>, + engine_consensus: Arc, post_execution_validator: MorphEngineValidator, ) -> Self { Self { inner, provider, - chain_spec, - consensus, + engine_consensus, post_execution_validator, + tree_headers: Mutex::new(BoundedFifoMap::new(Self::MAX_TREE_HEADERS)), } } + + fn record_tree_header(&self, header: SealedHeader) { + self.tree_headers.lock().insert(header.hash(), header); + } } impl MorphTreeEngineValidator @@ -276,68 +436,14 @@ where Evm: ConfigureEvm, P: BlockReader
, { - /// Enforces parent-aware L1 message queue invariants: - /// - /// 1. Across **all** hardforks (both pre-Jade and post-Jade), if the block contains - /// leading L1 messages, the first message's `queue_index` must be `>= parent.next_l1_msg_index`. - /// Violations are cross-block L1 message replays and return cacheable - /// [`MorphConsensusError::L1MessagesNotInOrder`] (since transactions are committed by the - /// block hash). Forward skips (`first_queue_index > parent.next_l1_msg_index`) remain - /// permitted. - /// 2. From Jade onward, `header.next_l1_msg_index` must match the exact derived index - /// (`parent.next_l1_msg_index` when no L1 messages are present, or `last_queue_index + 1` - /// otherwise). Mismatches return transient [`MorphConsensusError::InvalidNextL1MessageIndex`] - /// so an unhashed header field cannot poison `invalid_headers`. - fn validate_l1_msg_index_against_parent( + fn lookup_sealed_header( &self, - block: &SealedBlock, - parent: &MorphHeader, - ) -> Result<(), ConsensusError> { - let mut expected = parent.next_l1_msg_index; - let mut first_l1_msg = true; - for tx in block.body().transactions() { - if !tx.is_l1_msg() { - break; - } - let queue_index = tx.queue_index().ok_or_else(|| { - ConsensusError::msg("L1 message transaction is missing queue index") - })?; - if first_l1_msg { - first_l1_msg = false; - if queue_index < parent.next_l1_msg_index { - return Err(ConsensusError::other( - MorphConsensusError::L1MessagesNotInOrder { - expected: parent.next_l1_msg_index, - actual: queue_index, - }, - )); - } - } - expected = queue_index.checked_add(1).ok_or_else(|| { - ConsensusError::other(MorphConsensusError::InvalidNextL1MessageIndex { - expected: u64::MAX, - actual: block.header().next_l1_msg_index, - }) - })?; - } - - if !self - .chain_spec - .is_jade_active_at_timestamp(block.header().timestamp()) - { - return Ok(()); - } - - // Typed so that `MorphConsensus::is_transient_error` keeps this rejection out of - // reth's invalid-header cache: the field is not covered by the block hash, so - // the cache entry would also match the honest block. - let actual = block.header().next_l1_msg_index; - if actual != expected { - return Err(ConsensusError::other( - MorphConsensusError::InvalidNextL1MessageIndex { expected, actual }, - )); + hash: B256, + ) -> ProviderResult>> { + if let Some(header) = self.tree_headers.lock().get(&hash).cloned() { + return Ok(Some(header)); } - Ok(()) + self.provider.sealed_header_by_hash(hash) } fn validate_next_l1_msg_index( @@ -348,7 +454,7 @@ where let parent_hash = block.parent_hash(); let parent = match ctx.state().tree_state().sealed_header_by_hash(&parent_hash) { Some(parent) => Some(parent), - None => self.provider.sealed_header_by_hash(parent_hash)?, + None => self.lookup_sealed_header(parent_hash)?, }; let Some(parent) = parent else { // The upstream validator reports the missing parent with the @@ -356,7 +462,9 @@ where return Ok(()); }; - self.validate_l1_msg_index_against_parent(block, parent.header()) + self.engine_consensus + .inner() + .validate_l1_msg_index_against_parent(block, parent.header()) .map_err(Into::into) } @@ -370,56 +478,37 @@ where .map_err(|kind| InsertBlockError::new(block.clone(), kind).into()) } - /// Runs lightweight structural consensus validation before admitting a locally built - /// block via `InsertExecutedBlock`, ensuring pre-inserted blocks obey the same - /// header, parent, L1 queue, MorphTx, and DA payload rules as imported blocks. + /// Runs structural consensus validation before admitting a locally built block via + /// `InsertExecutedBlock`, exempting wall-clock / gas-limit-step / base-fee-cap / local DA + /// bounds so `newSafeL2Block` and local payload pre-insertion keep working cleanly. fn validate_pre_inserted_block( &self, block: &RecoveredBlock, ) -> ProviderResult<()> { + let consensus = self.engine_consensus.inner(); let sealed_header = block.sealed_header(); - self.consensus - .validate_header(sealed_header) + consensus + .validate_header_structural(sealed_header) .map_err(ProviderError::other)?; - if let Some(parent) = self.provider.sealed_header_by_hash(block.parent_hash())? { - self.consensus - .validate_header_against_parent(sealed_header, &parent) + if let Some(parent) = self.lookup_sealed_header(block.parent_hash())? { + consensus + .validate_header_against_parent_structural(sealed_header, &parent) .map_err(ProviderError::other)?; - self.validate_l1_msg_index_against_parent(block.sealed_block(), parent.header()) + consensus + .validate_l1_msg_index_against_parent(block.sealed_block(), parent.header()) .map_err(ProviderError::other)?; } - self.consensus - .validate_block_pre_execution(block.sealed_block()) + consensus + .validate_block_pre_execution_without_da_limit(block.sealed_block()) .map_err(ProviderError::other)?; Ok(()) } - fn validate_withdraw_trie_root( + fn verify_withdraw_trie_root( &self, + expectation: WithdrawTrieRootExpectation, output: reth_engine_tree::tree::ValidationOutput, ) -> reth_engine_tree::tree::ValidationOutcome { - let block = output.executed_block.recovered_block(); - if let Err(err) = self - .post_execution_validator - .validate_withdraw_trie_root_update(block.hash(), || { - output.executed_block.hashed_state() - }) - { - return Err(InsertBlockError::consensus_error( - err, - output.executed_block.sealed_block().clone(), - ) - .into()); - } - - Ok(output) - } - - fn validate_withdraw_trie_root_direct( - expected_withdraw_trie_root: Option, - output: reth_engine_tree::tree::ValidationOutput, - ) -> reth_engine_tree::tree::ValidationOutcome { - let expectation = MorphEngineValidator::expectation_from_root(expected_withdraw_trie_root); if let Err(err) = MorphEngineValidator::validate_withdraw_trie_root_expectation(expectation, || { output.executed_block.hashed_state() @@ -432,6 +521,13 @@ where .into()); } + self.record_tree_header( + output + .executed_block + .recovered_block() + .sealed_header() + .clone(), + ); Ok(output) } } @@ -458,24 +554,27 @@ where mut payload: MorphExecutionData, ) -> Result, NewPayloadError> { let block_hash = payload.block.hash(); - // Avoid leaking expectations into the cache when the block is already known - // or no non-zero cross-check root was supplied. - let is_zero_root = payload + // Validate the unhashed `next_l1_msg_index` here so `AlreadySeen` hits (both + // `tree_state` and DB) cannot bypass it, without poisoning `invalid_headers`. + if let Some(parent) = self + .lookup_sealed_header(payload.block.parent_hash()) + .map_err(|e| NewPayloadError::Other(Box::new(e)))? + { + self.engine_consensus + .inner() + .validate_unhashed_next_l1_msg_index(payload.block.as_ref(), parent.header()) + .map_err(|e| NewPayloadError::Other(Box::new(e)))?; + } + if payload.is_safe { + self.engine_consensus.mark_safe(block_hash); + } + if payload .expected_withdraw_trie_root - .is_some_and(|root| root == B256::ZERO); - if is_zero_root { + .is_some_and(|root| root.is_zero()) + { self.post_execution_validator .take_withdraw_trie_root_expectation(block_hash); payload.expected_withdraw_trie_root = None; - } else if payload.expected_withdraw_trie_root.is_some() - && self - .provider - .sealed_header_by_hash(block_hash) - .ok() - .flatten() - .is_some() - { - payload.expected_withdraw_trie_root = None; } self.inner.convert_payload_to_block(payload) } @@ -494,9 +593,13 @@ where .take_withdraw_trie_root_expectation(block_hash); self.validate_next_l1_msg_index_for_block(payload.block.as_ref(), &ctx)?; + if payload.is_safe { + self.engine_consensus.mark_safe(block_hash); + } let output = self.inner.validate_payload(payload, ctx)?; - Self::validate_withdraw_trie_root_direct(expected_withdraw_trie_root, output) + let expectation = MorphEngineValidator::expectation_from_root(expected_withdraw_trie_root); + self.verify_withdraw_trie_root(expectation, output) } fn validate_block( @@ -513,7 +616,11 @@ where let output = self .post_execution_validator .clear_withdraw_trie_root_expectation_on_error(block_hash, validation)?; - self.validate_withdraw_trie_root(output) + let expectation = self + .post_execution_validator + .take_withdraw_trie_root_expectation(block_hash) + .unwrap_or(WithdrawTrieRootExpectation::SkipValidation); + self.verify_withdraw_trie_root(expectation, output) } fn on_inserted_executed_block( @@ -521,10 +628,15 @@ where block: BuiltPayloadExecutedBlock, ) -> ProviderResult> { self.validate_pre_inserted_block(block.recovered_block.as_ref())?; - self.inner.on_inserted_executed_block(block) + let executed = self.inner.on_inserted_executed_block(block)?; + self.record_tree_header(executed.recovered_block().sealed_header().clone()); + Ok(executed) } fn on_canonical_head_changed(&self, hash: B256, state: &EngineApiTreeState) { + if let Some(header) = state.tree_state().sealed_header_by_hash(&hash) { + self.record_tree_header(header); + } self.inner.on_canonical_head_changed(hash, state); } @@ -663,20 +775,20 @@ where } } -#[derive(Debug, Default)] -struct WithdrawTrieRootCache { - entries: HashMap, - order: VecDeque, -} - /// Morph engine validator for payload validation. /// /// This validator is used by the engine API to validate incoming payloads. /// For Morph, most validation is deferred to the consensus layer. -#[derive(Debug, Default, Clone)] +#[derive(Debug, Clone)] #[non_exhaustive] pub struct MorphEngineValidator { - expected_withdraw_trie_roots: Arc>, + expected_withdraw_trie_roots: Arc>>, +} + +impl Default for MorphEngineValidator { + fn default() -> Self { + Self::new() + } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -690,7 +802,11 @@ impl MorphEngineValidator { /// Creates a new [`MorphEngineValidator`]. pub fn new() -> Self { - Self::default() + Self { + expected_withdraw_trie_roots: Arc::new(Mutex::new(BoundedFifoMap::new( + Self::MAX_EXPECTED_WITHDRAW_TRIE_ROOTS, + ))), + } } fn expectation_from_root(root: Option) -> WithdrawTrieRootExpectation { @@ -707,33 +823,16 @@ impl MorphEngineValidator { block_hash: B256, expectation: WithdrawTrieRootExpectation, ) { - let mut cache = self.expected_withdraw_trie_roots.lock(); - let is_new_entry = cache.entries.insert(block_hash, expectation).is_none(); - - if is_new_entry { - cache.order.push_back(block_hash); - - while cache.entries.len() > Self::MAX_EXPECTED_WITHDRAW_TRIE_ROOTS { - let Some(evicted_hash) = cache.order.pop_front() else { - break; - }; - cache.entries.remove(&evicted_hash); - } - } + self.expected_withdraw_trie_roots + .lock() + .insert(block_hash, expectation); } fn take_withdraw_trie_root_expectation( &self, block_hash: B256, ) -> Option { - let mut cache = self.expected_withdraw_trie_roots.lock(); - let removed = cache.entries.remove(&block_hash); - - if removed.is_some() { - cache.order.retain(|hash| *hash != block_hash); - } - - removed + self.expected_withdraw_trie_roots.lock().remove(&block_hash) } fn clear_withdraw_trie_root_expectation_on_error( @@ -789,6 +888,7 @@ impl MorphEngineValidator { Ok(()) } + #[cfg(test)] fn validate_withdraw_trie_root_update( &self, block_hash: B256, @@ -816,9 +916,15 @@ impl PayloadValidator for MorphEngineValidator { let expected_withdraw_trie_root = payload.expected_withdraw_trie_root; let sealed_block = Arc::unwrap_or_clone(payload.block); - if expected_withdraw_trie_root.is_some() { - let expectation = Self::expectation_from_root(expected_withdraw_trie_root); - self.record_withdraw_trie_root_expectation(sealed_block.hash(), expectation); + if let Some(root) = expected_withdraw_trie_root { + if !root.is_zero() { + self.record_withdraw_trie_root_expectation( + sealed_block.hash(), + WithdrawTrieRootExpectation::Verify(root), + ); + } else { + self.take_withdraw_trie_root_expectation(sealed_block.hash()); + } } Ok(sealed_block) @@ -1314,4 +1420,32 @@ mod tests { .is_ok() ); } + + #[test] + fn morph_engine_consensus_safe_blocks_bounded_fifo() { + let consensus = MorphEngineConsensus::new(MorphConsensus::new(Arc::new( + morph_chainspec::MORPH_MAINNET.as_ref().clone(), + ))); + let hash = B256::from([0x91; 32]); + + assert!(!consensus.is_safe(hash)); + + consensus.mark_safe(hash); + assert!(consensus.is_safe(hash)); + + // Bounded FIFO eviction at MAX_SAFE_BLOCKS (1024). + for idx in 0..=MorphEngineConsensus::MAX_SAFE_BLOCKS { + let mut raw = [0u8; 32]; + raw[..8].copy_from_slice(&(idx as u64).to_be_bytes()); + consensus.mark_safe(B256::from(raw)); + } + assert_eq!( + consensus.safe_blocks.lock().entries.len(), + MorphEngineConsensus::MAX_SAFE_BLOCKS + ); + assert!( + !consensus.is_safe(hash), + "oldest safe entry must be evicted once MAX_SAFE_BLOCKS is exceeded" + ); + } } diff --git a/crates/node/tests/it/engine.rs b/crates/node/tests/it/engine.rs index feb09b54..a951611b 100644 --- a/crates/node/tests/it/engine.rs +++ b/crates/node/tests/it/engine.rs @@ -1511,3 +1511,438 @@ async fn new_safe_l2_block_rejects_v2_morph_tx_before_celadon() -> eyre::Result< Ok(()) } + +/// `engine_newSafeL2Block` must exempt `VerifyHeader` rules (`TimestampIsInFuture`, +/// `TimestampIsInPast`, 1/1024 `GasLimit` bound, and `BaseFeeOverLimit`) and the local +/// per-block DA byte cap (`max_tx_payload_bytes_per_block`) across empty, non-empty, and +/// derivation-reorg blocks, matching morph-geth's `NewSafeL2Block` (`safe = true`). +#[tokio::test(flavor = "multi_thread")] +async fn new_safe_l2_block_exempts_header_bounds_and_da_size_limit() -> eyre::Result<()> { + reth_tracing::init_test_tracing(); + + // Set a tiny 128-byte consensus payload cap so any 256-byte L2 calldata tx would fail + // `MorphConsensus::validate_block_pre_execution` unless `Safe` mode exempts it. + let (mut nodes, wallet) = TestNodeBuilder::new() + .with_genesis_max_tx_payload_bytes(128) + .build() + .await?; + let node = nodes.pop().unwrap(); + let client = node.auth_server_handle().http_client(); + + let genesis = canonical_snapshot(&node)?; + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_secs(); + + // 1. Empty safe block (skips `InsertExecutedBlock`, goes through `new_payload -> validate_payload`): + // - timestamp 120s in the future, + // - gas_limit = 60_000_000 (2x genesis 30_000_000, > 1/1024 bound), + // - base_fee = 15 Gwei (> 10 Gwei `MORPH_MAXIMUM_BASE_FEE`). + let high_base_fee = 15_000_000_000u128; + let safe_block1 = SafeL2Data { + number: 1, + gas_limit: 60_000_000, + base_fee_per_gas: Some(high_base_fee), + timestamp: now + 120, + transactions: vec![], + parent_hash: Some(genesis.hash), + }; + let h1: MorphHeader = client + .request("engine_newSafeL2Block", (safe_block1,)) + .await?; + let h1_hash = h1.hash_slow(); + assert_eq!(canonical_snapshot(&node)?.hash, h1_hash); + assert_eq!(canonical_snapshot(&node)?.safe_hash, Some(h1_hash)); + + // 2. Non-empty safe block (goes through `on_inserted_executed_block`) with oversized L2 calldata + // (> 128-byte genesis DA limit), another 2x gas_limit jump, high base_fee, and future timestamp. + let oversized_tx0 = MorphTxBuilder::new(wallet.chain_id, wallet.inner.clone(), 0) + .with_v1_eth_fee() + .with_to(Address::with_last_byte(0x42)) + .with_data(vec![0xab; 256]) + .with_fees(25_000_000_000, 1_000_000_000) + .with_gas_limit(100_000) + .build_signed()?; + let safe_block2 = SafeL2Data { + number: 2, + gas_limit: 120_000_000, + base_fee_per_gas: Some(high_base_fee), + timestamp: now + 240, + transactions: vec![oversized_tx0.clone()], + parent_hash: Some(h1_hash), + }; + let h2: MorphHeader = client + .request("engine_newSafeL2Block", (safe_block2,)) + .await?; + assert_eq!(canonical_snapshot(&node)?.hash, h2.hash_slow()); + + // 3. Safe derivation reorg at `number <= canonical_head` (skips `InsertExecutedBlock` even + // though non-empty!) with `timestamp < parent.timestamp`, sharp gas_limit drop, and + // oversized L2 payload. + let safe_block2_reorg = SafeL2Data { + number: 2, + gas_limit: 20_000_000, + base_fee_per_gas: Some(high_base_fee), + timestamp: now + 115, + transactions: vec![oversized_tx0], + parent_hash: Some(h1_hash), + }; + let h2_reorg: MorphHeader = client + .request("engine_newSafeL2Block", (safe_block2_reorg,)) + .await?; + let h2_reorg_hash = h2_reorg.hash_slow(); + assert_ne!(h2_reorg_hash, h2.hash_slow()); + assert_eq!(canonical_snapshot(&node)?.hash, h2_reorg_hash); + assert_eq!(canonical_snapshot(&node)?.safe_hash, Some(h2_reorg_hash)); + + Ok(()) +} + +/// Verifies both fixes to `validate_next_l1_message_index`: +/// 1. Pre-Jade blocks with NO L1 messages and `next_l1_message_index < parent.next_l1_msg_index` +/// are accepted (live and `AlreadySeen`), while Pre-Jade blocks WITH L1 messages still reject +/// `next_l1_message_index < last_queue_index + 1`. +/// 2. Unpersisted in-memory `tree_state` parents (`provider.sealed_header_by_hash(parent) == None`) +/// are resolved via `TreeHeaderCache` so tampered `next_l1_message_index` on an `AlreadySeen` +/// child is rejected. +#[tokio::test(flavor = "multi_thread")] +async fn validate_next_l1_msg_index_pre_jade_empty_l1_and_unpersisted_tree_parent() +-> eyre::Result<()> { + reth_tracing::init_test_tracing(); + use reth_provider::HeaderProvider; + + // --- Part 1: Pre-Jade empty-L1-message block with decreased `next_l1_message_index` --- + let (mut pre_jade_nodes, _wallet) = TestNodeBuilder::new() + .with_schedule(HardforkSchedule::PreJade) + .build() + .await?; + let pre_jade = pre_jade_nodes.pop().unwrap(); + let pre_client = pre_jade.auth_server_handle().http_client(); + + let genesis = canonical_snapshot(&pre_jade)?; + let b1 = assemble_l2_block_v2( + &pre_jade, + AssembleL2BlockV2Params { + parent_hash: genesis.hash, + transactions: L1MessageBuilder::build_sequential(0, 2), + timestamp: Some(1), + }, + ) + .await?; + assert_eq!(b1.next_l1_message_index, 2); + import_l2_block(&pre_jade, b1.clone()).await?; + + // Build Block 2 with NO L1 messages, then set `next_l1_message_index = 0` (< parent's 2). + let mut b2_no_l1 = assemble_l2_block_v2( + &pre_jade, + AssembleL2BlockV2Params { + parent_hash: b1.hash, + transactions: vec![], + timestamp: Some(2), + }, + ) + .await?; + b2_no_l1.next_l1_message_index = 0; + + let v_res: GenericResponse = pre_client + .request("engine_validateL2Block", (b2_no_l1.clone(),)) + .await?; + assert!( + v_res.success, + "pre-Jade block without L1 messages must allow next_l1_message_index < parent" + ); + // AlreadySeen re-validation of the same Pre-Jade block (before FCU advances head) must also succeed. + let v_seen: GenericResponse = pre_client + .request("engine_validateL2Block", (b2_no_l1.clone(),)) + .await?; + assert!(v_seen.success); + + // Pre-Jade block on `b1` WITH L1 messages `[2, 3]` (`expected >= 4`) and `actual = 1` MUST + // fail both `validateL2Block` and `newL2BlockV2`. + let mut b2_with_l1 = assemble_l2_block_v2( + &pre_jade, + AssembleL2BlockV2Params { + parent_hash: b1.hash, + transactions: L1MessageBuilder::build_sequential(2, 2), + timestamp: Some(3), + }, + ) + .await?; + b2_with_l1.next_l1_message_index = 1; + let bad_with_l1: GenericResponse = pre_client + .request("engine_validateL2Block", (b2_with_l1.clone(),)) + .await?; + assert!(!bad_with_l1.success); + assert!(import_l2_block(&pre_jade, b2_with_l1).await.is_err()); + + let imported_b2 = import_l2_block(&pre_jade, b2_no_l1).await?; + assert_eq!(imported_b2.next_l1_msg_index, 0); + + // --- Part 2: Post-Jade unpersisted `tree_state` parent lookup via `TreeHeaderCache` --- + let (mut nodes, wallet) = TestNodeBuilder::new().with_num_nodes(2).build().await?; + let follower = nodes.pop().expect("two nodes requested"); + let sequencer = nodes.pop().expect("two nodes requested"); + + let seq_genesis = canonical_snapshot(&sequencer)?; + // Advance `follower` onto canonical chain `Genesis -> a1 -> a2` so side-branch `parent_p` + // (height 1) will stay non-canonical in `tree_state` (`provider.sealed_header_by_hash == None`). + let a1 = assemble_l2_block_v2( + &follower, + AssembleL2BlockV2Params { + parent_hash: seq_genesis.hash, + transactions: vec![], + timestamp: Some(10), + }, + ) + .await?; + import_l2_block(&follower, a1.clone()).await?; + let a2 = assemble_l2_block_v2( + &follower, + AssembleL2BlockV2Params { + parent_hash: a1.hash, + transactions: vec![], + timestamp: Some(11), + }, + ) + .await?; + import_l2_block(&follower, a2).await?; + + // Build side branch `Genesis -> parent_p (L1 msgs [0, 1]) -> child_c (tx0, non-empty)` on `sequencer`. + let parent_p = assemble_l2_block_v2( + &sequencer, + AssembleL2BlockV2Params { + parent_hash: seq_genesis.hash, + transactions: L1MessageBuilder::build_sequential(0, 2), + timestamp: Some(1), + }, + ) + .await?; + assert_eq!(parent_p.next_l1_message_index, 2); + import_l2_block(&sequencer, parent_p.clone()).await?; + + let raw_tx0 = make_transfer_tx(wallet.chain_id, wallet.inner.clone(), 0).await; + let tx0_hash = sequencer.rpc.inject_tx(raw_tx0).await?; + wait_until_pooled(&sequencer, tx0_hash).await?; + let child_c = assemble_l2_block_v2( + &sequencer, + AssembleL2BlockV2Params { + parent_hash: parent_p.hash, + transactions: vec![], + timestamp: Some(2), + }, + ) + .await?; + assert_eq!(child_c.next_l1_message_index, 2); + + // Insert `parent_p` and `child_c` into `follower`'s `tree_state` via `beacon_engine_handle.new_payload` + // WITHOUT FCU, so `parent_p` resides ONLY in `tree_state` (not in `CanonicalInMemoryState` or MDBX) + // and `child_c` is armed as `AlreadySeen` in `follower`'s `tree_state`. + let decode_sealed = + |data: &ExecutableL2Data| -> eyre::Result { + use alloy_consensus::proofs; + use reth_primitives_traits::SealedBlock; + let txs = data + .transactions + .iter() + .map(|raw| { + let mut slice = raw.as_ref(); + Ok(morph_primitives::MorphTxEnvelope::decode_2718(&mut slice)?) + }) + .collect::>>()?; + let header = MorphHeader { + inner: alloy_consensus::Header { + parent_hash: data.parent_hash, + beneficiary: data.miner, + state_root: data.state_root, + transactions_root: proofs::calculate_transaction_root(&txs), + receipts_root: data.receipts_root, + logs_bloom: alloy_primitives::Bloom::from_slice(&data.logs_bloom), + number: data.number, + gas_limit: data.gas_limit, + gas_used: data.gas_used, + timestamp: data.timestamp, + base_fee_per_gas: data.base_fee_per_gas.map(|f| f as u64), + ..Default::default() + }, + next_l1_msg_index: data.next_l1_message_index, + }; + let sealed = SealedBlock::seal_slow(morph_primitives::Block::new( + header, + morph_primitives::BlockBody { + transactions: txs, + ommers: vec![], + withdrawals: None, + }, + )); + assert_eq!(sealed.hash(), data.hash); + Ok(MorphPayloadTypes::block_to_payload(sealed, None)) + }; + + let p_status = follower + .inner + .add_ons_handle + .beacon_engine_handle + .new_payload(decode_sealed(&parent_p)?) + .await?; + assert!(p_status.is_valid()); + assert!( + follower + .inner + .provider + .sealed_header_by_hash(parent_p.hash)? + .is_none(), + "precondition: parent_p must reside only in tree_state, not in provider/MDBX" + ); + + let c_status = follower + .inner + .add_ons_handle + .beacon_engine_handle + .new_payload(decode_sealed(&child_c)?) + .await?; + assert!(c_status.is_valid()); + + // `child_c` is now `AlreadySeen` in `follower`'s `tree_state`, and its parent `parent_p` + // is only in `tree_state`: tampering `next_l1_message_index` on `new_payload` MUST fail + // via `convert_payload_to_block` without poisoning `invalid_headers`! + let mut child_c_tampered = child_c.clone(); + child_c_tampered.next_l1_message_index = 99; + let tampered_status = follower + .inner + .add_ons_handle + .beacon_engine_handle + .new_payload(decode_sealed(&child_c_tampered)?) + .await?; + assert!( + tampered_status.is_invalid(), + "new_payload must reject tampered next_l1_message_index with tree_state parent: {tampered_status:?}" + ); + assert!( + format!("{tampered_status:?}").contains("invalid block.NextL1MsgIndex"), + "unexpected validation error: {tampered_status:?}" + ); + + // Honest `child_c` must still be valid (`invalid_headers` not poisoned). + let honest_status = follower + .inner + .add_ons_handle + .beacon_engine_handle + .new_payload(decode_sealed(&child_c)?) + .await?; + assert!( + honest_status.is_valid(), + "honest AlreadySeen child_c must remain valid: {honest_status:?}" + ); + + Ok(()) +} + +/// `[MR-14]` When `engine_newL2BlockV2` reorganizes past an existing `safe` block so that +/// the old `safe` block is no longer on the canonical chain, the orphaned `safe` tag must be +/// rewound to the current `finalized` block (or genesis when no block is finalized yet) rather +/// than pointing `"safe"` RPC queries at the abandoned fork. +#[tokio::test(flavor = "multi_thread")] +async fn new_l2_block_v2_reorg_rewinds_orphaned_safe_tag() -> eyre::Result<()> { + reth_tracing::init_test_tracing(); + + let (mut nodes, _wallet) = TestNodeBuilder::new().build().await?; + let node = nodes.pop().unwrap(); + let auth = node.auth_server_handle().http_client(); + let rpc = node + .rpc_client() + .ok_or_else(|| eyre::eyre!("HTTP RPC client not available"))?; + + let genesis = canonical_snapshot(&node)?; + + // 1. Before any finalized block exists: build Genesis -> a1 (safe) -> a2 (safe), then + // reorg onto Genesis -> b1 via `engine_newL2BlockV2`. `safe` must rewind to Genesis. + let a1 = assemble_l2_block_v2( + &node, + AssembleL2BlockV2Params { + parent_hash: genesis.hash, + transactions: vec![], + timestamp: Some(10), + }, + ) + .await?; + import_l2_block(&node, a1.clone()).await?; + let a2 = assemble_l2_block_v2( + &node, + AssembleL2BlockV2Params { + parent_hash: a1.hash, + transactions: vec![], + timestamp: Some(11), + }, + ) + .await?; + import_l2_block(&node, a2.clone()).await?; + auth.request::<(), _>("engine_setBlockTags", (a2.hash, B256::ZERO)) + .await?; + assert_eq!(canonical_snapshot(&node)?.safe_hash, Some(a2.hash)); + + let b1 = assemble_l2_block_v2( + &node, + AssembleL2BlockV2Params { + parent_hash: genesis.hash, + transactions: vec![], + timestamp: Some(20), + }, + ) + .await?; + let imported_b1: MorphHeader = auth.request("engine_newL2BlockV2", (b1.clone(),)).await?; + assert_eq!(imported_b1.hash_slow(), b1.hash); + assert_eq!( + canonical_snapshot(&node)?.safe_hash, + Some(genesis.hash), + "orphaned safe tag without finalized block must rewind to genesis" + ); + let safe_rpc_block: serde_json::Value = + rpc.request("eth_getBlockByNumber", ("safe", false)).await?; + assert_eq!( + safe_rpc_block["hash"].as_str(), + Some(genesis.hash.to_string().as_str()) + ); + + // 2. With finalized = b1: advance b1 -> b2 (safe), then reorg onto b1 -> c2 via + // `engine_newL2BlockV2`. `safe` must rewind to finalized `b1` (never stay on `b2`). + let b2 = assemble_l2_block_v2( + &node, + AssembleL2BlockV2Params { + parent_hash: b1.hash, + transactions: vec![], + timestamp: Some(21), + }, + ) + .await?; + import_l2_block(&node, b2.clone()).await?; + auth.request::<(), _>("engine_setBlockTags", (b2.hash, b1.hash)) + .await?; + assert_eq!(canonical_snapshot(&node)?.safe_hash, Some(b2.hash)); + assert_eq!(node.inner.provider.finalized_block_hash()?, Some(b1.hash)); + + let c2 = assemble_l2_block_v2( + &node, + AssembleL2BlockV2Params { + parent_hash: b1.hash, + transactions: vec![], + timestamp: Some(30), + }, + ) + .await?; + let imported_c2: MorphHeader = auth.request("engine_newL2BlockV2", (c2.clone(),)).await?; + assert_eq!(imported_c2.hash_slow(), c2.hash); + assert_eq!( + canonical_snapshot(&node)?.safe_hash, + Some(b1.hash), + "orphaned safe tag must rewind to finalized block b1" + ); + let safe_rpc_block2: serde_json::Value = + rpc.request("eth_getBlockByNumber", ("safe", false)).await?; + assert_eq!( + safe_rpc_block2["hash"].as_str(), + Some(b1.hash.to_string().as_str()) + ); + + Ok(()) +} diff --git a/crates/node/tests/it/invalid_payload_recovery.rs b/crates/node/tests/it/invalid_payload_recovery.rs index a9082125..b74c0628 100644 --- a/crates/node/tests/it/invalid_payload_recovery.rs +++ b/crates/node/tests/it/invalid_payload_recovery.rs @@ -277,65 +277,192 @@ async fn tampered_next_l1_msg_index_rejected_when_block_already_seen() -> eyre:: Ok(()) } -/// M-H07: A locally built non-empty block that violates consensus (e.g., future timestamp) -/// must be rejected by `on_inserted_executed_block` so it is NOT pre-inserted into -/// `tree_state` and cannot subsequently bypass validation via `AlreadySeen`. +/// Structural consensus violations (such as non-empty `extra_data` or `gas_used > gas_limit`) +/// must still be rejected even when `is_safe` (`engine_newSafeL2Block`) is set. #[tokio::test(flavor = "multi_thread")] -async fn pre_inserted_consensus_invalid_block_is_rejected_and_not_cached() -> eyre::Result<()> { +async fn safe_mode_still_rejects_structural_consensus_violations() -> eyre::Result<()> { reth_tracing::init_test_tracing(); + use morph_payload_types::MorphPayloadTypes; + use reth_node_api::PayloadTypes; + use reth_primitives_traits::SealedBlock; - let (mut nodes, wallet) = TestNodeBuilder::new().build().await?; - let node = nodes.pop().expect("one node requested"); + let (mut nodes, _wallet) = TestNodeBuilder::new().build().await?; + let mut node = nodes.pop().expect("one node requested"); - let raw_tx = make_transfer_tx(wallet.chain_id, wallet.inner.clone(), wallet.inner_nonce).await; - let tx_hash = node.rpc.inject_tx(raw_tx).await?; - wait_until_pooled(&node, tx_hash).await?; + let base_payload = build_block_no_submit(&mut node, vec![]).await?; - let before = canonical_snapshot(&node)?; - let future_timestamp = std::time::SystemTime::now() + let mut bad_extra = morph_primitives::Block::new( + base_payload.block().header().clone(), + base_payload.block().body().clone(), + ); + bad_extra.header.inner.extra_data = alloy_primitives::Bytes::from_static(b"invalid"); + let payload_extra = + MorphPayloadTypes::block_to_payload(SealedBlock::seal_slow(bad_extra), None) + .with_safe_validation(); + let status = node + .inner + .add_ons_handle + .beacon_engine_handle + .new_payload(payload_extra) + .await?; + assert!( + status.is_invalid(), + "non-empty extra_data must be rejected in safe mode: {status:?}" + ); + + let mut bad_gas = morph_primitives::Block::new( + base_payload.block().header().clone(), + base_payload.block().body().clone(), + ); + bad_gas.header.inner.gas_used = bad_gas.header.inner.gas_limit + 1; + let payload_gas = MorphPayloadTypes::block_to_payload(SealedBlock::seal_slow(bad_gas), None) + .with_safe_validation(); + let status = node + .inner + .add_ons_handle + .beacon_engine_handle + .new_payload(payload_gas) + .await?; + assert!( + status.is_invalid(), + "gas_used > gas_limit must be rejected in safe mode: {status:?}" + ); + + Ok(()) +} + +/// When a `Safe` payload arrives while its parent is not yet in the engine tree, +/// `EngineApiTreeHandler` converts it via `convert_payload_to_block`, buffers the +/// `SealedBlock`, and later validates it via `MorphTreeEngineValidator::validate_block` +/// once the parent connects (`try_connect_buffered_blocks`). The `Safe` validation +/// mode must survive buffering (and not be clobbered by `validate_block`), otherwise +/// valid L1-derived blocks with future timestamps, >1/1024 gas-limit jumps, high base +/// fees, or oversized DA payloads would be rejected and poison `invalid_headers`. +#[tokio::test(flavor = "multi_thread")] +async fn buffered_safe_payload_preserves_validation_mode_when_parent_connects() -> eyre::Result<()> +{ + reth_tracing::init_test_tracing(); + use alloy_primitives::Address; + use alloy_rpc_types_engine::ForkchoiceState; + use jsonrpsee::core::client::ClientT; + use morph_node::test_utils::MorphTxBuilder; + use morph_payload_types::{MorphPayloadTypes, SafeL2Data}; + use morph_primitives::MorphHeader; + use reth_node_api::PayloadTypes; + use reth_primitives_traits::SealedBlock; + use reth_provider::BlockReader; + + let (mut producer_nodes, wallet) = TestNodeBuilder::new() + .with_genesis_max_tx_payload_bytes(128) + .build() + .await?; + let producer = producer_nodes.pop().unwrap(); + let prod_client = producer.auth_server_handle().http_client(); + + let (mut follower_nodes, _) = TestNodeBuilder::new() + .with_genesis_max_tx_payload_bytes(128) + .build() + .await?; + let follower = follower_nodes.pop().unwrap(); + + let genesis = canonical_snapshot(&producer)?; + assert_eq!(genesis.hash, canonical_snapshot(&follower)?.hash); + + let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap_or_default() - .as_secs() - + 3600; + .as_secs(); + + // Build Block 1 (normal empty block) on `producer`. + let safe_b1 = SafeL2Data { + number: 1, + gas_limit: 30_000_000, + base_fee_per_gas: Some(1_000_000), + timestamp: genesis.number + 1, + transactions: vec![], + parent_hash: Some(genesis.hash), + }; + let h1: MorphHeader = prod_client + .request("engine_newSafeL2Block", (safe_b1,)) + .await?; + let b1_hash = h1.hash_slow(); + let sealed_b1 = SealedBlock::seal_slow( + producer + .inner + .provider + .block_by_number(1)? + .expect("block 1 in producer"), + ); - let future_block = assemble_l2_block_v2( - &node, - AssembleL2BlockV2Params { - parent_hash: before.hash, - transactions: vec![], - timestamp: Some(future_timestamp), - }, - ) - .await?; - assert_eq!( - future_block.transactions.len(), - 1, - "precondition: block must be non-empty so InsertExecutedBlock is emitted" + // Build Block 2 on `producer` requiring `Safe` exemptions on every axis: + // - future timestamp (`now + 180`), + // - 2x gas_limit jump (`60_000_000`, > 1/1024 bound), + // - base_fee > MORPH_MAXIMUM_BASE_FEE (`15 Gwei`), + // - 256-byte L2 calldata (`> 128`-byte genesis DA payload limit). + let oversized_tx = MorphTxBuilder::new(wallet.chain_id, wallet.inner.clone(), 0) + .with_v1_eth_fee() + .with_to(Address::with_last_byte(0x42)) + .with_data(vec![0xcd; 256]) + .with_fees(25_000_000_000, 1_000_000_000) + .with_gas_limit(100_000) + .build_signed()?; + let safe_b2 = SafeL2Data { + number: 2, + gas_limit: 60_000_000, + base_fee_per_gas: Some(15_000_000_000), + timestamp: now + 180, + transactions: vec![oversized_tx], + parent_hash: Some(b1_hash), + }; + let h2: MorphHeader = prod_client + .request("engine_newSafeL2Block", (safe_b2,)) + .await?; + let b2_hash = h2.hash_slow(); + let sealed_b2 = SealedBlock::seal_slow( + producer + .inner + .provider + .block_by_number(2)? + .expect("block 2 in producer"), ); - // Give the async engine tree task ample time to process InsertExecutedBlock; - // `on_inserted_executed_block` must reject the future-timestamp header. - tokio::time::sleep(std::time::Duration::from_millis(500)).await; - assert_eq!( - node.inner.provider.pending_block_num_hash()?, - None, - "consensus-invalid future block must not be pre-inserted into tree_state" + // 1. Submit Block 2 (`Safe`) to `follower` BEFORE Block 1 so `follower` buffers it via + // `convert_payload_to_block` -> `self.state.buffer` (`Syncing`). + let follower_engine = &follower.inner.add_ons_handle.beacon_engine_handle; + let b2_safe_payload = + MorphPayloadTypes::block_to_payload(sealed_b2, None).with_safe_validation(); + let b2_buffered_status = follower_engine.new_payload(b2_safe_payload).await?; + assert!( + b2_buffered_status.is_syncing(), + "disconnected Safe block 2 must buffer as Syncing: {b2_buffered_status:?}" ); - // Importing it must fail consensus validation rather than hitting AlreadySeen. - let err = import_l2_block(&node, future_block) - .await - .expect_err("future-timestamp block must be rejected on import") - .to_string(); + // 2. Now submit Block 1 (`Full`) to `follower`: `try_connect_buffered_blocks` immediately + // validates buffered Block 2 through `MorphTreeEngineValidator::validate_block`. + let b1_payload = MorphPayloadTypes::block_to_payload(sealed_b1, None); + let b1_status = follower_engine.new_payload(b1_payload).await?; assert!( - err.to_lowercase().contains("future"), - "expected future-timestamp consensus rejection, got: {err}" + b1_status.is_valid(), + "connecting parent block 1 must succeed: {b1_status:?}" ); - assert_eq!( - canonical_snapshot(&node)?, - before, - "canonical state must remain unchanged after rejecting future block" + + // 3. Forkchoice update to Block 2 must succeed (`Valid`), proving buffered Block 2 + // kept its `Safe` exemptions during `validate_block` and did not poison `invalid_headers`. + let fcu = follower_engine + .fork_choice_updated( + ForkchoiceState { + head_block_hash: b2_hash, + safe_block_hash: b2_hash, + finalized_block_hash: alloy_primitives::B256::ZERO, + }, + None, + ) + .await?; + assert!( + fcu.is_valid(), + "FCU to connected Safe block 2 must be Valid (not LinksToRejectedPayload): {fcu:?}" ); + assert_eq!(canonical_snapshot(&follower)?.hash, b2_hash); Ok(()) } diff --git a/crates/node/tests/it/morph_tx.rs b/crates/node/tests/it/morph_tx.rs index d5456a1e..a508430c 100644 --- a/crates/node/tests/it/morph_tx.rs +++ b/crates/node/tests/it/morph_tx.rs @@ -1626,3 +1626,233 @@ async fn morph_tx_v2_self_delegation_executes_delegate_code_in_same_tx() -> eyre Ok(()) } + +// ============================================================================= +// M-M12 regression tests: Call-mode alt-token fee pool eviction safety +// ============================================================================= + +/// Building a candidate block via `engine_assembleL2BlockV2` on an older non-canonical +/// ancestor (where a Call-mode token was NOT yet active) must NOT evict a `MorphTx` that +/// IS valid on the current canonical head. +#[tokio::test(flavor = "multi_thread")] +async fn assemble_on_non_canonical_parent_does_not_evict_canonical_valid_morph_tx() +-> eyre::Result<()> { + reth_tracing::init_test_tracing(); + use alloy_consensus::TxReceipt; + use morph_payload_types::AssembleL2BlockV2Params; + use reth_provider::ReceiptProvider; + use reth_transaction_pool::TransactionPool; + + let registry = alloy_primitives::address!("5300000000000000000000000000000000000021"); + // Token 1 `decimals | isActive` packed slot in `test-genesis.json`: + // `0x1200` = decimals 18, `isActive = false`; `0x1201` = decimals 18, `isActive = true`. + let active_slot: B256 = + "0x53bdca72fa8d2e145a1b3bd11cde5bd75428acd18eac3d6adf4e06e7e637706f".parse()?; + let inactive_word = B256::from(U256::from(0x1200u64)); + let active_word = B256::from(U256::from(0x1201u64)); + + // 7-byte runtime on L2TokenRegistry: `SSTORE(CALLDATALOAD(0), CALLDATALOAD(32))` (`6020355f355500`). + let (mut nodes, wallet) = TestNodeBuilder::new() + .with_account_code(registry, "0x6020355f355500") + .with_account_storage(registry, active_slot, inactive_word) + .build() + .await?; + let node = nodes.pop().unwrap(); + let genesis = super::helpers::canonical_snapshot(&node)?; + + // Block 1: activate `TEST_TOKEN_ID` on canonical chain. + let mut activate_calldata = Vec::with_capacity(64); + activate_calldata.extend_from_slice(active_slot.as_slice()); + activate_calldata.extend_from_slice(active_word.as_slice()); + let activate_tx = MorphTxBuilder::new(wallet.chain_id, wallet.inner.clone(), 0) + .with_v1_eth_fee() + .with_to(registry) + .with_data(activate_calldata) + .with_gas_limit(100_000) + .build_signed()?; + let activate_hash = node.rpc.inject_tx(activate_tx).await?; + super::helpers::wait_until_pooled(&node, activate_hash).await?; + let block1 = super::helpers::assemble_l2_block_v2( + &node, + AssembleL2BlockV2Params { + parent_hash: genesis.hash, + transactions: vec![], + timestamp: Some(1), + }, + ) + .await?; + super::helpers::import_l2_block(&node, block1.clone()).await?; + super::helpers::wait_until_evicted(&node, activate_hash).await?; + + // Inject a valid Call-mode MorphTx (`fee_token_id = 1`) from account 1 on canonical Block 1. + let signer1 = wallet_at_index(1, wallet.chain_id); + let morph_tx = MorphTxBuilder::new(wallet.chain_id, signer1, 0) + .with_v0_token_fee(TEST_TOKEN_ID) + .with_to(Address::with_last_byte(0x77)) + .build_signed()?; + let morph_tx_hash = node.rpc.inject_tx(morph_tx).await?; + super::helpers::wait_until_pooled(&node, morph_tx_hash).await?; + + // Assemble a candidate block on Genesis (Block 0), where `TEST_TOKEN_ID` is inactive + // (`MorphInvalidTransaction::TokenNotActive(1)`). + let stale_branch = super::helpers::assemble_l2_block_v2( + &node, + AssembleL2BlockV2Params { + parent_hash: genesis.hash, + transactions: vec![], + timestamp: Some(10), + }, + ) + .await?; + assert!( + stale_branch.transactions.is_empty(), + "MorphTx must be skipped on stale parent where token was inactive" + ); + assert!( + node.inner.pool.contains(&morph_tx_hash), + "non-canonical parent build must NOT evict canonical-valid MorphTx from global pool" + ); + + // Assembling & importing Block 2 on canonical Block 1 must include and execute the MorphTx cleanly. + let block2 = super::helpers::assemble_l2_block_v2( + &node, + AssembleL2BlockV2Params { + parent_hash: block1.hash, + transactions: vec![], + timestamp: Some(2), + }, + ) + .await?; + assert_eq!(block2.transactions.len(), 1); + super::helpers::import_l2_block(&node, block2).await?; + super::helpers::wait_until_evicted(&node, morph_tx_hash).await?; + let receipt = node + .inner + .provider + .receipt_by_hash(morph_tx_hash)? + .expect("MorphTx receipt must exist"); + assert!(receipt.status()); + + Ok(()) +} + +/// M-M12: A Call-mode `MorphTx` whose token contract reverts on `transfer` +/// (`MorphInvalidTransaction::TokenTransferFailed`) is evicted from the global pool when +/// building on the synchronized canonical head, while eviction is suppressed during the +/// async txpool maintenance lag window (`pool.last_seen_block_hash != parent_hash`). +#[tokio::test(flavor = "multi_thread")] +async fn broken_token_morph_tx_evicted_only_when_pool_synced_to_canonical_head() -> eyre::Result<()> +{ + reth_tracing::init_test_tracing(); + use alloy_consensus::Sealable; + use jsonrpsee::core::client::ClientT; + use morph_payload_types::{AssembleL2BlockV2Params, SafeL2Data}; + use morph_primitives::MorphHeader; + use reth_transaction_pool::{TransactionPool, TransactionPoolExt}; + + let registry = alloy_primitives::address!("5300000000000000000000000000000000000021"); + let token_addr_slot: B256 = + "0x53bdca72fa8d2e145a1b3bd11cde5bd75428acd18eac3d6adf4e06e7e637706d".parse()?; + let broken_token = Address::with_last_byte(0x99); + let mut broken_token_word = [0u8; 32]; + broken_token_word[12..].copy_from_slice(broken_token.as_slice()); + + // `broken_token`: `balanceOf(address)` (`0x70a08231`) returns `U256::MAX` so balance checks + // pass, while `transfer(address,uint256)` reverts -> `TokenTransferFailed`. + let broken_token_runtime = "0x5f3560e01c6370a08231146011575f5ffd5b5f195f5260205ff3"; + + let (mut nodes, wallet) = TestNodeBuilder::new() + .with_account_code(registry, "0x6020355f355500") + .with_account_code(broken_token, broken_token_runtime) + .build() + .await?; + let node = nodes.pop().unwrap(); + let genesis = super::helpers::canonical_snapshot(&node)?; + + // Inject a valid Call-mode MorphTx (`fee_token_id = 1`) from account 1 while the token works. + let signer1 = wallet_at_index(1, wallet.chain_id); + let morph_tx = MorphTxBuilder::new(wallet.chain_id, signer1, 0) + .with_v0_token_fee(TEST_TOKEN_ID) + .with_to(Address::with_last_byte(0x77)) + .with_fees(5_000_000_000, 1_000_000_000) + .build_signed()?; + let morph_tx_hash = node.rpc.inject_tx(morph_tx).await?; + super::helpers::wait_until_pooled(&node, morph_tx_hash).await?; + + // Commit Block 1 switching `TEST_TOKEN_ID` to `broken_token` using a deterministic supplied tx. + let mut point_to_broken_calldata = Vec::with_capacity(64); + point_to_broken_calldata.extend_from_slice(token_addr_slot.as_slice()); + point_to_broken_calldata.extend_from_slice(&broken_token_word); + let mutator_tx = MorphTxBuilder::new(wallet.chain_id, wallet.inner.clone(), 0) + .with_v1_eth_fee() + .with_to(registry) + .with_data(point_to_broken_calldata) + .with_fees(50_000_000_000, 50_000_000_000) + .with_gas_limit(100_000) + .build_signed()?; + let client = node.auth_server_handle().http_client(); + let block1: MorphHeader = client + .request( + "engine_newSafeL2Block", + (SafeL2Data { + number: 1, + gas_limit: 30_000_000, + base_fee_per_gas: Some(1_000_000), + timestamp: 1, + transactions: vec![mutator_tx], + parent_hash: Some(genesis.hash), + },), + ) + .await?; + let block1_hash = block1.hash_slow(); + + let deadline = tokio::time::Instant::now() + super::helpers::LOCAL_POLL_BUDGET; + while node.inner.pool.block_info().last_seen_block_hash != block1_hash { + assert!(tokio::time::Instant::now() < deadline); + tokio::time::sleep(super::helpers::POLL_INTERVAL).await; + } + + // 1. Simulate async txpool maintenance lag (`last_seen_block_hash != parent_hash`): + // eviction is suppressed for that lagged tick. + let mut lagged_info = node.inner.pool.block_info(); + lagged_info.last_seen_block_hash = genesis.hash; + node.inner.pool.set_block_info(lagged_info); + + let lagged_block2 = super::helpers::assemble_l2_block_v2( + &node, + AssembleL2BlockV2Params { + parent_hash: block1_hash, + transactions: vec![], + timestamp: Some(2), + }, + ) + .await?; + assert!(lagged_block2.transactions.is_empty()); + assert!( + node.inner.pool.contains(&morph_tx_hash), + "pool maintenance lag window (pool last_seen_block_hash != parent_hash) must suppress eviction" + ); + + // 2. Once `pool.block_info().last_seen_block_hash` catches up to `block1_hash`, + // the next canonical build evicts the genuinely broken MorphTx cleanly. + let mut synced_info = node.inner.pool.block_info(); + synced_info.last_seen_block_hash = block1_hash; + node.inner.pool.set_block_info(synced_info); + + let block2 = super::helpers::assemble_l2_block_v2( + &node, + AssembleL2BlockV2Params { + parent_hash: block1_hash, + transactions: vec![], + timestamp: Some(3), + }, + ) + .await?; + assert!(block2.transactions.is_empty()); + assert!( + !node.inner.pool.contains(&morph_tx_hash), + "genuinely broken MorphTx on clean canonical head MUST be evicted" + ); + + Ok(()) +} diff --git a/crates/node/tests/it/rpc.rs b/crates/node/tests/it/rpc.rs index e53dfbad..eaac1b78 100644 --- a/crates/node/tests/it/rpc.rs +++ b/crates/node/tests/it/rpc.rs @@ -1804,14 +1804,17 @@ fn encode_balance_of(addr: Address) -> String { format!("0x{}", alloy_primitives::hex::encode(buf)) } -/// `eth_simulateV1` with `validation: false` must disable L1 and L2 fee charging -/// for both ETH and token-fee MorphTxs post-Curie with non-zero L1 oracle fees: -/// - Omitted-`from` and zero-balance callers succeed. -/// - Funded caller balances and FeeVault balance are unchanged by L1/L2 fees -/// (and `value > 0` transfers move only `value`). -/// - Call-mode token-fee MorphTxs neither deduct tokens nor emit fee `Transfer` logs. +/// End-to-end `eth_simulateV1` coverage on a single post-Curie node with non-zero L1 oracle fees: +/// 1. `validation: false` runs calls in an empty envelope with no L1 fee: calls without fee fields +/// (ETH & call-mode token MorphTxs, including `traceTransfers: true`) leave FeeVault/caller +/// balances unchanged and move only `value`; an explicit gas price pays the L2 fee only; and, +/// as upstream, `value` or a gas price the caller cannot cover fails with insufficient funds. +/// 2. `validation: true` charges full placeholder-signature Curie `commit + blob` L1 + L2 fees +/// (for both ETH and token-fee MorphTxs) while keeping zero `r`/`s`/`v`/`yParity` on returned txs. +/// 3. `validation: true` with legacy `gasPrice` + `feeTokenID` on a zero-ETH caller executes as +/// a `0x7f` token-fee MorphTx rather than degrading to Legacy ETH. #[tokio::test(flavor = "multi_thread")] -async fn simulate_v1_validation_false_skips_l1_and_l2_fees() -> eyre::Result<()> { +async fn eth_simulate_v1_morph_l1_fee_and_token_semantics() -> eyre::Result<()> { reth_tracing::init_test_tracing(); const L1_ORACLE: Address = @@ -1820,10 +1823,17 @@ async fn simulate_v1_validation_false_skips_l1_and_l2_fees() -> eyre::Result<()> alloy_primitives::address!("530000000000000000000000000000000000000a"); const TEST_TOKEN: Address = alloy_primitives::address!("5300000000000000000000000000000000000022"); - const L1_BASE_FEE: u64 = 10_000_000_000; // 10 gwei (non-zero Curie commit fee) - const L1_BLOB_BASE_FEE: u64 = 10_000_000_000; // 10 gwei (non-zero Curie blob fee) - // Runtime bytecode: return `BALANCE(calldataload(0))` (32 bytes). + const L1_BASE_FEE: u64 = 10_000_000_000; // 10 gwei + const L1_BLOB_BASE_FEE: u64 = 10_000_000_000; // 10 gwei + // Matches `tests/assets/test-genesis.json` slots 7 & 8. + const COMMIT_SCALAR: u128 = 0x35ba5d7b55; + const BLOB_SCALAR: u128 = 0x18e38a4c; + const L1_FEE_PRECISION: u128 = 1_000_000_000; + const TRANSFER_TOPIC: &str = + "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"; + // Return `BALANCE(calldataload(0))` (32 bytes) / `(BALANCE(0), BALANCE(32))` (64 bytes). const BALANCE_READER_CODE: &str = "0x6000353160005260206000f3"; + const DUAL_BALANCE_READER_CODE: &str = "0x600035316000526020353160205260406000f3"; let (mut nodes, wallet) = TestNodeBuilder::new() .with_account_storage(L1_ORACLE, U256::from(1u64), U256::from(L1_BASE_FEE)) @@ -1831,6 +1841,7 @@ async fn simulate_v1_validation_false_skips_l1_and_l2_fees() -> eyre::Result<()> .build() .await?; let mut node = nodes.pop().unwrap(); + let chain_id = wallet.chain_id; let funded = wallet.inner.address(); advance_chain(1, &mut node, wallet_to_arc(wallet)).await?; @@ -1849,483 +1860,1258 @@ async fn simulate_v1_validation_false_skips_l1_and_l2_fees() -> eyre::Result<()> .map(|a| a.balance) .unwrap_or_default(); - // Read funded wallet's initial call-mode fee token balance via eth_call. let initial_token_hex: String = client .request( "eth_call", ( - serde_json::json!({ - "to": TEST_TOKEN, - "input": encode_balance_of(funded), - }), + serde_json::json!({ "to": TEST_TOKEN, "input": encode_balance_of(funded) }), "latest", ), ) .await?; let initial_token_balance = decode_u256_word(&initial_token_hex); - assert!( - initial_token_balance > U256::ZERO, - "funded wallet must hold genesis test fee tokens" - ); + assert!(initial_token_balance > U256::ZERO); + + let has_transfer_log = |call: &Value| { + call["logs"] + .as_array() + .expect("logs array") + .iter() + .any(|log| { + log["topics"] + .as_array() + .and_then(|t| t.first()) + .and_then(Value::as_str) + == Some(TRANSFER_TOPIC) + }) + }; - let reader_addr = Address::random(); - let unfunded_caller = Address::random(); - let recipient = Address::random(); - let value_recipient = Address::random(); - let transfer_value = U256::from(1_000_000_000_000_000_000u128); // 1 ETH - let calldata = format!("0x{}", alloy_primitives::hex::encode(vec![0xaa; 128])); - - let payload = serde_json::json!({ - "blockStateCalls": [{ - "stateOverrides": { - reader_addr.to_string(): { - "code": BALANCE_READER_CODE, - }, - }, - "calls": [ - // 0: omitted `from` (spec default 0x0000...0000, zero ETH) - { - "to": recipient, - "input": calldata, - }, - // 1: explicit zero-balance caller with non-zero gasPrice - { - "from": unfunded_caller, - "to": recipient, - "gasPrice": "0x3b9aca00", - "input": calldata, - }, - // 2: funded caller, value = 0, non-zero EIP-1559 fee caps + calldata - { - "from": funded, - "to": recipient, - "maxFeePerGas": "0x77359400", - "maxPriorityFeePerGas": "0x3b9aca00", - "input": calldata, - }, - // 3: check funded caller ETH balance unchanged - { - "to": reader_addr, - "input": encode_address_word(funded), - }, - // 4: check FeeVault ETH balance unchanged (no phantom reward) - { - "to": reader_addr, - "input": encode_address_word(FEE_VAULT), - }, - // 5: funded caller, value = 1 ETH transfer - { - "from": funded, - "to": value_recipient, - "value": format!("{transfer_value:#x}"), - "maxFeePerGas": "0x77359400", - "maxPriorityFeePerGas": "0x3b9aca00", - }, - // 6: check funded caller ETH balance decreased by exact transfer_value - { - "to": reader_addr, - "input": encode_address_word(funded), + // ------------------------------------------------------------------------- + // 1. `validation: false` charges no L1 fee for ETH & call-mode token MorphTxs + // ------------------------------------------------------------------------- + { + let reader_addr = Address::random(); + let unfunded_caller = Address::random(); + let recipient = Address::random(); + let value_recipient = Address::random(); + let transfer_value = U256::from(1_000_000_000_000_000_000u128); + let calldata = format!("0x{}", alloy_primitives::hex::encode(vec![0xaa; 128])); + + let payload = serde_json::json!({ + "blockStateCalls": [{ + "stateOverrides": { + reader_addr.to_string(): { "code": BALANCE_READER_CODE }, }, - // 7: check value_recipient received exact transfer_value - { - "to": reader_addr, - "input": encode_address_word(value_recipient), - }, - // 8: check FeeVault ETH balance still unchanged - { - "to": reader_addr, - "input": encode_address_word(FEE_VAULT), - }, - // 9: call-mode token-fee MorphTx from unfunded caller (0 ETH, 0 tokens) - { - "from": unfunded_caller, - "to": recipient, - "feeTokenID": format!("{TEST_TOKEN_ID:#x}"), - "feeLimit": "0x0", - "input": calldata, - }, - // 10: call-mode token-fee MorphTx from funded wallet (must emit 0 logs & deduct 0 tokens) - { - "from": funded, - "to": recipient, - "maxFeePerGas": "0x77359400", - "maxPriorityFeePerGas": "0x3b9aca00", - "feeTokenID": format!("{TEST_TOKEN_ID:#x}"), - "feeLimit": "0xde0b6b3a7640000", - "input": calldata, - }, - // 11: check funded wallet token balance unchanged - { - "to": TEST_TOKEN, - "input": encode_balance_of(funded), - }, - // 12: check FeeVault token balance unchanged (0) - { - "to": TEST_TOKEN, - "input": encode_balance_of(FEE_VAULT), - }, - ], - }], - "validation": false, - "returnFullTransactions": true, - }); + "calls": [ + // 0: omitted `from` + { "to": recipient, "input": calldata }, + // 1: zero-balance caller; the empty envelope carries no L1 fee + { "from": unfunded_caller, "to": recipient, "input": calldata }, + // 2: funded caller, value = 0 + { "from": funded, "to": recipient, "input": calldata }, + // 3-4: check funded caller & FeeVault ETH balances unchanged + { "to": reader_addr, "input": encode_address_word(funded) }, + { "to": reader_addr, "input": encode_address_word(FEE_VAULT) }, + // 5: funded caller, value = 1 ETH transfer + { "from": funded, "to": value_recipient, "value": format!("{transfer_value:#x}") }, + // 6-8: check funded, recipient, and FeeVault balances + { "to": reader_addr, "input": encode_address_word(funded) }, + { "to": reader_addr, "input": encode_address_word(value_recipient) }, + { "to": reader_addr, "input": encode_address_word(FEE_VAULT) }, + // 9-10: unfunded & funded call-mode token-fee MorphTxs + { "from": unfunded_caller, "to": recipient, "feeTokenID": format!("{TEST_TOKEN_ID:#x}"), "feeLimit": "0x0", "input": calldata }, + { "from": funded, "to": recipient, "feeTokenID": format!("{TEST_TOKEN_ID:#x}"), "feeLimit": "0xde0b6b3a7640000", "input": calldata }, + // 11-12: check funded & FeeVault token balances unchanged + { "to": TEST_TOKEN, "input": encode_balance_of(funded) }, + { "to": TEST_TOKEN, "input": encode_balance_of(FEE_VAULT) }, + ], + }], + "validation": false, + "returnFullTransactions": true, + }); + + let blocks: Value = client + .request("eth_simulateV1", (payload, "latest")) + .await?; + let block = &blocks[0]; + let calls = block["calls"].as_array().expect("calls array"); + assert_eq!(calls.len(), 13); + for (idx, call) in calls.iter().enumerate() { + assert_eq!(call["status"].as_str(), Some("0x1"), "call {idx}: {call}"); + } - let blocks: Value = client - .request("eth_simulateV1", (payload, "latest")) - .await?; - let block = &blocks[0]; - let calls = block["calls"].as_array().expect("calls array"); - assert_eq!(calls.len(), 13); + assert_eq!( + decode_u256_word(calls[3]["returnData"].as_str().unwrap()), + initial_funded_balance + ); + assert_eq!( + decode_u256_word(calls[4]["returnData"].as_str().unwrap()), + initial_vault_balance + ); + assert_eq!( + decode_u256_word(calls[6]["returnData"].as_str().unwrap()), + initial_funded_balance - transfer_value + ); + assert_eq!( + decode_u256_word(calls[7]["returnData"].as_str().unwrap()), + transfer_value + ); + assert_eq!( + decode_u256_word(calls[8]["returnData"].as_str().unwrap()), + initial_vault_balance + ); + assert!(calls[9]["logs"].as_array().unwrap().is_empty()); + assert!(calls[10]["logs"].as_array().unwrap().is_empty()); + assert_eq!( + decode_u256_word(calls[11]["returnData"].as_str().unwrap()), + initial_token_balance + ); + assert_eq!( + decode_u256_word(calls[12]["returnData"].as_str().unwrap()), + U256::ZERO + ); + + let txs = block["transactions"] + .as_array() + .expect("transactions array"); + assert_eq!( + txs[2]["nonce"].as_str(), + Some(format!("{initial_funded_nonce:#x}").as_str()) + ); + assert_eq!( + txs[5]["nonce"].as_str(), + Some(format!("{:#x}", initial_funded_nonce + 1).as_str()) + ); + assert_eq!( + txs[10]["nonce"].as_str(), + Some(format!("{:#x}", initial_funded_nonce + 2).as_str()) + ); + + // `traceTransfers: true` with `validation: false` records only the value transfer log. + let trace_blocks: Value = client + .request( + "eth_simulateV1", + ( + serde_json::json!({ + "blockStateCalls": [{ + "calls": [{ + "from": funded, + "to": value_recipient, + "value": format!("{transfer_value:#x}"), + }], + }], + "traceTransfers": true, + "validation": false, + }), + "latest", + ), + ) + .await?; + let trace_call = &trace_blocks[0]["calls"][0]; + assert_eq!(trace_call["status"].as_str(), Some("0x1")); + assert_eq!(trace_call["logs"].as_array().unwrap().len(), 1); + + // An explicit gas price still pays the L2 fee (upstream keeps fee charging on with + // `validation: false`), but the empty envelope adds no L1 fee: the caller loses and the + // FeeVault gains exactly `gasUsed * gasPrice`. + let gas_price = 1_000_000_000u128; + let charged: Value = client + .request( + "eth_simulateV1", + ( + serde_json::json!({ + "blockStateCalls": [{ + "stateOverrides": { + reader_addr.to_string(): { "code": BALANCE_READER_CODE }, + }, + "calls": [ + { "from": funded, "to": recipient, "gasPrice": format!("{gas_price:#x}"), "input": calldata }, + { "to": reader_addr, "input": encode_address_word(funded) }, + { "to": reader_addr, "input": encode_address_word(FEE_VAULT) }, + ], + }], + "validation": false, + }), + "latest", + ), + ) + .await?; + let calls = charged[0]["calls"].as_array().expect("calls array"); + for (idx, call) in calls.iter().enumerate() { + assert_eq!(call["status"].as_str(), Some("0x1"), "call {idx}: {call}"); + } + let gas_used = u64::from_str_radix( + calls[0]["gasUsed"] + .as_str() + .unwrap() + .trim_start_matches("0x"), + 16, + )?; + let l2_fee = U256::from(gas_used) * U256::from(gas_price); + assert_eq!( + decode_u256_word(calls[1]["returnData"].as_str().unwrap()), + initial_funded_balance - l2_fee + ); + assert_eq!( + decode_u256_word(calls[2]["returnData"].as_str().unwrap()), + initial_vault_balance + l2_fee + ); - for (idx, call) in calls.iter().enumerate() { + // As upstream, a `value` or gas price the caller cannot cover fails the request. + for underfunded in [ + serde_json::json!({ "from": unfunded_caller, "to": recipient, "value": "0x3e8" }), + serde_json::json!({ "from": unfunded_caller, "to": recipient, "gasPrice": format!("{gas_price:#x}"), "input": calldata }), + ] { + let err = client + .request::( + "eth_simulateV1", + ( + serde_json::json!({ + "blockStateCalls": [{ "calls": [underfunded] }], + "validation": false, + }), + "latest", + ), + ) + .await + .expect_err("an unaffordable value or gas price must fail"); + let err_str = err.to_string(); + assert!( + err_str.contains("insufficient funds") || err_str.contains("-38014"), + "unexpected error: {err_str}" + ); + } + + // `validation: false` disables the base-fee check, so a non-zero `baseFeePerGas` block + // override must not reject a zero-fee MorphTx either. + let override_blocks: Value = client + .request( + "eth_simulateV1", + ( + serde_json::json!({ + "blockStateCalls": [{ + "blockOverrides": { "baseFeePerGas": "0x3b9aca00" }, + "calls": [{ + "from": unfunded_caller, + "to": recipient, + "feeTokenID": format!("{TEST_TOKEN_ID:#x}"), + "feeLimit": "0x0", + "input": calldata, + }], + }], + "validation": false, + }), + "latest", + ), + ) + .await?; assert_eq!( - call["status"].as_str(), + override_blocks[0]["calls"][0]["status"].as_str(), Some("0x1"), - "call {idx} must succeed under validation=false: {call}" + "baseFeePerGas override must not reject zero-fee MorphTx under validation:false: {override_blocks}" ); } - // Funded caller ETH balance unchanged after value=0 call. - assert_eq!( - decode_u256_word(calls[3]["returnData"].as_str().unwrap()), - initial_funded_balance, - "validation=false must not deduct L1/L2 fees from funded caller" - ); - // FeeVault ETH balance unchanged after value=0 call. - assert_eq!( - decode_u256_word(calls[4]["returnData"].as_str().unwrap()), - initial_vault_balance, - "validation=false must not credit phantom fees to FeeVault" - ); - // Funded caller ETH balance reduced by exact transfer_value after value>0 call. - assert_eq!( - decode_u256_word(calls[6]["returnData"].as_str().unwrap()), - initial_funded_balance - transfer_value, - "value transfer under validation=false must debit only tx.value" - ); - assert_eq!( - decode_u256_word(calls[7]["returnData"].as_str().unwrap()), - transfer_value, - "recipient must receive exact transfer_value" - ); - assert_eq!( - decode_u256_word(calls[8]["returnData"].as_str().unwrap()), - initial_vault_balance, - "FeeVault balance must remain unchanged after value transfer" - ); - - // Call-mode token-fee MorphTxs must emit zero fee Transfer logs and move zero tokens. - assert!( - calls[9]["logs"].as_array().unwrap().is_empty(), - "unfunded token-fee MorphTx must emit no logs under validation=false" - ); - assert!( - calls[10]["logs"].as_array().unwrap().is_empty(), - "funded call-mode token-fee MorphTx must emit no fee Transfer logs under validation=false" - ); - assert_eq!( - decode_u256_word(calls[11]["returnData"].as_str().unwrap()), - initial_token_balance, - "funded caller token balance must be unchanged under validation=false" - ); - assert_eq!( - decode_u256_word(calls[12]["returnData"].as_str().unwrap()), - U256::ZERO, - "FeeVault token balance must remain zero under validation=false" - ); + // ------------------------------------------------------------------------- + // 2. `validation: true` charges full placeholder-sig Curie L1 + L2 fees + // ------------------------------------------------------------------------- + { + let sender = Address::random(); + let recipient = Address::random(); + let reader_addr = Address::random(); + let calldata = Bytes::from(vec![0xab; 1024]); + let gas_limit = 50_000u64; + let max_fee_per_gas = 2_000_000_000u128; + let max_priority_fee_per_gas = 1_000_000_000u128; + + let zero_sig = alloy_primitives::Signature::new(U256::ZERO, U256::ZERO, false); + let placeholder_sig = alloy_primitives::Signature::new(U256::MAX, U256::MAX, true); + let tx_inner = alloy_consensus::TxEip1559 { + chain_id, + nonce: 0, + gas_limit, + max_fee_per_gas, + max_priority_fee_per_gas, + to: TxKind::Call(recipient), + value: U256::ZERO, + access_list: Default::default(), + input: calldata.clone(), + }; + let zero_sig_len = MorphTxEnvelope::Eip1559(tx_inner.clone().into_signed(zero_sig)) + .encoded_2718() + .len() as u128; + let encoded_len = MorphTxEnvelope::Eip1559(tx_inner.into_signed(placeholder_sig)) + .encoded_2718() + .len() as u128; + assert_eq!(encoded_len, zero_sig_len + 64); + + let commit_only_l1_fee = + U256::from((COMMIT_SCALAR * u128::from(L1_BASE_FEE)) / L1_FEE_PRECISION); + let zero_sig_l1_fee = U256::from( + (COMMIT_SCALAR * u128::from(L1_BASE_FEE) + + BLOB_SCALAR * zero_sig_len * u128::from(L1_BLOB_BASE_FEE)) + / L1_FEE_PRECISION, + ); + let full_l1_fee = U256::from( + (COMMIT_SCALAR * u128::from(L1_BASE_FEE) + + BLOB_SCALAR * encoded_len * u128::from(L1_BLOB_BASE_FEE)) + / L1_FEE_PRECISION, + ); + let l2_max_fee = U256::from(gas_limit) * U256::from(max_fee_per_gas); + let tx_call = serde_json::json!({ + "from": sender, + "to": recipient, + "gas": format!("{gas_limit:#x}"), + "maxFeePerGas": format!("{max_fee_per_gas:#x}"), + "maxPriorityFeePerGas": format!("{max_priority_fee_per_gas:#x}"), + "input": calldata.to_string(), + }); + + // Balance omitting the 64B placeholder signature L1 fee must fail. + let err = client + .request::( + "eth_simulateV1", + ( + serde_json::json!({ + "blockStateCalls": [{ + "stateOverrides": { + sender.to_string(): { "balance": format!("{:#x}", l2_max_fee + zero_sig_l1_fee) }, + }, + "calls": [tx_call], + }], + "validation": true, + }), + "latest", + ), + ) + .await + .expect_err("balance omitting 64B placeholder signature L1 fee must fail"); + let err_str = err.to_string(); + assert!(err_str.contains("insufficient funds") || err_str.contains("-38014")); + + // Exact `l2_max_fee + full_l1_fee` succeeds, debits exact fees, and keeps zero r/s/v. + let exact_budget = l2_max_fee + full_l1_fee; + let blocks: Value = client + .request( + "eth_simulateV1", + ( + serde_json::json!({ + "blockStateCalls": [{ + "stateOverrides": { + sender.to_string(): { "balance": format!("{exact_budget:#x}") }, + reader_addr.to_string(): { "code": DUAL_BALANCE_READER_CODE }, + }, + "calls": [ + tx_call, + { + "from": funded, + "to": reader_addr, + "gas": "0x186a0", + "maxFeePerGas": format!("{max_fee_per_gas:#x}"), + "maxPriorityFeePerGas": format!("{max_priority_fee_per_gas:#x}"), + "input": encode_two_address_words(sender, FEE_VAULT), + }, + ], + }], + "validation": true, + "returnFullTransactions": true, + }), + "latest", + ), + ) + .await?; + let block = &blocks[0]; + let calls = block["calls"].as_array().unwrap(); + assert_eq!(calls[0]["status"].as_str(), Some("0x1")); + assert_eq!(calls[1]["status"].as_str(), Some("0x1")); + + let txs = block["transactions"].as_array().unwrap(); + assert_eq!(txs[0]["r"].as_str(), Some("0x0")); + assert_eq!(txs[0]["s"].as_str(), Some("0x0")); + assert_eq!(txs[0]["v"].as_str(), Some("0x0")); + assert_eq!(txs[0]["yParity"].as_str(), Some("0x0")); + + let block_base_fee = u128::from_str_radix( + block["baseFeePerGas"] + .as_str() + .unwrap() + .trim_start_matches("0x"), + 16, + )?; + let gas_used = u64::from_str_radix( + calls[0]["gasUsed"] + .as_str() + .unwrap() + .trim_start_matches("0x"), + 16, + )?; + let effective_gas_price = max_fee_per_gas.min(block_base_fee + max_priority_fee_per_gas); + let expected_total_fee = + U256::from(gas_used) * U256::from(effective_gas_price) + full_l1_fee; + + let (sender_after, vault_after) = + decode_two_u256_words(calls[1]["returnData"].as_str().unwrap()); + assert_eq!(sender_after, exact_budget - expected_total_fee); + assert_eq!(vault_after, initial_vault_balance + expected_total_fee); + + // Token-fee MorphTx under `validation: true`: tight `feeLimit` fails, generous succeeds. + let token_tight_limit = U256::from(gas_limit) * U256::from(effective_gas_price) + + commit_only_l1_fee + + (full_l1_fee - commit_only_l1_fee) / U256::from(2u64); + client + .request::( + "eth_simulateV1", + ( + serde_json::json!({ + "blockStateCalls": [{ + "calls": [{ + "from": funded, + "to": recipient, + "gas": format!("{gas_limit:#x}"), + "maxFeePerGas": format!("{max_fee_per_gas:#x}"), + "maxPriorityFeePerGas": format!("{max_priority_fee_per_gas:#x}"), + "feeTokenID": format!("{TEST_TOKEN_ID:#x}"), + "feeLimit": format!("{token_tight_limit:#x}"), + "input": calldata.to_string(), + }], + }], + "validation": true, + }), + "latest", + ), + ) + .await + .expect_err("token-fee MorphTx must fail when feeLimit omits Curie blob L1 fee"); + + let morph_blocks: Value = client + .request( + "eth_simulateV1", + ( + serde_json::json!({ + "blockStateCalls": [{ + "calls": [{ + "from": funded, + "to": recipient, + "gas": format!("{gas_limit:#x}"), + "maxFeePerGas": format!("{max_fee_per_gas:#x}"), + "maxPriorityFeePerGas": format!("{max_priority_fee_per_gas:#x}"), + "feeTokenID": format!("{TEST_TOKEN_ID:#x}"), + "feeLimit": format!("{:#x}", l2_max_fee + full_l1_fee * U256::from(2u64)), + "input": calldata.to_string(), + }], + }], + "validation": true, + }), + "latest", + ), + ) + .await?; + let morph_call = &morph_blocks[0]["calls"][0]; + assert_eq!(morph_call["status"].as_str(), Some("0x1")); + assert!(has_transfer_log(morph_call)); + } - // Verify caller nonce bumped across funded ETH and MorphTx calls (indices 2, 5, 10). - let txs = block["transactions"] - .as_array() - .expect("transactions array"); - assert_eq!( - txs[2]["nonce"].as_str(), - Some(format!("{initial_funded_nonce:#x}").as_str()) - ); - assert_eq!( - txs[5]["nonce"].as_str(), - Some(format!("{:#x}", initial_funded_nonce + 1).as_str()) - ); - assert_eq!( - txs[10]["nonce"].as_str(), - Some(format!("{:#x}", initial_funded_nonce + 2).as_str()) - ); + // ------------------------------------------------------------------------- + // 3. `validation: true` with legacy `gasPrice` + `feeTokenID` executes MorphTx + // ------------------------------------------------------------------------- + { + let recipient = Address::random(); + let calldata = Bytes::from(vec![0xcd; 128]); + let blocks: Value = client + .request( + "eth_simulateV1", + ( + serde_json::json!({ + "blockStateCalls": [{ + "stateOverrides": { funded.to_string(): { "balance": "0x0" } }, + "calls": [ + { + "from": funded, + "to": recipient, + "gas": "0xc350", + "gasPrice": "0x77359400", + "feeTokenID": format!("{TEST_TOKEN_ID:#x}"), + "input": calldata.to_string(), + }, + { + "from": funded, + "to": TEST_TOKEN, + "gas": "0x186a0", + "gasPrice": "0x77359400", + "feeTokenID": format!("{TEST_TOKEN_ID:#x}"), + "input": encode_balance_of(funded), + }, + ], + }], + "validation": true, + "returnFullTransactions": true, + }), + "latest", + ), + ) + .await?; + let block = &blocks[0]; + let calls = block["calls"].as_array().unwrap(); + assert_eq!(calls[0]["status"].as_str(), Some("0x1")); + assert_eq!(calls[1]["status"].as_str(), Some("0x1")); + + let txs = block["transactions"].as_array().unwrap(); + assert_eq!(txs[0]["type"].as_str(), Some("0x7f")); + assert_eq!(txs[0]["feeTokenID"].as_str(), Some("0x1")); + assert_eq!(txs[0]["r"].as_str(), Some("0x0")); + assert_eq!(txs[0]["s"].as_str(), Some("0x0")); + assert_eq!(txs[0]["v"].as_str(), Some("0x0")); + assert_eq!(txs[0]["yParity"].as_str(), Some("0x0")); + assert!(has_transfer_log(&calls[0])); + assert!(decode_u256_word(calls[1]["returnData"].as_str().unwrap()) < initial_token_balance); + } - // Also exercise the `traceTransfers: true` (`TransferInspector`) branch under - // `validation: false`: a 1 ETH transfer emits exactly 1 synthetic ETH transfer - // log (to `value_recipient`) and zero FeeVault transfer logs. - let trace_payload = serde_json::json!({ - "blockStateCalls": [{ - "calls": [{ - "from": funded, - "to": value_recipient, - "value": format!("{transfer_value:#x}"), - "maxFeePerGas": "0x77359400", - "maxPriorityFeePerGas": "0x3b9aca00", - }], - }], - "traceTransfers": true, - "validation": false, - }); - let trace_blocks: Value = client - .request("eth_simulateV1", (trace_payload, "latest")) - .await?; - let trace_call = &trace_blocks[0]["calls"][0]; - assert_eq!(trace_call["status"].as_str(), Some("0x1")); - let trace_logs = trace_call["logs"].as_array().expect("trace logs array"); - assert_eq!( - trace_logs.len(), - 1, - "traceTransfers with validation=false must record only the value transfer, not fee transfers: {trace_logs:?}" - ); + // ------------------------------------------------------------------------- + // 4. `eth_fillTransaction` keeps geth's `toTransaction` rule: legacy `gasPrice` builds a + // legacy transaction even with `feeTokenID`, so the simulate-only normalization above + // must not reach it. + // ------------------------------------------------------------------------- + { + let filled: Value = client + .request( + "eth_fillTransaction", + (serde_json::json!({ + "from": funded, + "to": Address::random(), + "gas": "0x5208", + "gasPrice": "0x77359400", + "feeTokenID": format!("{TEST_TOKEN_ID:#x}"), + }),), + ) + .await?; + let tx = &filled["tx"]; + assert!( + matches!(tx["type"].as_str(), Some("0x0") | None), + "legacy gasPrice must fill a legacy transaction: {filled}" + ); + assert!(tx.get("feeTokenID").is_none_or(Value::is_null), "{filled}"); + } Ok(()) } -/// `eth_simulateV1` with `validation: true` must wrap simulated transactions with -/// their real EIP-2718 encoding so post-Curie `commit + blob` L1 fees are charged -/// and validated accurately (for both standard ETH txs and token-fee MorphTxs). +/// `eth_call` and `eth_callMany` must respect `--rpc.gascap` even when +/// `blockOverrides.gasLimit = u64::MAX` is combined with an omitted `gas` field +/// and a non-zero `gasPrice` (both Morph token-fee and standard ETH callers). #[tokio::test(flavor = "multi_thread")] -async fn simulate_v1_validation_true_charges_full_curie_l1_and_l2_fees() -> eyre::Result<()> { +async fn eth_call_and_call_many_respect_rpc_gas_cap_under_block_gas_limit_override() +-> eyre::Result<()> { reth_tracing::init_test_tracing(); - const L1_ORACLE: Address = - alloy_primitives::address!("530000000000000000000000000000000000000f"); - const FEE_VAULT: Address = - alloy_primitives::address!("530000000000000000000000000000000000000a"); - const L1_BASE_FEE: u64 = 10_000_000_000; // 10 gwei - const L1_BLOB_BASE_FEE: u64 = 10_000_000_000; // 10 gwei - // Matches `tests/assets/test-genesis.json` slots 7 & 8. - const COMMIT_SCALAR: u128 = 0x35ba5d7b55; - const BLOB_SCALAR: u128 = 0x18e38a4c; - const L1_FEE_PRECISION: u128 = 1_000_000_000; - // Runtime bytecode: return `(BALANCE(calldataload(0)), BALANCE(calldataload(32)))` (64 bytes). - const DUAL_BALANCE_READER_CODE: &str = "0x600035316000526020353160205260406000f3"; + // Default `--rpc.gascap` in reth. + const DEFAULT_RPC_GAS_CAP: u64 = 50_000_000; + // `GAS; PUSH1 0; MSTORE; PUSH1 0x20; PUSH1 0; RETURN` — returns remaining EVM gas. + const GAS_PROBE_CODE: &str = "0x5a60005260206000f3"; + // `JUMPDEST; PUSH1 0; JUMP` — burns all available gas until OutOfGas. + const INFINITE_LOOP_CODE: &str = "0x5b600056"; + + let decode_gas_seen = |output: &Bytes| -> u64 { + assert_eq!(output.len(), 32, "GAS probe must return 32-byte uint256"); + let val = U256::from_be_slice(output); + u64::try_from(val).expect("gas_seen must fit in u64") + }; - let (mut nodes, wallet) = TestNodeBuilder::new() - .with_account_storage(L1_ORACLE, U256::from(1u64), U256::from(L1_BASE_FEE)) - .with_account_storage(L1_ORACLE, U256::from(6u64), U256::from(L1_BLOB_BASE_FEE)) - .build() - .await?; + let (mut nodes, wallet) = TestNodeBuilder::new().build().await?; let mut node = nodes.pop().unwrap(); - let chain_id = wallet.chain_id; - let funded_wallet = wallet.inner.address(); + advance_chain(1, &mut node, wallet_to_arc(wallet)).await?; let client = node .rpc_client() .ok_or_else(|| eyre::eyre!("HTTP RPC client not available"))?; - let initial_vault_balance = node - .inner - .provider - .latest()? - .basic_account(&FEE_VAULT)? - .map(|a| a.balance) - .unwrap_or_default(); + let probe_contract = Address::random(); + let loop_contract = Address::random(); + let zero_eth_sender = Address::random(); + let rich_eth_sender = Address::random(); + let fee_token_id = format!("{TEST_TOKEN_ID:#x}"); + let block_override_max_gas = serde_json::json!({ + "gasLimit": "0xffffffffffffffff", + }); - let sender = Address::random(); - let recipient = Address::random(); - let reader_addr = Address::random(); - let calldata = Bytes::from(vec![0xab; 1024]); - let gas_limit = 50_000u64; - let max_fee_per_gas = 2_000_000_000u128; // 2 gwei - let max_priority_fee_per_gas = 1_000_000_000u128; // 1 gwei - - // Build the exact simulated EIP-1559 envelope (`Signature(0, 0, false)`) that - // `resolve_transaction` / `TryIntoSimTx` produces so we know its exact EIP-2718 length. - let sim_sig = alloy_primitives::Signature::new(U256::ZERO, U256::ZERO, false); - let expected_eth_envelope = MorphTxEnvelope::Eip1559( - alloy_consensus::TxEip1559 { - chain_id, - nonce: 0, - gas_limit, - max_fee_per_gas, - max_priority_fee_per_gas, - to: TxKind::Call(recipient), - value: U256::ZERO, - access_list: Default::default(), - input: calldata.clone(), - } - .into_signed(sim_sig), + // (a) Token-fee `eth_call` with omitted `gas`, non-zero `gasPrice`, and + // `blockOverrides.gasLimit = u64::MAX`. + let token_call = serde_json::json!({ + "from": zero_eth_sender, + "to": probe_contract, + "gasPrice": "0x1", + "feeTokenID": fee_token_id, + }); + let token_state_overrides = serde_json::json!({ + probe_contract.to_string(): { + "code": GAS_PROBE_CODE, + }, + }); + let token_out: Bytes = client + .request( + "eth_call", + ( + token_call.clone(), + "latest", + token_state_overrides, + block_override_max_gas.clone(), + ), + ) + .await?; + let token_gas_seen = decode_gas_seen(&token_out); + assert!( + token_gas_seen > 0 && token_gas_seen <= DEFAULT_RPC_GAS_CAP, + "token-fee eth_call gas_seen ({token_gas_seen}) must be within (0, {DEFAULT_RPC_GAS_CAP}]" ); - let encoded_len = expected_eth_envelope.encoded_2718().len() as u128; - let commit_only_l1_fee = - U256::from((COMMIT_SCALAR * u128::from(L1_BASE_FEE)) / L1_FEE_PRECISION); - let full_l1_fee = U256::from( - (COMMIT_SCALAR * u128::from(L1_BASE_FEE) - + BLOB_SCALAR * encoded_len * u128::from(L1_BLOB_BASE_FEE)) - / L1_FEE_PRECISION, + assert!( + token_gas_seen > 49_000_000, + "expected gas cap ~{DEFAULT_RPC_GAS_CAP} under max block gas override, got {token_gas_seen}" + ); + + // (b) ETH-mode `eth_call` with huge state-overridden balance, omitted `gas`, + // non-zero `gasPrice`, and `blockOverrides.gasLimit = u64::MAX`. + let eth_call = serde_json::json!({ + "from": rich_eth_sender, + "to": probe_contract, + "gasPrice": "0x1", + }); + let combined_state_overrides = serde_json::json!({ + probe_contract.to_string(): { + "code": GAS_PROBE_CODE, + }, + rich_eth_sender.to_string(): { + "balance": "0xffffffffffffffffffffffff", + }, + }); + let eth_out: Bytes = client + .request( + "eth_call", + ( + eth_call.clone(), + "latest", + combined_state_overrides.clone(), + block_override_max_gas.clone(), + ), + ) + .await?; + let eth_gas_seen = decode_gas_seen(ð_out); + assert!( + eth_gas_seen > 0 && eth_gas_seen <= DEFAULT_RPC_GAS_CAP, + "ETH eth_call gas_seen ({eth_gas_seen}) must be within (0, {DEFAULT_RPC_GAS_CAP}]" ); assert!( - full_l1_fee > commit_only_l1_fee * U256::from(2u64), - "calldata blob fee must significantly exceed commit-only fee" + eth_gas_seen > 49_000_000, + "expected gas cap ~{DEFAULT_RPC_GAS_CAP} under max block gas override, got {eth_gas_seen}" ); - let l2_max_fee = U256::from(gas_limit) * U256::from(max_fee_per_gas); - let tx_call = serde_json::json!({ - "from": sender, - "to": recipient, - "gas": format!("{gas_limit:#x}"), - "maxFeePerGas": format!("{max_fee_per_gas:#x}"), - "maxPriorityFeePerGas": format!("{max_priority_fee_per_gas:#x}"), - "input": calldata.to_string(), + // (c) `eth_callMany` with `blockOverride.gasLimit = u64::MAX` covering both + // token-fee and ETH calls in a single bundle. + let bundles = serde_json::json!([{ + "transactions": [token_call, eth_call], + "blockOverride": block_override_max_gas, + }]); + let state_context = serde_json::json!({ + "blockNumber": "latest", }); + let call_many_res: Value = client + .request( + "eth_callMany", + (bundles, state_context, combined_state_overrides), + ) + .await?; + let bundle_results = call_many_res + .as_array() + .and_then(|bundles| bundles.first()) + .and_then(Value::as_array) + .expect("eth_callMany must return one bundle with two results"); + assert_eq!(bundle_results.len(), 2); + for (idx, item) in bundle_results.iter().enumerate() { + assert!( + item.get("error").is_none() || item["error"].is_null(), + "eth_callMany tx {idx} unexpectedly failed: {item}" + ); + let value_hex = item["value"] + .as_str() + .unwrap_or_else(|| panic!("eth_callMany tx {idx} missing value: {item}")); + let output: Bytes = value_hex.parse()?; + let gas_seen = decode_gas_seen(&output); + assert!( + gas_seen > 0 && gas_seen <= DEFAULT_RPC_GAS_CAP, + "eth_callMany tx {idx} gas_seen ({gas_seen}) must be within (0, {DEFAULT_RPC_GAS_CAP}]" + ); + assert!( + gas_seen > 49_000_000, + "eth_callMany tx {idx} expected gas cap ~{DEFAULT_RPC_GAS_CAP}, got {gas_seen}" + ); + } - // (1) Balance covers L2 + commit-only L1 fee (+ half the blob fee), NOT full Curie L1 fee: - // must fail with insufficient funds (-38014). Under the old empty-RLP bug this passed! - let insufficient_balance = - l2_max_fee + commit_only_l1_fee + (full_l1_fee - commit_only_l1_fee) / U256::from(2u64); - let fail_payload = serde_json::json!({ - "blockStateCalls": [{ - "stateOverrides": { - sender.to_string(): { - "balance": format!("{insufficient_balance:#x}"), - }, - }, - "calls": [tx_call], - }], - "validation": true, + // (d) Infinite-loop bytecode with token-fee `eth_call` + omitted `gas` + + // non-zero `gasPrice` + `blockOverrides.gasLimit = u64::MAX` must hit + // OutOfGas promptly instead of running uncapped. + let loop_call = serde_json::json!({ + "from": zero_eth_sender, + "to": loop_contract, + "gasPrice": "0x1", + "feeTokenID": format!("{TEST_TOKEN_ID:#x}"), }); - let err = client - .request::("eth_simulateV1", (fail_payload, "latest")) - .await - .expect_err("validation=true must reject when balance omits Curie blob L1 fee"); - let err_str = err.to_string(); + let loop_state_overrides = serde_json::json!({ + loop_contract.to_string(): { + "code": INFINITE_LOOP_CODE, + }, + }); + let loop_res: Result = tokio::time::timeout( + std::time::Duration::from_secs(30), + client.request( + "eth_call", + ( + loop_call, + "latest", + loop_state_overrides, + block_override_max_gas, + ), + ), + ) + .await + .expect("infinite-loop eth_call must terminate promptly under --rpc.gascap"); + let err_str = loop_res + .expect_err("infinite-loop eth_call must halt with OutOfGas") + .to_string() + .to_lowercase(); assert!( - err_str.contains("insufficient funds") || err_str.contains("-38014"), - "expected insufficient funds error, got: {err_str}" + err_str.contains("out of gas"), + "expected OutOfGas error, got: {err_str}" ); - // (2) Balance covers exact `l2_max_fee + full_l1_fee`: must succeed and deduct exact - // `l2_used_fee + full_l1_fee` from sender and credit the same amount to FeeVault. - let exact_budget = l2_max_fee + full_l1_fee; - let pass_payload = serde_json::json!({ - "blockStateCalls": [{ - "stateOverrides": { - sender.to_string(): { - "balance": format!("{exact_budget:#x}"), - }, - reader_addr.to_string(): { - "code": DUAL_BALANCE_READER_CODE, - }, - }, - "calls": [ - tx_call, - // Executed immediately after Call 0 commits and BEFORE Call 1's own - // `reward_beneficiary` runs, so it observes exact post-Call-0 balances - // of both `sender` and `FEE_VAULT`. - { - "from": funded_wallet, - "to": reader_addr, - "gas": "0x186a0", - "maxFeePerGas": format!("{max_fee_per_gas:#x}"), - "maxPriorityFeePerGas": format!("{max_priority_fee_per_gas:#x}"), - "input": encode_two_address_words(sender, FEE_VAULT), - }, - ], - }], - "validation": true, + Ok(()) +} + +/// Builds runtime bytecode that reverts when `GAS < min_gas` and `STOP`s otherwise: +/// `PUSH8 ; GAS; LT; PUSH1 0x0f; JUMPI; STOP; JUMPDEST; PUSH1 0; PUSH1 0; REVERT`. +fn gas_threshold_contract_code(min_gas: u64) -> String { + let mut code = Vec::with_capacity(21); + code.push(0x67); // PUSH8 + code.extend_from_slice(&min_gas.to_be_bytes()); + code.extend_from_slice(&[ + 0x5a, // GAS + 0x10, // LT (gas_remaining < min_gas) + 0x60, 0x0f, // PUSH1 0x0f + 0x57, // JUMPI + 0x00, // STOP + 0x5b, // JUMPDEST (0x0f) + 0x60, 0x00, // PUSH1 0 + 0x60, 0x00, // PUSH1 0 + 0xfd, // REVERT + ]); + format!("0x{}", alloy_primitives::hex::encode(code)) +} + +/// Builds `stateOverrides` registering an active 1:1 slot-mode fee token (`token_id`) +/// at `token_addr` in `L2TokenRegistry` and funding `holder` with a large balance at slot `0`. +fn slot_mode_token_state_overrides( + token_id: u16, + token_addr: Address, + holder: Address, +) -> (String, Value, String, Value) { + const L2_TOKEN_REGISTRY: Address = + alloy_primitives::address!("5300000000000000000000000000000000000021"); + + let mapping_slot = |base_slot: u64, key: &[u8; 32]| -> U256 { + let mut preimage = [0u8; 64]; + preimage[..32].copy_from_slice(key); + preimage[32..].copy_from_slice(&U256::from(base_slot).to_be_bytes::<32>()); + U256::from_be_bytes(alloy_primitives::keccak256(preimage).0) + }; + + let mut token_key = [0u8; 32]; + token_key[30..32].copy_from_slice(&token_id.to_be_bytes()); + let base = mapping_slot(151, &token_key); + let price_slot = mapping_slot(153, &token_key); + + let mut addr_word = [0u8; 32]; + addr_word[12..32].copy_from_slice(token_addr.as_slice()); + + let mut status_word = [0u8; 32]; + status_word[30] = 18; // decimals + status_word[31] = 1; // isActive = true + + let mut holder_key = [0u8; 32]; + holder_key[12..32].copy_from_slice(holder.as_slice()); + let holder_balance_slot = mapping_slot(0, &holder_key); + let b256_hex = |v: U256| B256::from(v.to_be_bytes::<32>()).to_string(); + + let registry_override = serde_json::json!({ + "stateDiff": { + b256_hex(base): B256::from(addr_word).to_string(), + // `balanceSlot + 1 = 1` -> slot-mode at storage slot 0. + b256_hex(base + U256::from(1u64)): b256_hex(U256::from(1u64)), + b256_hex(base + U256::from(2u64)): B256::from(status_word).to_string(), + b256_hex(base + U256::from(3u64)): b256_hex(U256::from(1u64)), + b256_hex(price_slot): b256_hex(U256::from(1u64)), + } + }); + let token_override = serde_json::json!({ + "stateDiff": { + b256_hex(holder_balance_slot): b256_hex(U256::from(u128::MAX)), + } }); - let blocks: Value = client - .request("eth_simulateV1", (pass_payload, "latest")) + + ( + L2_TOKEN_REGISTRY.to_string(), + registry_override, + token_addr.to_string(), + token_override, + ) +} + +/// Builds the 4 core `eth_estimateGas` caller modes against `target`: +/// zero-priced, ETH-paid, slot-mode fee token, and call-mode fee token. +fn estimate_gas_caller_modes( + target: Address, + zero_eth_slot_sender: Address, + rich_eth_sender: Address, + call_token_holder: Address, + slot_token_id: u16, +) -> Vec<(&'static str, Value)> { + vec![ + ( + "zero-price", + serde_json::json!({ "from": zero_eth_slot_sender, "to": target }), + ), + ( + "eth-paid", + serde_json::json!({ "from": rich_eth_sender, "to": target, "gasPrice": "0x1" }), + ), + ( + "slot-token-paid", + serde_json::json!({ + "from": zero_eth_slot_sender, + "to": target, + "gasPrice": "0x1", + "feeTokenID": format!("{slot_token_id:#x}"), + }), + ), + ( + "call-token-paid", + serde_json::json!({ + "from": call_token_holder, + "to": target, + "gasPrice": "0x1", + "feeTokenID": format!("{TEST_TOKEN_ID:#x}"), + "feeLimit": "0xffffffffffffffffffffffff", + }), + ), + ] +} + +/// Launches a single Morph test node with a custom `--rpc.gascap` (`0` = unlimited). +async fn launch_node_with_rpc_gas_cap( + gas_cap: u64, +) -> eyre::Result<(MorphTestNode, reth_e2e_test_utils::wallet::Wallet)> { + let genesis: alloy_genesis::Genesis = + serde_json::from_str(include_str!("../assets/test-genesis.json"))?; + let chain_spec = std::sync::Arc::new(morph_chainspec::MorphChainSpec::from_genesis(genesis)); + let (mut nodes, wallet) = + reth_e2e_test_utils::E2ETestSetupBuilder::::new_with_attributes_generator( + 1, + chain_spec, + morph_node::test_utils::morph_payload_attributes, + ) + .with_node_config_modifier(move |mut config| { + config.txpool.minimal_protocol_basefee = morph_chainspec::MORPH_BASE_FEE; + config.rpc.rpc_gas_cap = gas_cap; + config + }) + .build() .await?; - let block = &blocks[0]; - let calls = block["calls"].as_array().expect("calls array"); - assert_eq!(calls[0]["status"].as_str(), Some("0x1")); - assert_eq!(calls[1]["status"].as_str(), Some("0x1")); + Ok((nodes.pop().unwrap(), wallet)) +} - let block_base_fee = u128::from_str_radix( - block["baseFeePerGas"] - .as_str() - .unwrap() - .trim_start_matches("0x"), - 16, - )?; - let gas_used = u64::from_str_radix( - calls[0]["gasUsed"] - .as_str() - .unwrap() - .trim_start_matches("0x"), - 16, - )?; - let effective_gas_price = max_fee_per_gas.min(block_base_fee + max_priority_fee_per_gas); - let expected_total_fee = U256::from(gas_used) * U256::from(effective_gas_price) + full_l1_fee; +/// `eth_estimateGas` must: +/// 1. Honor `blockOverrides.gasLimit` values above the current header's `gas_limit` +/// (30M) rather than clamping back to `header.gas_limit()` (`[MR-12]`). +/// 2. Clamp estimation to `--rpc.gascap` (`call_gas_limit`, default 50M) across +/// zero-priced, explicit `gas`, ETH-paid, slot-mode token, and call-mode token paths (`[MR-10]`). +#[tokio::test(flavor = "multi_thread")] +async fn estimate_gas_respects_block_gas_limit_override_above_header_and_rpc_gas_cap() +-> eyre::Result<()> { + reth_tracing::init_test_tracing(); - let (sender_balance_after, vault_balance_after) = - decode_two_u256_words(calls[1]["returnData"].as_str().unwrap()); - assert_eq!( - sender_balance_after, - exact_budget - expected_total_fee, - "sender must be charged exact L2 execution fee + full Curie (commit + blob) L1 fee" + const SLOT_TOKEN_ID: u16 = 2; + + let (mut nodes, wallet) = TestNodeBuilder::new().build().await?; + let mut node = nodes.pop().unwrap(); + let call_token_holder = wallet.inner.address(); + advance_chain(1, &mut node, wallet_to_arc(wallet)).await?; + + let client = node + .rpc_client() + .ok_or_else(|| eyre::eyre!("HTTP RPC client not available"))?; + + let contract_35m = Address::random(); + let contract_60m = Address::random(); + let slot_token_addr = Address::random(); + let zero_eth_slot_sender = Address::random(); + let rich_eth_sender = Address::random(); + + let (reg_key, reg_val, tok_key, tok_val) = + slot_mode_token_state_overrides(SLOT_TOKEN_ID, slot_token_addr, zero_eth_slot_sender); + + let mut overrides_map = serde_json::Map::new(); + overrides_map.insert( + contract_35m.to_string(), + serde_json::json!({ "code": gas_threshold_contract_code(35_000_000) }), ); - assert_eq!( - vault_balance_after, - initial_vault_balance + expected_total_fee, - "FeeVault must receive exact L2 execution fee + full Curie (commit + blob) L1 fee" + overrides_map.insert( + contract_60m.to_string(), + serde_json::json!({ "code": gas_threshold_contract_code(60_000_000) }), + ); + overrides_map.insert( + rich_eth_sender.to_string(), + serde_json::json!({ "balance": "0xffffffffffffffffffffffff" }), ); + overrides_map.insert(reg_key, reg_val); + overrides_map.insert(tok_key, tok_val); + let state_overrides = Value::Object(overrides_map); - // (3) Token-fee MorphTx under `validation: true`: a `feeLimit` that only covers - // L2 (`gas_limit * effective_gas_price`) + commit-only L1 fee (+ half the blob fee) - // must fail, while covering full Curie L1 + L2 succeeds and emits the call-mode - // ERC-20 `Transfer` fee log(s). (Genesis token ID 1 has 1:1 price_ratio == scale == 1e18.) - let l2_effective_max_fee = U256::from(gas_limit) * U256::from(effective_gas_price); - let token_tight_limit = l2_effective_max_fee - + commit_only_l1_fee - + (full_l1_fee - commit_only_l1_fee) / U256::from(2u64); - let morph_fail_payload = serde_json::json!({ - "blockStateCalls": [{ - "calls": [{ - "from": funded_wallet, - "to": recipient, - "gas": format!("{gas_limit:#x}"), - "maxFeePerGas": format!("{max_fee_per_gas:#x}"), - "maxPriorityFeePerGas": format!("{max_priority_fee_per_gas:#x}"), - "feeTokenID": format!("{TEST_TOKEN_ID:#x}"), - "feeLimit": format!("{token_tight_limit:#x}"), - "input": calldata.to_string(), - }], - }], - "validation": true, - }); + // 1. Without `blockOverrides.gasLimit`, the 30M header ceiling rejects a 35M contract. client - .request::("eth_simulateV1", (morph_fail_payload, "latest")) + .request::( + "eth_estimateGas", + ( + serde_json::json!({ "from": zero_eth_slot_sender, "to": contract_35m }), + "latest", + state_overrides.clone(), + ), + ) .await - .expect_err("token-fee MorphTx must fail under validation=true when feeLimit omits Curie blob L1 fee"); - - let token_generous_limit = l2_max_fee + full_l1_fee * U256::from(2u64); - let morph_pass_payload = serde_json::json!({ - "blockStateCalls": [{ - "calls": [{ - "from": funded_wallet, - "to": recipient, - "gas": format!("{gas_limit:#x}"), - "maxFeePerGas": format!("{max_fee_per_gas:#x}"), - "maxPriorityFeePerGas": format!("{max_priority_fee_per_gas:#x}"), - "feeTokenID": format!("{TEST_TOKEN_ID:#x}"), - "feeLimit": format!("{token_generous_limit:#x}"), - "input": calldata.to_string(), - }], - }], - "validation": true, + .expect_err("35M requirement must fail under 30M header gas limit without override"); + + // 2. `[MR-12]`: `blockOverrides.gasLimit = 45M` (> 30M header, < 50M `--rpc.gascap`) succeeds + // across all caller modes on `"latest"` and `"pending"`, while 20M tightens the ceiling. + let block_override_45m = serde_json::json!({ + "gasLimit": format!("{:#x}", 45_000_000u64), }); - let morph_blocks: Value = client - .request("eth_simulateV1", (morph_pass_payload, "latest")) + for (label, req) in estimate_gas_caller_modes( + contract_35m, + zero_eth_slot_sender, + rich_eth_sender, + call_token_holder, + SLOT_TOKEN_ID, + ) { + let est: U256 = client + .request( + "eth_estimateGas", + ( + req, + "latest", + state_overrides.clone(), + block_override_45m.clone(), + ), + ) + .await + .unwrap_or_else(|e| panic!("{label}: expected 45M blockOverride to succeed, got {e}")); + let est_u64 = u64::try_from(est)?; + assert!( + est_u64 > 35_000_000 && est_u64 <= 45_000_000, + "{label}: expected estimate in (35M, 45M], got {est_u64}" + ); + } + + let pending_est: U256 = client + .request( + "eth_estimateGas", + ( + serde_json::json!({ "from": zero_eth_slot_sender, "to": contract_35m }), + "pending", + state_overrides.clone(), + block_override_45m, + ), + ) .await?; - let morph_call = &morph_blocks[0]["calls"][0]; - assert_eq!(morph_call["status"].as_str(), Some("0x1")); - let transfer_topic = "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"; - let logs = morph_call["logs"].as_array().expect("logs array"); + let pending_est_u64 = u64::try_from(pending_est)?; assert!( - logs.iter().any(|log| { - log["topics"] - .as_array() - .and_then(|t| t.first()) - .and_then(Value::as_str) - == Some(transfer_topic) - }), - "validated call-mode token-fee MorphTx must emit ERC-20 Transfer fee logs: {logs:?}" + pending_est_u64 > 35_000_000 && pending_est_u64 <= 45_000_000, + "pending block estimate expected in (35M, 45M], got {pending_est_u64}" ); + client + .request::( + "eth_estimateGas", + ( + serde_json::json!({ "from": zero_eth_slot_sender, "to": contract_35m }), + "latest", + state_overrides.clone(), + serde_json::json!({ "gasLimit": format!("{:#x}", 20_000_000u64) }), + ), + ) + .await + .expect_err("lower 20M blockOverrides.gasLimit must still reject 35M requirement"); + + // 3. `[MR-10]`: With `blockOverrides.gasLimit = u64::MAX`, `--rpc.gascap` (50M) still + // clamps all paths, so a 60M contract fails across every mode (including explicit `gas` + // and call-mode token without `feeLimit`). + let block_override_max = serde_json::json!({ "gasLimit": "0xffffffffffffffff" }); + let mut capped_60m_requests = estimate_gas_caller_modes( + contract_60m, + zero_eth_slot_sender, + rich_eth_sender, + call_token_holder, + SLOT_TOKEN_ID, + ); + capped_60m_requests.push(( + "explicit-gas-80m", + serde_json::json!({ + "from": zero_eth_slot_sender, + "to": contract_60m, + "gas": format!("{:#x}", 80_000_000u64), + }), + )); + capped_60m_requests.push(( + "call-token-without-fee-limit", + serde_json::json!({ + "from": call_token_holder, + "to": contract_60m, + "gasPrice": "0x1", + "feeTokenID": format!("{TEST_TOKEN_ID:#x}"), + }), + )); + for (label, req) in capped_60m_requests { + let err = client + .request::( + "eth_estimateGas", + ( + req, + "latest", + state_overrides.clone(), + block_override_max.clone(), + ), + ) + .await + .expect_err(&format!( + "{label}: 60M requirement must be rejected by 50M --rpc.gascap" + )); + let err_str = err.to_string().to_lowercase(); + assert!( + err_str.contains("execution reverted") || err_str.contains("gas required exceeds"), + "{label}: unexpected error: {err_str}" + ); + } + + Ok(()) +} + +/// Custom `--rpc.gascap` configurations in `eth_estimateGas`: +/// - `--rpc.gascap = 500_000` (< 30M header) clamps all caller modes and diagnostic retries. +/// - `--rpc.gascap = 10_000` (< 21,000 `MIN_TRANSACTION_GAS`) rejects basic transfers. +/// - `--rpc.gascap = 0` disables the RPC gas cap (`0` = unlimited). +#[tokio::test(flavor = "multi_thread")] +async fn estimate_gas_custom_rpc_gas_cap_clamps_below_header_and_zero_disables_cap() +-> eyre::Result<()> { + reth_tracing::init_test_tracing(); + + const SLOT_TOKEN_ID: u16 = 2; + const INFINITE_LOOP_CODE: &str = "0x5b600056"; + + // (a) `--rpc.gascap = 500_000` (< 30M header gas limit, without any blockOverrides). + { + let (mut node, wallet) = launch_node_with_rpc_gas_cap(500_000).await?; + let call_token_holder = wallet.inner.address(); + advance_chain(1, &mut node, wallet_to_arc(wallet)).await?; + let client = node + .rpc_client() + .ok_or_else(|| eyre::eyre!("HTTP RPC client not available"))?; + + let ok_contract = Address::random(); + let loop_contract = Address::random(); + let retry_loop_contract = Address::random(); + let slot_token_addr = Address::random(); + let zero_eth_slot_sender = Address::random(); + let rich_eth_sender = Address::random(); + + // Reverts when `GAS < 200_000` (triggering `map_out_of_gas_err` when `gas = 100_000`), + // and enters an infinite loop when `GAS >= 200_000` so the diagnostic retry would hang if + // `max_gas_limit` were left at `blockOverrides.gasLimit = u64::MAX` instead of 500k. + let mut retry_loop_bytes = Vec::with_capacity(24); + retry_loop_bytes.push(0x67); // PUSH8 + retry_loop_bytes.extend_from_slice(&200_000u64.to_be_bytes()); + retry_loop_bytes.extend_from_slice(&[ + 0x5a, 0x10, 0x60, 0x12, 0x57, // GAS < 200k -> jump to revert (0x12) + 0x5b, 0x60, 0x0e, 0x56, // 0x0e: infinite loop + 0x5b, 0x60, 0x00, 0x60, 0x00, 0xfd, // 0x12: revert + ]); + + let (reg_key, reg_val, tok_key, tok_val) = + slot_mode_token_state_overrides(SLOT_TOKEN_ID, slot_token_addr, zero_eth_slot_sender); + + let mut overrides_map = serde_json::Map::new(); + overrides_map.insert( + ok_contract.to_string(), + serde_json::json!({ "code": gas_threshold_contract_code(300_000) }), + ); + overrides_map.insert( + loop_contract.to_string(), + serde_json::json!({ "code": INFINITE_LOOP_CODE }), + ); + overrides_map.insert( + retry_loop_contract.to_string(), + serde_json::json!({ "code": format!("0x{}", alloy_primitives::hex::encode(retry_loop_bytes)) }), + ); + overrides_map.insert( + rich_eth_sender.to_string(), + serde_json::json!({ "balance": "0xffffffffffffffffffffffff" }), + ); + overrides_map.insert(reg_key, reg_val); + overrides_map.insert(tok_key, tok_val); + let state_overrides = Value::Object(overrides_map); + + let est: U256 = client + .request( + "eth_estimateGas", + ( + serde_json::json!({ "from": zero_eth_slot_sender, "to": ok_contract }), + "latest", + state_overrides.clone(), + ), + ) + .await?; + let est_u64 = u64::try_from(est)?; + assert!( + est_u64 > 300_000 && est_u64 <= 500_000, + "expected estimate in (300k, 500k], got {est_u64}" + ); + + let retry_res: Result = tokio::time::timeout( + std::time::Duration::from_secs(10), + client.request( + "eth_estimateGas", + ( + serde_json::json!({ + "from": zero_eth_slot_sender, + "to": retry_loop_contract, + "gas": format!("{:#x}", 100_000u64), + }), + "latest", + state_overrides.clone(), + serde_json::json!({ "gasLimit": "0xffffffffffffffff" }), + ), + ), + ) + .await + .expect("diagnostic retry must terminate promptly under --rpc.gascap = 500k"); + let retry_err = retry_res + .expect_err("diagnostic retry loop must fail with OutOfGas") + .to_string() + .to_lowercase(); + assert!( + retry_err.contains("out of gas") || retry_err.contains("100000"), + "expected OutOfGas error for diagnostic retry, got: {retry_err}" + ); + + for (label, req) in estimate_gas_caller_modes( + loop_contract, + zero_eth_slot_sender, + rich_eth_sender, + call_token_holder, + SLOT_TOKEN_ID, + ) { + let err_str = client + .request::("eth_estimateGas", (req, "latest", state_overrides.clone())) + .await + .expect_err(&format!("{label}: infinite loop must fail at 500k cap")) + .to_string(); + assert!( + err_str.contains("500000"), + "{label}: expected OutOfGas at exact 500,000 gas cap, got: {err_str}" + ); + } + } + + // (b) `--rpc.gascap = 10_000` (< 21,000) must not short-circuit basic transfers to 21,000. + { + let (mut node, wallet) = launch_node_with_rpc_gas_cap(10_000).await?; + let sender = wallet.inner.address(); + advance_chain(1, &mut node, wallet_to_arc(wallet)).await?; + let client = node + .rpc_client() + .ok_or_else(|| eyre::eyre!("HTTP RPC client not available"))?; + + let err_str = client + .request::( + "eth_estimateGas", + (serde_json::json!({ + "from": sender, + "to": Address::random(), + "value": "0x0", + }),), + ) + .await + .expect_err("basic transfer must fail when --rpc.gascap < 21,000") + .to_string(); + assert!( + err_str.contains("gas required exceeds allowance (10000)"), + "expected allowance error for 10,000 gas cap, got: {err_str}" + ); + } + + // (c) `rpc_gas_cap = 0` disables the RPC gas cap across all caller modes. + { + let (mut node, wallet) = launch_node_with_rpc_gas_cap(0).await?; + let call_token_holder = wallet.inner.address(); + advance_chain(1, &mut node, wallet_to_arc(wallet)).await?; + let client = node + .rpc_client() + .ok_or_else(|| eyre::eyre!("HTTP RPC client not available"))?; + + let contract_60m = Address::random(); + let slot_token_addr = Address::random(); + let zero_eth_slot_sender = Address::random(); + let rich_eth_sender = Address::random(); + + let (reg_key, reg_val, tok_key, tok_val) = + slot_mode_token_state_overrides(SLOT_TOKEN_ID, slot_token_addr, zero_eth_slot_sender); + + let mut overrides_map = serde_json::Map::new(); + overrides_map.insert( + contract_60m.to_string(), + serde_json::json!({ "code": gas_threshold_contract_code(60_000_000) }), + ); + overrides_map.insert( + rich_eth_sender.to_string(), + serde_json::json!({ "balance": "0xffffffffffffffffffffffff" }), + ); + overrides_map.insert(reg_key, reg_val); + overrides_map.insert(tok_key, tok_val); + let state_overrides = Value::Object(overrides_map); + let block_override_100m = serde_json::json!({ + "gasLimit": format!("{:#x}", 100_000_000u64), + }); + + for (label, req) in estimate_gas_caller_modes( + contract_60m, + zero_eth_slot_sender, + rich_eth_sender, + call_token_holder, + SLOT_TOKEN_ID, + ) { + let est: U256 = client + .request( + "eth_estimateGas", + ( + req, + "latest", + state_overrides.clone(), + block_override_100m.clone(), + ), + ) + .await + .unwrap_or_else(|e| panic!("{label}: --rpc.gascap=0 must be uncapped, got {e}")); + let est_u64 = u64::try_from(est)?; + assert!( + est_u64 > 60_000_000 && est_u64 <= 100_000_000, + "{label}: expected estimate in (60M, 100M], got {est_u64}" + ); + } + } + Ok(()) } diff --git a/crates/node/tests/it/txpool.rs b/crates/node/tests/it/txpool.rs index e7c2d5f1..28eda327 100644 --- a/crates/node/tests/it/txpool.rs +++ b/crates/node/tests/it/txpool.rs @@ -343,7 +343,7 @@ async fn tx_gas_limit_below_eip7623_floor_is_mined() -> eyre::Result<()> { fn sign_eip1559_transfer( chain_id: u64, signer: &alloy_signer_local::PrivateKeySigner, - nonce: u64, + tx_seq: u64, max_fee_per_gas: u128, max_priority_fee_per_gas: u128, ) -> eyre::Result { @@ -352,7 +352,7 @@ fn sign_eip1559_transfer( let tx = TxEip1559 { chain_id, - nonce, + nonce: tx_seq, gas_limit: 21_000, max_fee_per_gas, max_priority_fee_per_gas, @@ -471,3 +471,71 @@ async fn morph_tx_v1_zero_eth_balance_rejected() -> eyre::Result<()> { ); Ok(()) } + +#[tokio::test(flavor = "multi_thread")] +async fn txpool_replacement_enforces_priority_fee_or_price_bump() -> eyre::Result<()> { + use alloy_consensus::{SignableTransaction, TxLegacy}; + use alloy_signer::SignerSync; + use morph_node::test_utils::MorphTxBuilder; + + reth_tracing::init_test_tracing(); + let (mut nodes, wallet) = TestNodeBuilder::new().build().await?; + let mut node = nodes.pop().unwrap(); + + // 1. Seed nonce 0 with a Legacy tx at gasPrice = 10_000_000 wei. + let legacy_tx = TxLegacy { + chain_id: Some(wallet.chain_id), + nonce: 0, + gas_price: 10_000_000, + gas_limit: 21_000, + to: TxKind::Call(Address::with_last_byte(0x42)), + value: U256::from(100), + input: Bytes::new(), + }; + let legacy_sig = wallet + .inner + .sign_hash_sync(&legacy_tx.signature_hash()) + .map_err(|e| eyre::eyre!("{e}"))?; + let legacy_raw: Bytes = MorphTxEnvelope::Legacy(legacy_tx.into_signed(legacy_sig)) + .encoded_2718() + .into(); + node.rpc.inject_tx(legacy_raw).await?; + + // Replacing Legacy(10M) with EIP-1559(maxFee = 12M, tip = 2M) must be rejected as underpriced + // because `priority_fee_or_price()` (2M) < 1.1 * 10M (11M). + let low_tip_1559 = + sign_eip1559_transfer(wallet.chain_id, &wallet.inner, 0, 12_000_000, 2_000_000)?; + let err = node + .rpc + .inject_tx(low_tip_1559) + .await + .expect_err("Legacy -> EIP-1559 without >=10% priority fee bump must be rejected"); + assert!( + err.to_string().to_lowercase().contains("underpriced"), + "expected replacement transaction underpriced error, got: {err}" + ); + + // Replacing Legacy(10M) with EIP-1559(maxFee = 12M, tip = 11M) succeeds. + let bumped_1559 = + sign_eip1559_transfer(wallet.chain_id, &wallet.inner, 0, 12_000_000, 11_000_000)?; + node.rpc.inject_tx(bumped_1559).await?; + + // Replacing EIP-1559(maxFee = 12M, tip = 11M) with MorphTx(maxFee = 20M, tip = 0) is rejected. + let zero_tip_morph = MorphTxBuilder::new(wallet.chain_id, wallet.inner.clone(), 0) + .with_v1_eth_fee() + .with_fees(20_000_000, 0) + .build_signed()?; + let err = node + .rpc + .inject_tx(zero_tip_morph) + .await + .expect_err("positive-tip EIP-1559 -> zero-tip MorphTx must be rejected"); + assert!( + err.to_string().to_lowercase().contains("underpriced"), + "expected replacement transaction underpriced error, got: {err}" + ); + + let payload = node.advance_block().await?; + assert_eq!(payload.block().body().transactions.len(), 1); + Ok(()) +} diff --git a/crates/payload/builder/Cargo.toml b/crates/payload/builder/Cargo.toml index a217f79b..081dbc22 100644 --- a/crates/payload/builder/Cargo.toml +++ b/crates/payload/builder/Cargo.toml @@ -14,7 +14,7 @@ workspace = true [dependencies] # Morph morph-chainspec.workspace = true -morph-evm = { workspace = true, features = ["serde-bincode-compat"] } +morph-evm = { workspace = true, features = ["std", "serde-bincode-compat"] } morph-payload-types.workspace = true morph-primitives = { workspace = true, features = ["serde-bincode-compat", "reth-codec"] } @@ -23,7 +23,7 @@ reth-basic-payload-builder.workspace = true reth-chainspec.workspace = true reth-evm = { workspace = true, features = ["std"] } reth-execution-cache.workspace = true -reth-execution-types.workspace = true +reth-execution-types = { workspace = true, features = ["std"] } reth-payload-builder.workspace = true reth-payload-primitives.workspace = true reth-payload-util.workspace = true diff --git a/crates/payload/builder/src/builder.rs b/crates/payload/builder/src/builder.rs index c07e1281..f0baf720 100644 --- a/crates/payload/builder/src/builder.rs +++ b/crates/payload/builder/src/builder.rs @@ -3,7 +3,7 @@ use crate::metrics::MorphPayloadBuilderMetrics; use crate::{MorphBuilderConfig, MorphPayloadBuilderError, config::PayloadBuildingBreaker}; use alloy_consensus::{BlockHeader, Transaction, Typed2718, transaction::TxHashRef}; -use alloy_eips::eip2718::Encodable2718; +use alloy_eips::{BlockId, eip2718::Encodable2718}; use alloy_primitives::{Address, B256, Bytes, U256}; use evm2::{DatabaseError, evm::State, registry::HandlerError}; use morph_chainspec::{ @@ -66,6 +66,23 @@ fn is_evictable_token_fee_error(error: &dyn InvalidTxError) -> bool { ) } +/// Returns true when `parent_hash` is still the current canonical head and the pool's +/// `last_seen_block_hash` has not moved onto a different head. +fn is_synchronized_canonical_parent( + client: &Client, + pool: &Pool, + parent_hash: B256, +) -> bool +where + Pool: TransactionPool, + Client: StateProviderFactory, +{ + let canonical_head_hash = client.block_hash_for_id(BlockId::latest()).ok().flatten(); + let pool_seen_hash = pool.block_info().last_seen_block_hash; + canonical_head_hash == Some(parent_hash) + && (pool_seen_hash.is_zero() || pool_seen_hash == parent_hash) +} + /// Validates MorphTx (0x7F) hardfork activation gates and structural field rules against /// the target block timestamp, matching `MorphConsensus::validate_block_pre_execution`. fn validate_morph_tx_for_block( @@ -254,12 +271,20 @@ where payload_id, }; + // Only evict failing pool transactions when building on the current canonical head + // AND the pool has not moved onto a different head: a non-canonical parent (e.g., + // `assembleL2BlockV2` rebuilding on an older block before a token was activated) + // must never remove transactions that are valid on the canonical chain. + let can_evict_from_pool = + is_synchronized_canonical_parent(&self.client, &self.pool, parent_hash); + let ctx = MorphPayloadBuilderCtx { evm_config: self.evm_config.clone(), config: builder_config, cancel, best_payload, builder_config: self.config.clone(), + can_evict_from_pool, metrics: MorphPayloadBuilderMetrics::default(), }; @@ -294,6 +319,7 @@ where build_payload_inner( cached_reads.as_db_mut(state), state_provider.as_ref(), + &self.client, &self.pool, ctx, best, @@ -364,6 +390,9 @@ struct MorphPayloadBuilderCtx { best_payload: Option, /// Builder configuration with limits. builder_config: MorphBuilderConfig, + /// Whether this build targets the current canonical head synchronized with the pool, + /// permitting deterministic token-fee eviction from the global pool. + can_evict_from_pool: bool, /// Prometheus metrics for this payload build job. metrics: MorphPayloadBuilderMetrics, } @@ -424,6 +453,7 @@ impl MorphPayloadBuilderCtx { let supplied_tx_count = self.attributes().transactions.len(); let mut executed_txs: Vec = Vec::with_capacity(supplied_tx_count); let mut saw_l2_transaction = false; + let mut first_l1_msg = true; for (tx_idx, tx_with_encoded) in self.attributes().transactions.iter().enumerate() { // The transaction is already recovered in `try_new` via `try_into_recovered()`. @@ -457,7 +487,20 @@ impl MorphPayloadBuilderCtx { }, ) })?; - if queue_index != info.next_l1_message_index { + // Sequencer assembly (`!no_tx_pool`) requires exact continuity with + // `info.next_l1_message_index` (matching morph-geth's `miner/worker.go`). + // Deterministic L1 derivation (`no_tx_pool`) permits the leading L1 message + // to skip past `parent.next_l1_msg_index` when L1 messages were skipped, + // while still rejecting cross-block replays (`<`) and requiring strict + // sequential indices for subsequent L1 messages in the same block. + let allow_forward_skip = self.attributes().no_tx_pool && first_l1_msg; + first_l1_msg = false; + let invalid_queue_index = if allow_forward_skip { + queue_index < info.next_l1_message_index + } else { + queue_index != info.next_l1_message_index + }; + if invalid_queue_index { return Err(PayloadBuilderError::other( MorphPayloadBuilderError::InvalidSuppliedTransaction { error: format!( @@ -604,6 +647,10 @@ impl MorphPayloadBuilderCtx { // L1-message gas to the block gas pool. Regular transactions do return unused gas. info.gas_pool_used += if is_l1_msg { tx_gas } else { gas_used }; + // Track sender only after successful execution so later pool txs from the same + // sender are never evicted if they fail against in-block mutated sender state. + info.executed_senders.insert(recovered_tx.signer()); + // Increment transaction count info.transaction_count += 1; @@ -618,31 +665,37 @@ impl MorphPayloadBuilderCtx { /// /// Returns `Ok(Some(()))` if the job was cancelled or breaker triggered, `Ok(None)` otherwise. /// Executed transaction bytes are appended to the provided vector. - fn execute_pool_transactions( + #[expect(clippy::too_many_arguments)] + fn execute_pool_transactions( &self, builder: &mut impl BlockBuilder, info: &mut ExecutionInfo, executed_txs: &mut Vec, best_txs: BestTxs, + client: &Client, pool: &Pool, breaker: &PayloadBuildingBreaker, ) -> Result, PayloadBuilderError> where BestTxs: PayloadTransactions>, + Client: StateProviderFactory, Pool: TransactionPool>, { + let parent_hash = self.parent().hash(); self.execute_pool_transactions_with_evictor( builder, info, executed_txs, best_txs, breaker, + || is_synchronized_canonical_parent(client, pool, parent_hash), |tx_hash| { pool.remove_transactions(vec![tx_hash]); }, ) } + #[expect(clippy::too_many_arguments)] fn execute_pool_transactions_with_evictor( &self, builder: &mut impl BlockBuilder, @@ -650,6 +703,7 @@ impl MorphPayloadBuilderCtx { executed_txs: &mut Vec, mut best_txs: BestTxs, breaker: &PayloadBuildingBreaker, + mut is_still_canonical_parent: impl FnMut() -> bool, mut evict_from_pool: impl FnMut(B256), ) -> Result, PayloadBuilderError> where @@ -661,7 +715,6 @@ impl MorphPayloadBuilderCtx { .gas_limit .saturating_to::(); let base_fee = builder.evm_env().block_base_fee(); - let mut executed_senders: HashSet
= HashSet::new(); while let Some(tx) = best_txs.next(()) { // Check if the job was cancelled. This must stay `is_cancelled`: `is_interrupted` @@ -773,8 +826,13 @@ impl MorphPayloadBuilderCtx { "skipping invalid transaction and its descendants" ); best_txs.mark_invalid(tx.signer(), tx.nonce()); - if is_evictable_token_fee_error(error.as_ref()) - && !executed_senders.contains(&tx.signer()) + // Re-check canonical/pool head alignment right before evicting so a + // canonical head advance or reorg while this build job was running + // cannot delete a transaction valid on the new head. + if self.can_evict_from_pool + && is_evictable_token_fee_error(error.as_ref()) + && !info.executed_senders.contains(&tx.signer()) + && is_still_canonical_parent() { tracing::debug!( target: "payload_builder", @@ -815,7 +873,7 @@ impl MorphPayloadBuilderCtx { self.metrics .commit_tx_apply_duration_seconds .record(apply_started.elapsed()); - executed_senders.insert(tx.signer()); + info.executed_senders.insert(tx.signer()); // Update execution info info.cumulative_gas_used += gas_used; @@ -856,13 +914,15 @@ struct ExecutionInfo { next_l1_message_index: u64, /// Number of transactions executed (including both sequencer and pool transactions). transaction_count: u64, + /// Senders that have already executed at least one transaction (supplied or pool) in this block. + executed_senders: HashSet
, /// Maximum DA block size from the builder config. max_da_block_size: Option, } impl ExecutionInfo { /// Creates a new [`ExecutionInfo`] with the initial next L1 message index from parent. - const fn new(next_l1_message_index: u64, max_da_block_size: Option) -> Self { + fn new(next_l1_message_index: u64, max_da_block_size: Option) -> Self { Self { cumulative_gas_used: 0, gas_pool_used: 0, @@ -870,6 +930,7 @@ impl ExecutionInfo { total_fees: U256::ZERO, next_l1_message_index, transaction_count: 0, + executed_senders: HashSet::new(), max_da_block_size, } } @@ -899,9 +960,10 @@ impl ExecutionInfo { } /// Builds the payload on top of the state. -fn build_payload_inner<'a, DB, BestTxs, Pool>( +fn build_payload_inner<'a, DB, BestTxs, Client, Pool>( db: DB, state_provider: &(impl StateProvider + ?Sized), + client: &Client, pool: &Pool, ctx: MorphPayloadBuilderCtx, best: impl FnOnce(BestTransactionsAttributes) -> BestTxs + Send + Sync + 'a, @@ -910,6 +972,7 @@ fn build_payload_inner<'a, DB, BestTxs, Pool>( where DB: Database + 'a, BestTxs: PayloadTransactions> + 'a, + Client: StateProviderFactory, Pool: TransactionPool>, { let build_started = Instant::now(); @@ -994,6 +1057,7 @@ where &mut info, &mut executed_txs, best_txs, + client, pool, &breaker, )? @@ -1355,6 +1419,7 @@ mod tests { cancel: Default::default(), best_payload, builder_config: MorphBuilderConfig::default(), + can_evict_from_pool: true, metrics: MorphPayloadBuilderMetrics::default(), } } @@ -1604,6 +1669,7 @@ mod tests { cancel: Default::default(), best_payload: None, builder_config: MorphBuilderConfig::default(), + can_evict_from_pool: true, metrics: MorphPayloadBuilderMetrics::default(), } } @@ -1840,6 +1906,7 @@ mod tests { &mut executed_txs, best_txs, &breaker, + || true, |hash| evicted.push(hash), ) .expect("pool execution should complete"); @@ -1957,10 +2024,10 @@ mod tests { use reth_primitives_traits::Recovered; use std::collections::{HashMap, VecDeque}; - let make_morph_tx = |signer: Address, nonce: u64, tag: u8| { + let make_morph_tx = |signer: Address, tx_seq: u64, tag: u8| { let tx = TxMorph { chain_id: 2818, - nonce, + nonce: tx_seq, gas_limit: 50_000, max_fee_per_gas: 100, max_priority_fee_per_gas: 10, @@ -2064,6 +2131,7 @@ mod tests { &mut executed_txs, best_txs, &breaker, + || true, |hash| evicted.push(hash), ) .expect("pool execution should complete"); @@ -2075,4 +2143,241 @@ mod tests { assert_eq!(evicted, vec![h_transfer_fail, h_inactive]); assert_eq!(executed_txs.len(), 1); } + + #[test] + fn test_execute_pool_transactions_does_not_evict_when_non_canonical_or_supplied_sender() { + use alloy_consensus::{Sealable, Signed}; + use alloy_primitives::{Signature, TxKind}; + use morph_primitives::{TxL1Msg, TxMorph}; + use morph_txpool::MorphPooledTransaction; + use reth_primitives_traits::Recovered; + use std::collections::{HashMap, VecDeque}; + + let make_morph_tx = |signer: Address, tx_seq: u64, tag: u8| { + let tx = TxMorph { + chain_id: 2818, + nonce: tx_seq, + gas_limit: 50_000, + max_fee_per_gas: 100, + max_priority_fee_per_gas: 10, + to: TxKind::Call(Address::repeat_byte(0xee)), + fee_token_id: 1, + ..Default::default() + }; + let hash = B256::repeat_byte(tag); + let env = MorphTxEnvelope::Morph(Signed::new_unchecked( + tx, + Signature::test_signature(), + hash, + )); + let recovered = Recovered::new_unchecked(env, signer); + let len = recovered.encode_2718_len(); + (hash, MorphPooledTransaction::new(recovered, len)) + }; + + // 1. Non-canonical parent build (`can_evict_from_pool == false`): never evicts. + let sender_a = Address::repeat_byte(0x10); + let (h_stale_inactive, tx_stale_inactive) = make_morph_tx(sender_a, 0, 0xa1); + let mut outcomes = HashMap::new(); + outcomes.insert( + h_stale_inactive, + Err(MorphInvalidTransaction::TokenNotActive(1).into()), + ); + let mut builder = ScriptedBlockBuilder::new(outcomes); + let mut info = ExecutionInfo::default(); + let mut executed_txs = Vec::new(); + let mut ctx = test_ctx_with_timestamp_and_txs(1_800_000_000, vec![]); + ctx.can_evict_from_pool = false; + let breaker = ctx.builder_config.breaker(30_000_000); + let mut evicted = Vec::new(); + + ctx.execute_pool_transactions_with_evictor( + &mut builder, + &mut info, + &mut executed_txs, + ScriptedPoolTxs { + txs: VecDeque::from([tx_stale_inactive]), + marked_invalid: Vec::new(), + }, + &breaker, + || panic!("live canonical recheck should not run when can_evict_from_pool is false"), + |hash| evicted.push(hash), + ) + .expect("pool execution should complete"); + assert!( + evicted.is_empty(), + "non-canonical parent build must never evict from global pool" + ); + + // 2. Supplied L1 message from `sender_l1` seeds `info.executed_senders`, preventing + // eviction of a subsequent failing pool tx from `sender_l1`. + let sender_l1 = Address::repeat_byte(0x30); + let l1_msg = TxL1Msg { + queue_index: 0, + gas_limit: 50_000, + to: Address::repeat_byte(0xaa), + value: U256::ZERO, + sender: sender_l1, + input: Bytes::new(), + }; + let l1_sealed = l1_msg.seal_slow(); + let l1_hash = l1_sealed.hash(); + let l1_encoded = Bytes::from(MorphTxEnvelope::L1Msg(l1_sealed).encoded_2718()); + let (h_l1_sender_pool_tx, tx_l1_sender_pool_tx) = make_morph_tx(sender_l1, 0, 0xc1); + + let mut outcomes = HashMap::new(); + outcomes.insert(l1_hash, Ok(21_000)); + outcomes.insert( + h_l1_sender_pool_tx, + Err(MorphInvalidTransaction::TokenTransferFailed { + reason: "l1 msg changed sender state".into(), + } + .into()), + ); + let mut builder = ScriptedBlockBuilder::new(outcomes); + let mut info = ExecutionInfo::default(); + let ctx = test_ctx_with_timestamp_and_txs(1_800_000_000, vec![l1_encoded]); + let mut executed_txs = ctx + .execute_supplied_transactions(&mut builder, &mut info) + .expect("supplied L1 msg should execute"); + assert!(info.executed_senders.contains(&sender_l1)); + + let breaker = ctx.builder_config.breaker(30_000_000); + let mut evicted = Vec::new(); + ctx.execute_pool_transactions_with_evictor( + &mut builder, + &mut info, + &mut executed_txs, + ScriptedPoolTxs { + txs: VecDeque::from([tx_l1_sender_pool_tx]), + marked_invalid: Vec::new(), + }, + &breaker, + || true, + |hash| evicted.push(hash), + ) + .expect("pool execution should complete"); + assert!( + evicted.is_empty(), + "sender with executed supplied L1 message in block must not be evicted" + ); + + // 3. Mid-build canonical head advance / reorg suppresses global pool eviction. + let sender_race = Address::repeat_byte(0x40); + let (h_race, tx_race) = make_morph_tx(sender_race, 0, 0xd1); + let mut outcomes = HashMap::new(); + outcomes.insert( + h_race, + Err(MorphInvalidTransaction::TokenNotRegistered(99).into()), + ); + let mut builder = ScriptedBlockBuilder::new(outcomes); + let mut info = ExecutionInfo::default(); + let mut executed_txs = Vec::new(); + let ctx = test_ctx_with_timestamp_and_txs(1_800_000_000, vec![]); + let breaker = ctx.builder_config.breaker(30_000_000); + let mut evicted = Vec::new(); + ctx.execute_pool_transactions_with_evictor( + &mut builder, + &mut info, + &mut executed_txs, + ScriptedPoolTxs { + txs: VecDeque::from([tx_race]), + marked_invalid: Vec::new(), + }, + &breaker, + || false, + |hash| evicted.push(hash), + ) + .expect("pool execution should complete"); + assert!( + evicted.is_empty(), + "canonical head advance mid-build must suppress pool eviction" + ); + } + + #[test] + fn test_execute_supplied_transactions_no_tx_pool_allows_leading_l1_forward_skip_only() { + use alloy_consensus::Sealable; + use morph_primitives::TxL1Msg; + use std::collections::HashMap; + + let make_l1 = |queue_index: u64| { + let sealed = TxL1Msg { + queue_index, + gas_limit: 50_000, + to: Address::repeat_byte(0xaa), + value: U256::ZERO, + sender: Address::repeat_byte(0xbb), + input: Bytes::new(), + } + .seal_slow(); + let hash = sealed.hash(); + let bytes = Bytes::from(MorphTxEnvelope::L1Msg(sealed).encoded_2718()); + (hash, bytes) + }; + + let make_no_pool_ctx = |txs: Vec| { + let mut rpc_attrs = morph_payload_types::MorphPayloadAttributes::default(); + rpc_attrs.inner.timestamp = 1_800_000_000; + rpc_attrs.transactions = Some(txs); + rpc_attrs.no_tx_pool = true; + let attrs = MorphPayloadBuilderAttributes::try_new( + B256::ZERO, + rpc_attrs, + morph_payload_types::MORPH_PAYLOAD_BUILDER_VERSION, + ) + .unwrap(); + let payload_id = attrs.payload_id(); + MorphPayloadBuilderCtx { + evm_config: test_evm_config(), + config: PayloadConfig::new( + Arc::new(SealedHeader::seal_slow(MorphHeader::default())), + attrs, + payload_id, + ), + cancel: Default::default(), + best_payload: None, + builder_config: MorphBuilderConfig::default(), + can_evict_from_pool: false, + metrics: MorphPayloadBuilderMetrics::default(), + } + }; + + // Forward skip on leading L1 msg (parent next=2, msgs=[5, 6]) succeeds under `no_tx_pool`. + let (h5, b5) = make_l1(5); + let (h6, b6) = make_l1(6); + let mut outcomes = HashMap::new(); + outcomes.insert(h5, Ok(21_000)); + outcomes.insert(h6, Ok(21_000)); + let mut builder = ScriptedBlockBuilder::new(outcomes); + let mut info = ExecutionInfo::new(2, None); + let ctx = make_no_pool_ctx(vec![b5.clone(), b6]); + let executed = ctx + .execute_supplied_transactions(&mut builder, &mut info) + .expect("leading forward skip in deterministic safe build must succeed"); + assert_eq!(executed.len(), 2); + assert_eq!(info.next_l1_message_index, 7); + + // Cross-block replay (`queue_index = 1 < parent next = 2`) still fails. + let (_h1, b1) = make_l1(1); + let mut builder = ScriptedBlockBuilder::new(HashMap::new()); + let mut info = ExecutionInfo::new(2, None); + let ctx = make_no_pool_ctx(vec![b1]); + assert!( + ctx.execute_supplied_transactions(&mut builder, &mut info) + .is_err() + ); + + // Non-contiguous second L1 message (`[5, 8]`) still fails. + let (_h8, b8) = make_l1(8); + let mut outcomes = HashMap::new(); + outcomes.insert(h5, Ok(21_000)); + let mut builder = ScriptedBlockBuilder::new(outcomes); + let mut info = ExecutionInfo::new(2, None); + let ctx = make_no_pool_ctx(vec![b5, b8]); + assert!( + ctx.execute_supplied_transactions(&mut builder, &mut info) + .is_err() + ); + } } diff --git a/crates/payload/types/src/lib.rs b/crates/payload/types/src/lib.rs index aa621bc3..15ebc71c 100644 --- a/crates/payload/types/src/lib.rs +++ b/crates/payload/types/src/lib.rs @@ -52,7 +52,7 @@ pub use safe_l2_data::SafeL2Data; #[non_exhaustive] pub struct MorphPayloadTypes; -/// Execution data for Morph node: a sealed block plus an optional expected withdraw trie root. +/// Execution data for Morph node: a sealed block plus optional cross-check metadata. #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct MorphExecutionData { /// The built block. @@ -60,6 +60,13 @@ pub struct MorphExecutionData { /// Optional expected withdraw trie root supplied by custom engine APIs. #[serde(default, skip_serializing_if = "Option::is_none")] pub expected_withdraw_trie_root: Option, + /// Marks L1-derived safe blocks (`engine_newSafeL2Block`) that exempt header wall-clock / + /// gas-limit / base-fee bounds and local DA byte caps while preserving structural invariants. + /// + /// Strictly internal in-process metadata (`#[serde(skip)]`) so external JSON/serde payloads + /// can never set `is_safe = true`. + #[serde(skip)] + pub is_safe: bool, } impl MorphExecutionData { @@ -68,6 +75,7 @@ impl MorphExecutionData { Self { block, expected_withdraw_trie_root: None, + is_safe: false, } } @@ -79,8 +87,15 @@ impl MorphExecutionData { Self { block, expected_withdraw_trie_root: Some(expected_withdraw_trie_root), + is_safe: false, } } + + /// Marks this payload as an L1-derived safe block (`NewSafeL2Block`). + pub const fn with_safe_validation(mut self) -> Self { + self.is_safe = true; + self + } } impl From for MorphExecutionData { @@ -247,5 +262,28 @@ mod tests { let data = MorphPayloadTypes::block_to_payload(block, None); assert_eq!(data.block_hash(), hash); assert!(data.expected_withdraw_trie_root.is_none()); + assert!(!data.is_safe); + } + + #[test] + fn test_execution_data_serde_skips_and_ignores_is_safe() { + let block = Arc::new(create_test_block()); + let safe = MorphExecutionData::new(block).with_safe_validation(); + assert!(safe.is_safe); + + let mut json_val = serde_json::to_value(&safe).expect("serialize MorphExecutionData"); + assert!( + json_val.get("is_safe").is_none() && json_val.get("isSafe").is_none(), + "is_safe must never be serialized" + ); + + json_val["is_safe"] = serde_json::json!(true); + json_val["isSafe"] = serde_json::json!(true); + let decoded: MorphExecutionData = + serde_json::from_value(json_val).expect("deserialize MorphExecutionData"); + assert!( + !decoded.is_safe, + "untrusted serde input must never set is_safe" + ); } } diff --git a/crates/proofs-exex/Cargo.toml b/crates/proofs-exex/Cargo.toml index 6c1a6728..25948cee 100644 --- a/crates/proofs-exex/Cargo.toml +++ b/crates/proofs-exex/Cargo.toml @@ -17,7 +17,7 @@ alloy-consensus.workspace = true alloy-eips.workspace = true eyre.workspace = true futures.workspace = true -reth-execution-types.workspace = true +reth-execution-types = { workspace = true, features = ["std"] } reth-exex.workspace = true reth-node-api.workspace = true reth-provider.workspace = true diff --git a/crates/proofs-exex/src/lib.rs b/crates/proofs-exex/src/lib.rs index 9a961892..c2133f07 100644 --- a/crates/proofs-exex/src/lib.rs +++ b/crates/proofs-exex/src/lib.rs @@ -161,6 +161,19 @@ where } } +/// What the sync loop must do after attempting a revert. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum RevertOutcome { + /// The revert landed, or there was nothing above the target to unwind. + Completed, + /// A retryable I/O error: the consumed state must be requeued, otherwise the revert is lost + /// and a later shallower reorg could anchor the abandoned branch onto the canonical chain. + Retry, + /// The store cannot represent this revert; it stays on the abandoned branch until a later + /// reorg or a manual re-initialization recovers it. + Abandoned, +} + impl MorphProofsExEx where Node: FullNodeComponents>, @@ -329,25 +342,40 @@ where match state { SyncTargetState::Revert { revert_to } => { - if Self::run_revert(&storage, collector, revert_to) { - sync_target.mark_revert_complete(&revert_to); + match Self::run_revert(&storage, collector, revert_to) { + RevertOutcome::Completed => sync_target.mark_revert_complete(&revert_to), + RevertOutcome::Retry => { + Self::requeue(&sync_target, SyncTargetState::Revert { revert_to }) + .await; + } + RevertOutcome::Abandoned => {} } } SyncTargetState::RevertThenSync { revert_to, sync_to } => { // Only advance once the revert landed. Marking it complete would strip a revert // that arrived while this one was running, and syncing forward on the abandoned // branch would just be refused by the store's parent check. - if Self::run_revert(&storage, collector, revert_to) { - sync_target.mark_revert_complete(&revert_to); - Self::sync_forward( - &sync_target, - &storage, - &provider, - collector, - verification_interval, - sync_to, - ) - .await; + match Self::run_revert(&storage, collector, revert_to) { + RevertOutcome::Completed => { + sync_target.mark_revert_complete(&revert_to); + Self::sync_forward( + &sync_target, + &storage, + &provider, + collector, + verification_interval, + sync_to, + ) + .await; + } + RevertOutcome::Retry => { + Self::requeue( + &sync_target, + SyncTargetState::RevertThenSync { revert_to, sync_to }, + ) + .await; + } + RevertOutcome::Abandoned => {} } } SyncTargetState::SyncUpTo { to } => { @@ -365,7 +393,7 @@ where } } - /// Runs a revert, classifies whatever it returns, and reports whether it landed. + /// Runs a revert, classifies whatever it returns, and reports what the sync loop must do next. /// /// Nothing propagates: a reorg the store cannot represent is not a reason to take the node down. /// The caller must not treat a failed revert as done, because `mark_revert_complete` could strip @@ -376,10 +404,10 @@ where storage: &MorphProofsStorage, collector: &LiveTrieCollector<'_, Node::Evm, Node::Provider, Storage>, revert_to: BlockWithParent, - ) -> bool { + ) -> RevertOutcome { let Err(error) = Self::handle_revert(storage, collector, revert_to) else { ProofHistoryMetrics::set_sync_healthy(true); - return true; + return RevertOutcome::Completed; }; let transient = Self::is_retryable_sync_error(&error); @@ -389,18 +417,19 @@ where target: "morph::proofs_exex", ?error, revert_to = revert_to.block.number, - "Transient proof-history revert failure; a later reorg may reschedule recovery" - ); - } else { - ProofHistoryMetrics::set_sync_healthy(false); - warn!( - target: "morph::proofs_exex", - ?error, - revert_to = revert_to.block.number, - "Proof history stays on the abandoned branch; proof RPCs refuse requests until a later reorg or re-initialization recovers it" + "Transient proof-history revert failure; retrying after backoff" ); + return RevertOutcome::Retry; } - false + + ProofHistoryMetrics::set_sync_healthy(false); + warn!( + target: "morph::proofs_exex", + ?error, + revert_to = revert_to.block.number, + "Proof history stays on the abandoned branch; proof RPCs refuse requests until a later reorg or re-initialization recovers it" + ); + RevertOutcome::Abandoned } /// Reverts proof history to `revert_to`. @@ -453,7 +482,7 @@ where } #[cfg(test)] - fn run_revert_for_test(&self, revert_to: BlockWithParent) -> bool { + fn run_revert_for_test(&self, revert_to: BlockWithParent) -> RevertOutcome { let collector = LiveTrieCollector::new( self.ctx.evm_config().clone(), self.ctx.provider().clone(), @@ -549,17 +578,22 @@ where } } - /// Re-arm a forward-sync target after a transient failure, then back off. + /// Re-arm consumed work after a transient failure, then back off. /// - /// `take_state()` already consumed the original `SyncUpTo`, so returning without this would - /// leave the loop parked on `notified()` until the next chain event. Requeuing puts the failed - /// target back as the base and merges anything that arrived while it ran on top, so a newer - /// notification still wins. - async fn requeue_sync_up_to(sync_target: &SyncTarget, target: u64) { - sync_target.requeue_state(SyncTargetState::SyncUpTo { to: target }); + /// `take_state()` already consumed the original state, so returning without this would drop + /// the work (a lost revert leaves the store on the abandoned branch) or leave the loop parked on + /// `notified()` until the next chain event. Requeuing puts the failed state back as the base and + /// merges anything that arrived while it ran on top, so a newer notification still wins and the + /// deeper of two reverts is kept. + async fn requeue(sync_target: &SyncTarget, failed: SyncTargetState) { + sync_target.requeue_state(failed); tokio::time::sleep(SYNC_RETRY_DELAY).await; } + async fn requeue_sync_up_to(sync_target: &SyncTarget, target: u64) { + Self::requeue(sync_target, SyncTargetState::SyncUpTo { to: target }).await; + } + /// Whether re-running the same work could succeed. /// /// Storage and provider I/O can fail for reasons that clear on their own. Every other variant @@ -1188,9 +1222,11 @@ mod tests { )); // The sync loop keys `mark_revert_complete` off this, so a contained failure must never // report success: doing so would strip a reorg that queued up while the revert was running. - assert!( - !exex.run_revert_for_test(initial_anchor), - "a failed revert must not be reported as landed" + // It is not retryable either: re-running it would fail the same way forever. + assert_eq!( + exex.run_revert_for_test(initial_anchor), + RevertOutcome::Abandoned, + "a structural revert failure must be abandoned, not reported as landed or retried" ); assert_eq!( diff --git a/crates/proofs/src/db/store.rs b/crates/proofs/src/db/store.rs index 5a9fa180..8f7a7c8b 100644 --- a/crates/proofs/src/db/store.rs +++ b/crates/proofs/src/db/store.rs @@ -557,6 +557,7 @@ impl MdbxProofsStorage { &self, tx: &(impl DbTxMut + DbTx), cutoff_items: Vec<(T::Key, u64)>, + is_deleted: impl Fn(&Option) -> bool, ) -> MorphProofsStorageResult where T: Table> + DupSort, @@ -575,10 +576,10 @@ impl MdbxProofsStorage { loop { if entry.block_number >= survivor_block { // Reached the survivor version (or newer). Stop deleting for this key. - // If the survivor is a tombstone (None), delete it too — with all older - // history already gone, a tombstone at the new earliest is redundant + // If the survivor marks a deletion, delete it too — with all older + // history already gone, a deletion marker at the new earliest is redundant // (it implies "does not exist"). - if entry.block_number == survivor_block && entry.value.0.is_none() { + if entry.block_number == survivor_block && is_deleted(&entry.value.0) { cur.delete_current()?; deleted_count += 1; } @@ -1125,20 +1126,31 @@ impl MorphProofsStore for MdbxProofsStorage { }; // 1. Execute Sparse Deletions and track actual deleted rows - let acc_deleted = - self.prune_history_preceding::(tx, plan.acc_survivors)?; + let acc_deleted = self.prune_history_preceding::( + tx, + plan.acc_survivors, + Option::is_none, + )?; - let st_deleted = - self.prune_history_preceding::(tx, plan.storage_survivors)?; + let st_deleted = self.prune_history_preceding::( + tx, + plan.storage_survivors, + Option::is_none, + )?; let ha_deleted = self.prune_history_preceding::( tx, plan.hashed_acc_survivors, + Option::is_none, )?; + // A cleared slot is persisted as `Some(StorageValue(U256::ZERO))`, and every reader + // treats zero as absent. Without this, a slot cleared and never rewritten would keep + // its zero row forever, growing the store and the cursor scans past it. let hs_deleted = self.prune_history_preceding::( tx, plan.hashed_storage_survivors, + |value| value.as_ref().is_none_or(|value| value.0.is_zero()), )?; let counts = WriteCounts { @@ -4543,4 +4555,62 @@ mod tests { assert_eq!(latest.1.number(), b3.block.number); assert_eq!(*latest.1.hash(), b3.block.hash); } + + #[test] + fn prune_reclaims_cleared_storage_slot() { + let dir = TempDir::new().unwrap(); + let store = MdbxProofsStorage::new(dir.path()).expect("env"); + let b0_hash = B256::repeat_byte(0x00); + store.set_earliest_block_number(0, b0_hash).unwrap(); + + let addr = B256::repeat_byte(0xAA); + let slot = B256::repeat_byte(0x11); + let key = HashedStorageKey::new(addr, slot); + let b1 = BlockWithParent::new(b0_hash, NumHash::new(1, B256::repeat_byte(0x01))); + let b2 = BlockWithParent::new(b1.block.hash, NumHash::new(2, B256::repeat_byte(0x02))); + + // Block 1 sets the slot, block 2 clears it again. + for (block, value) in [(b1, U256::from(42)), (b2, U256::ZERO)] { + let mut storage = HashedStorage::default(); + storage.storage.insert(slot, value); + let mut post_state = HashedPostState::default(); + post_state.storages.insert(addr, storage); + store + .store_trie_updates( + block, + BlockStateDiff { + sorted_trie_updates: TrieUpdatesSorted::default(), + sorted_post_state: post_state.into_sorted(), + }, + ) + .unwrap(); + } + + // Readers treat the stored zero as absent. + assert_eq!( + store + .storage_hashed_cursor(addr, 1) + .unwrap() + .seek(slot) + .unwrap(), + Some((slot, U256::from(42))) + ); + assert_eq!( + store + .storage_hashed_cursor(addr, 2) + .unwrap() + .seek(slot) + .unwrap(), + None + ); + + // Pruning through block 2 must drop the zero survivor too, not keep it forever. + store.prune_earliest_state(b2).unwrap(); + let tx = store.env.tx().unwrap(); + let mut cursor = tx.new_cursor::().unwrap(); + assert!( + cursor.seek_by_key_subkey(key, 0).unwrap().is_none(), + "a cleared slot must not survive pruning" + ); + } } diff --git a/crates/reference-index/src/backfill.rs b/crates/reference-index/src/backfill.rs index 70007ea8..5b6ef65b 100644 --- a/crates/reference-index/src/backfill.rs +++ b/crates/reference-index/src/backfill.rs @@ -65,6 +65,13 @@ pub(crate) fn commit_canonical_batch( block.number ))); } + if offset > 0 && block.parent_hash != blocks[offset - 1].hash { + return Err(ReferenceIndexError::Other(eyre::eyre!( + "non-linked reference-index batch at block {expected}: parent hash {} does not match predecessor {}", + block.parent_hash, + blocks[offset - 1].hash + ))); + } } let tx = db.tx_mut()?; @@ -98,12 +105,21 @@ mod tests { use super::*; use alloy_primitives::B256; - fn block(number: u64) -> CanonicalBlock { + fn block_hash(number: u64) -> B256 { let mut hash = [0u8; 32]; hash[24..].copy_from_slice(&number.to_be_bytes()); + B256::from(hash) + } + + fn block(number: u64) -> CanonicalBlock { CanonicalBlock { number, - hash: B256::from(hash), + hash: block_hash(number), + parent_hash: if number == 0 { + B256::ZERO + } else { + block_hash(number - 1) + }, timestamp: number, transactions: Vec::new(), } diff --git a/crates/reference-index/src/lib.rs b/crates/reference-index/src/lib.rs index bdeea202..d6421c6d 100644 --- a/crates/reference-index/src/lib.rs +++ b/crates/reference-index/src/lib.rs @@ -23,7 +23,7 @@ mod tables; mod types; mod writer; -pub use reader::{ReferenceIndexHandle, ReferenceIndexPhase, ReferenceIndexProgress}; +pub use reader::{ReferenceIndexHandle, ReferenceIndexPhase}; pub use runtime::{ReferenceIndexConfig, ReferenceIndexRuntime}; pub use source::{CanonicalBlock, CanonicalChain}; pub use types::{ diff --git a/crates/reference-index/src/reader.rs b/crates/reference-index/src/reader.rs index 2dd3c8e6..52099185 100644 --- a/crates/reference-index/src/reader.rs +++ b/crates/reference-index/src/reader.rs @@ -13,7 +13,6 @@ use std::sync::{ Arc, atomic::{AtomicBool, AtomicU8, Ordering}, }; -use tokio::sync::watch; /// Runtime phase, exported for metrics and logs, and read by the RPC layer only /// to skip its bounded catch-up wait while `Deferred` or `PreJade`. @@ -58,29 +57,6 @@ impl ReferenceIndexPhase { } } -/// Snapshot of reference-index runtime progress published over a -/// [`tokio::sync::watch`] channel so async RPC callers wake on cursor commits, -/// phase transitions, or runtime shutdown without polling. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct ReferenceIndexProgress { - /// Current runtime phase. - pub phase: ReferenceIndexPhase, - /// Latest durably committed `IndexedTo` block number observed by the runtime. - pub indexed_to: Option, - /// Whether the runtime has entered the terminal [`ReferenceIndexPhase::Unavailable`] state. - pub unavailable: bool, -} - -impl ReferenceIndexProgress { - const fn opening() -> Self { - Self { - phase: ReferenceIndexPhase::Opening, - indexed_to: None, - unavailable: false, - } - } -} - #[derive(Debug)] struct ReferenceIndexShared { db: RwLock>, @@ -91,11 +67,6 @@ struct ReferenceIndexShared { /// `IndexUnavailable` so clients stop retrying; in every other phase the /// tip comparison decides on its own (`IndexBehind` when the cursor lags). unavailable: AtomicBool, - /// Watch receiver cloned by RPC callers to wait asynchronously for cursor or - /// phase updates. The corresponding [`watch::Sender`] is owned exclusively by - /// [`crate::ReferenceIndexRuntime`] so runtime shutdown drops it and wakes - /// all waiters immediately. - progress_rx: watch::Receiver, metrics: ReferenceIndexMetrics, } @@ -113,30 +84,17 @@ pub struct ReferenceIndexHandle { } impl ReferenceIndexHandle { - /// Create a standalone handle without an attached background runtime. - /// - /// Its progress watch channel is immediately closed so async waiters do not - /// stall waiting for a nonexistent writer. + /// Create a handle before the background runtime has opened the database. pub fn new(jade_timestamp: u64) -> Self { - let (handle, _tx) = Self::new_with_progress(jade_timestamp); - handle - } - - pub(crate) fn new_with_progress( - jade_timestamp: u64, - ) -> (Self, watch::Sender) { - let (progress_tx, progress_rx) = watch::channel(ReferenceIndexProgress::opening()); - let handle = Self { + Self { shared: Arc::new(ReferenceIndexShared { db: RwLock::new(None), phase: AtomicU8::new(ReferenceIndexPhase::Opening as u8), unavailable: AtomicBool::new(false), - progress_rx, metrics: ReferenceIndexMetrics::default(), }), jade_timestamp, - }; - (handle, progress_tx) + } } /// Current in-memory runtime phase, exposed for logs and metrics. @@ -144,21 +102,6 @@ impl ReferenceIndexHandle { ReferenceIndexPhase::from_u8(self.shared.phase.load(Ordering::Acquire)) } - /// Latest runtime progress snapshot (phase, durable cursor height, and - /// unavailable flag). - pub fn progress(&self) -> ReferenceIndexProgress { - let mut progress = *self.shared.progress_rx.borrow(); - progress.phase = self.phase(); - progress.unavailable = self.shared.unavailable.load(Ordering::Acquire); - progress - } - - /// Subscribe to runtime progress updates (cursor commits, phase transitions, - /// `Unavailable`, and runtime shutdown). - pub fn subscribe_progress(&self) -> watch::Receiver { - self.shared.progress_rx.clone() - } - /// Whether a canonical tip at `timestamp` predates Jade. /// /// Before Jade no reference-carrying transaction can exist, so the complete @@ -169,6 +112,20 @@ impl ReferenceIndexHandle { timestamp < self.jade_timestamp } + /// Latest durably committed `IndexedTo` block number, or `None` before the + /// first commit. + /// + /// The RPC layer reads this only after a query came back `IndexBehind`, to + /// tell a steady-state lag (worth waiting out) from a runtime that is far + /// behind. It opens its own read transaction, so callers must use it from a + /// blocking context. + pub fn indexed_to(&self) -> Result, ReferenceIndexError> { + let Some(db) = self.db() else { + return Ok(None); + }; + db.indexed_to() + } + pub(crate) fn install_db(&self, db: ReferenceIndexDb) { *self.shared.db.write() = Some(db); } diff --git a/crates/reference-index/src/runtime.rs b/crates/reference-index/src/runtime.rs index 2ca29c67..44684d78 100644 --- a/crates/reference-index/src/runtime.rs +++ b/crates/reference-index/src/runtime.rs @@ -2,7 +2,7 @@ use crate::{ CanonicalChain, DEFAULT_BACKFILL_BATCH_BLOCKS, LIVE_LAG_SLO, ReferenceIndexError, - ReferenceIndexHandle, ReferenceIndexPhase, ReferenceIndexProgress, + ReferenceIndexHandle, ReferenceIndexPhase, backfill::{commit_canonical_batch, resolve_jade_first_block}, db::ReferenceIndexDb, reconcile::rollback_suffix, @@ -15,12 +15,9 @@ use std::{ path::{Path, PathBuf}, time::{Duration, Instant}, }; -use tokio::sync::{ - broadcast::{ - Receiver, - error::{RecvError, TryRecvError}, - }, - watch, +use tokio::sync::broadcast::{ + Receiver, + error::{RecvError, TryRecvError}, }; use tokio::time::MissedTickBehavior; use tracing::{debug, info, warn}; @@ -137,55 +134,22 @@ pub struct ReferenceIndexRuntime { config: ReferenceIndexConfig, chain: C, handle: ReferenceIndexHandle, - progress_tx: watch::Sender, } impl ReferenceIndexRuntime { /// Create a single-writer runtime and its cloneable RPC query handle. pub fn new(config: ReferenceIndexConfig, chain: C) -> (Self, ReferenceIndexHandle) { - let (handle, progress_tx) = ReferenceIndexHandle::new_with_progress(config.jade_timestamp); + let handle = ReferenceIndexHandle::new(config.jade_timestamp); ( Self { config, chain, handle: handle.clone(), - progress_tx, }, handle, ) } - fn publish_progress(&self, phase: ReferenceIndexPhase, indexed_to: Option) { - self.handle.set_phase(phase); - let _ = self.progress_tx.send(ReferenceIndexProgress { - phase, - indexed_to, - unavailable: phase == ReferenceIndexPhase::Unavailable, - }); - } - - fn set_phase(&self, phase: ReferenceIndexPhase) { - let current = *self.progress_tx.borrow(); - let changed = current.phase != phase; - self.handle.set_phase(phase); - if changed { - let _ = self.progress_tx.send(ReferenceIndexProgress { - phase, - indexed_to: current.indexed_to, - unavailable: phase == ReferenceIndexPhase::Unavailable, - }); - } - } - - fn set_indexed_to(&self, indexed_to: Option) { - let phase = self.handle.phase(); - let _ = self.progress_tx.send(ReferenceIndexProgress { - phase, - indexed_to, - unavailable: phase == ReferenceIndexPhase::Unavailable, - }); - } - fn open_db(&self) -> Result { if let Some(db) = self.handle.db() { return Ok(db); @@ -195,9 +159,7 @@ impl ReferenceIndexRuntime { self.config.chain_id, self.config.genesis_hash, )?; - let indexed_to = db.indexed_to()?; self.handle.install_db(db.clone()); - self.set_indexed_to(indexed_to); Ok(db) } @@ -225,7 +187,7 @@ impl ReferenceIndexRuntime { return Ok(()); } - self.set_phase(ReferenceIndexPhase::Repairing); + self.handle.set_phase(ReferenceIndexPhase::Repairing); self.handle.metrics().reorgs_total.increment(1); // A finalized block can never be reorged, so the rewind never needs to // go below it — bounding the scan (and the retained `IndexedBlocks` @@ -256,9 +218,7 @@ impl ReferenceIndexRuntime { let ancestor = ancestor.ok_or(ReferenceIndexError::ManualRebuildRequired { jade_first_block })?; - rollback_suffix(db, Some(ancestor), DEFAULT_BACKFILL_BATCH_BLOCKS)?; - self.set_indexed_to(Some(ancestor)); - Ok(()) + rollback_suffix(db, Some(ancestor), DEFAULT_BACKFILL_BATCH_BLOCKS) } /// Perform one synchronous reconciliation/backfill turn. @@ -271,7 +231,7 @@ impl ReferenceIndexRuntime { // cursor-vs-tip comparison surface `IndexBehind` — which tells clients // to retry — instead of `IndexUnavailable`, which tells them to stop. if error.requires_manual_rebuild() { - self.set_phase(ReferenceIndexPhase::Unavailable); + self.handle.set_phase(ReferenceIndexPhase::Unavailable); } } result @@ -282,16 +242,16 @@ impl ReferenceIndexRuntime { let head = self.chain.head()?; if head.timestamp < self.config.jade_timestamp { self.handle.metrics().lag_blocks.set(0.0); - self.set_phase(ReferenceIndexPhase::PreJade); + self.handle.set_phase(ReferenceIndexPhase::PreJade); return Ok(()); } if defer { - let indexed_to = db.indexed_to()?; + let indexed_to = db.indexed_to()?.unwrap_or_default(); self.handle .metrics() .lag_blocks - .set(head.number.saturating_sub(indexed_to.unwrap_or_default()) as f64); - self.publish_progress(ReferenceIndexPhase::Deferred, indexed_to); + .set(head.number.saturating_sub(indexed_to) as f64); + self.handle.set_phase(ReferenceIndexPhase::Deferred); return Ok(()); } @@ -306,15 +266,15 @@ impl ReferenceIndexRuntime { }; let finalized = self.chain.finalized_block_number()?; self.reconcile_cursor(&db, jade_first_block, finalized, head)?; - let indexed_to = db.indexed_to()?; - let start = indexed_to.map_or(jade_first_block, |cursor| cursor.saturating_add(1)); + let cursor = db.indexed_to()?; + let start = cursor.map_or(jade_first_block, |cursor| cursor.saturating_add(1)); if start > head.number { self.handle.metrics().lag_blocks.set(0.0); - self.publish_progress(ReferenceIndexPhase::Live, indexed_to); + self.handle.set_phase(ReferenceIndexPhase::Live); return Ok(()); } - self.publish_progress(ReferenceIndexPhase::Backfill, indexed_to); + self.handle.set_phase(ReferenceIndexPhase::Backfill); let end = start .saturating_add(DEFAULT_BACKFILL_BATCH_BLOCKS - 1) .min(head.number); @@ -326,6 +286,22 @@ impl ReferenceIndexRuntime { blocks.len() ))); } + // Verify cursor-to-batch and intra-batch parent linkage so a TOCTOU + // reorg between `reconcile_cursor` and `canonical_blocks` aborts and + // retries instead of splicing a new branch onto an orphaned prefix. + if let Some(cursor) = cursor { + let indexed_cursor_hash = db.indexed_block_hash(cursor)?.ok_or_else(|| { + ReferenceIndexError::CorruptMetadata( + "durable cursor is missing an IndexedBlocks hash", + ) + })?; + if blocks[0].parent_hash != indexed_cursor_hash { + return Err(ReferenceIndexError::Other(eyre::eyre!( + "canonical chain reorged before backfill batch at {start}: parent hash {} does not match indexed cursor {cursor} ({indexed_cursor_hash})", + blocks[0].parent_hash + ))); + } + } for (offset, block) in blocks.iter().enumerate() { let expected_number = start + offset as u64; let canonical_hash = self.chain.canonical_hash(expected_number)?; @@ -334,6 +310,11 @@ impl ReferenceIndexRuntime { "canonical block changed while reading backfill batch at {expected_number}" ))); } + if offset > 0 && block.parent_hash != blocks[offset - 1].hash { + return Err(ReferenceIndexError::Other(eyre::eyre!( + "canonical parent hash mismatch inside backfill batch at {expected_number}" + ))); + } } commit_canonical_batch(&db, jade_first_block, start, &blocks, finalized)?; @@ -343,16 +324,13 @@ impl ReferenceIndexRuntime { if lag > LIVE_LAG_SLO { debug!(target: TARGET, lag, slo = LIVE_LAG_SLO, "reference index remains behind its live-lag SLO"); } - let next_phase = if end == current_head.number + if end == current_head.number && blocks .last() .is_some_and(|block| block.hash == current_head.hash) { - ReferenceIndexPhase::Live - } else { - ReferenceIndexPhase::Backfill - }; - self.publish_progress(next_phase, Some(end)); + self.handle.set_phase(ReferenceIndexPhase::Live); + } Ok(()) } @@ -569,23 +547,50 @@ mod tests { impl TestChain { fn linear(count: u64, first_timestamp: u64) -> Self { - let blocks = (0..count) - .map(|number| CanonicalBlock { + let mut blocks = Vec::with_capacity(count as usize); + let mut parent_hash = B256::ZERO; + for number in 0..count { + let hash = B256::with_last_byte(number as u8); + blocks.push(CanonicalBlock { number, - hash: B256::with_last_byte(number as u8), + hash, + parent_hash, timestamp: first_timestamp + number, transactions: Vec::new(), - }) - .collect(); + }); + parent_hash = hash; + } Self { blocks: Arc::new(RwLock::new(blocks)), finalized: Arc::new(RwLock::new(None)), } } + fn push_next(&self) { + let mut blocks = self.blocks.write(); + let last = blocks.last().expect("non-empty test chain"); + let number = last.number + 1; + let parent_hash = last.hash; + let timestamp = last.timestamp + 1; + blocks.push(CanonicalBlock { + number, + hash: B256::with_last_byte(number as u8), + parent_hash, + timestamp, + transactions: Vec::new(), + }); + } + fn replace_suffix(&self, from: u64) { - for block in self.blocks.write().iter_mut().skip(from as usize) { - block.hash = B256::repeat_byte(0x80 | block.number as u8); + let mut blocks = self.blocks.write(); + for index in (from as usize)..blocks.len() { + let number = blocks[index].number; + blocks[index].hash = B256::repeat_byte(0x80 | number as u8); + blocks[index].parent_hash = if index == 0 { + B256::ZERO + } else { + blocks[index - 1].hash + }; } } @@ -910,62 +915,147 @@ mod tests { assert_eq!(handle.db().unwrap().indexed_block_hash(0).unwrap(), None); } - #[tokio::test] - async fn watch_progress_notifies_on_commit_phase_transition_unavailable_and_drop() { + #[derive(Clone, Debug)] + struct ReorgOnBatchReadChain { + inner: TestChain, + reorg_from: u64, + fired: Arc, + } + + impl CanonicalChain for ReorgOnBatchReadChain { + fn head(&self) -> Result { + self.inner.head() + } + + fn canonical_hash(&self, number: u64) -> Result, ReferenceIndexError> { + self.inner.canonical_hash(number) + } + + fn block_timestamp(&self, number: u64) -> Result, ReferenceIndexError> { + self.inner.block_timestamp(number) + } + + fn finalized_block_number(&self) -> Result, ReferenceIndexError> { + self.inner.finalized_block_number() + } + + fn canonical_blocks( + &self, + range: RangeInclusive, + ) -> Result, ReferenceIndexError> { + // Simulate a reorg landing after `reconcile_cursor` already verified + // the previous cursor hash, right before the next batch is read. + if !self.fired.swap(true, std::sync::atomic::Ordering::SeqCst) { + self.inner.replace_suffix(self.reorg_from); + } + self.inner.canonical_blocks(range) + } + } + + #[test] + fn toctou_reorg_between_reconcile_and_batch_read_aborts_and_repairs_without_splicing() { let dir = tempfile::tempdir().unwrap(); - let chain = TestChain::linear(10, 200); + let base = TestChain::linear(5, 200); + let chain = ReorgOnBatchReadChain { + inner: base.clone(), + reorg_from: 4, + fired: Arc::new(std::sync::atomic::AtomicBool::new(true)), + }; let config = ReferenceIndexConfig::new(dir.path(), 2818, B256::ZERO, 200); let (mut runtime, handle) = ReferenceIndexRuntime::new(config, chain.clone()); - let mut rx = handle.subscribe_progress(); + // Index blocks 0..=4 on branch A. + runtime.synchronize_once(false).unwrap(); + assert_eq!(handle.phase(), ReferenceIndexPhase::Live); + let old_block4_hash = base.canonical_hash(4).unwrap().unwrap(); assert_eq!( - *rx.borrow(), - ReferenceIndexProgress { - phase: ReferenceIndexPhase::Opening, - indexed_to: None, - unavailable: false, - } + handle.db().unwrap().indexed_block_hash(4).unwrap(), + Some(old_block4_hash) + ); + + // Advance branch A to block 5, then arm the TOCTOU reorg at block 4 + // so `canonical_blocks(5..=5)` returns B5 (parent B4 != A4) while + // `canonical_hash(5)` matches B5. + base.push_next(); + chain + .fired + .store(false, std::sync::atomic::Ordering::SeqCst); + + let err = runtime.synchronize_once(false).unwrap_err(); + assert!( + err.to_string().contains("does not match indexed cursor 4"), + "unexpected error: {err}" ); + assert!( + !err.requires_manual_rebuild(), + "TOCTOU reorg must be retried rather than marking index unavailable" + ); + // Must not have spliced B5 onto A4. + let db = handle.db().unwrap(); + assert_eq!(db.indexed_to().unwrap(), Some(4)); + assert_eq!(db.indexed_block_hash(4).unwrap(), Some(old_block4_hash)); + assert_eq!(db.indexed_block_hash(5).unwrap(), None); - // Initial backfill + live commit notifies watchers with cursor height. + // Next turn reconciles away A4 and indexes B4..=B5 cleanly. runtime.synchronize_once(false).unwrap(); - rx.changed().await.unwrap(); + assert_eq!(handle.phase(), ReferenceIndexPhase::Live); + assert_eq!(db.indexed_to().unwrap(), Some(5)); assert_eq!( - *rx.borrow(), - ReferenceIndexProgress { - phase: ReferenceIndexPhase::Live, - indexed_to: Some(9), - unavailable: false, - } + db.indexed_block_hash(4).unwrap(), + base.canonical_hash(4).unwrap() ); - - // Transition to Deferred notifies watchers while preserving cursor height. - runtime.synchronize_once(true).unwrap(); - rx.changed().await.unwrap(); assert_eq!( - *rx.borrow(), - ReferenceIndexProgress { - phase: ReferenceIndexPhase::Deferred, - indexed_to: Some(9), - unavailable: false, - } + db.indexed_block_hash(5).unwrap(), + base.canonical_hash(5).unwrap() ); + assert_ne!(db.indexed_block_hash(4).unwrap(), Some(old_block4_hash)); + } - // Unrecoverable reorg notifies watchers with Unavailable. - chain.replace_suffix(0); - let _ = runtime.synchronize_once(false).unwrap_err(); - rx.changed().await.unwrap(); - assert_eq!( - *rx.borrow(), - ReferenceIndexProgress { - phase: ReferenceIndexPhase::Unavailable, - indexed_to: Some(9), - unavailable: true, + #[derive(Clone, Debug)] + struct BrokenParentBatchChain(TestChain); + + impl CanonicalChain for BrokenParentBatchChain { + fn head(&self) -> Result { + self.0.head() + } + + fn canonical_hash(&self, number: u64) -> Result, ReferenceIndexError> { + self.0.canonical_hash(number) + } + + fn block_timestamp(&self, number: u64) -> Result, ReferenceIndexError> { + self.0.block_timestamp(number) + } + + fn finalized_block_number(&self) -> Result, ReferenceIndexError> { + self.0.finalized_block_number() + } + + fn canonical_blocks( + &self, + range: RangeInclusive, + ) -> Result, ReferenceIndexError> { + let mut blocks = self.0.canonical_blocks(range)?; + if let Some(second) = blocks.get_mut(1) { + second.parent_hash = B256::repeat_byte(0xee); } - ); + Ok(blocks) + } + } - // Dropping the runtime drops the exclusive watch sender and wakes waiters immediately. - drop(runtime); - assert!(rx.changed().await.is_err()); + #[test] + fn intra_batch_parent_hash_mismatch_aborts_without_committing() { + let dir = tempfile::tempdir().unwrap(); + let chain = BrokenParentBatchChain(TestChain::linear(4, 200)); + let config = ReferenceIndexConfig::new(dir.path(), 2818, B256::ZERO, 200); + let (mut runtime, handle) = ReferenceIndexRuntime::new(config, chain); + + let err = runtime.synchronize_once(false).unwrap_err(); + assert!( + err.to_string().contains("parent hash mismatch"), + "unexpected error: {err}" + ); + assert_eq!(handle.phase(), ReferenceIndexPhase::Backfill); + assert_eq!(handle.db().unwrap().indexed_to().unwrap(), None); } } diff --git a/crates/reference-index/src/source.rs b/crates/reference-index/src/source.rs index bce30d79..f13f34ef 100644 --- a/crates/reference-index/src/source.rs +++ b/crates/reference-index/src/source.rs @@ -16,6 +16,8 @@ pub struct CanonicalBlock { pub number: u64, /// Header hash observed for this canonical block. pub hash: B256, + /// Parent header hash observed for this canonical block. + pub parent_hash: B256, /// Header timestamp. pub timestamp: u64, /// Transactions in their canonical block order. @@ -86,10 +88,12 @@ where .map(|block| { let number = block.header.number(); let timestamp = block.header.timestamp(); + let parent_hash = block.header.parent_hash(); let hash = block.header.hash_slow(); Ok(CanonicalBlock { number, hash, + parent_hash, timestamp, transactions: block.body.transactions, }) diff --git a/crates/revm/src/handler.rs b/crates/revm/src/handler.rs index c1d10e6f..d02a4cfb 100644 --- a/crates/revm/src/handler.rs +++ b/crates/revm/src/handler.rs @@ -109,6 +109,9 @@ fn build_registry(eip7702: bool) -> TxRegistry, tx: &MorphTxEnv) -> bool { + !host.feature(EvmFeatures::EIP3607) + && tx.rlp_bytes.as_ref().is_none_or(|bytes| bytes.is_empty()) +} + /// Fetches the L1 data fee parameters for this transaction and prices it. /// /// Must NOT use a per-block cache because the oracle can be updated by a regular transaction /// (from the external gas-oracle service) within the same block. Subsequent user txs must see /// the updated fee parameters, matching go-ethereum's per-tx `L1BlockInfo` read. fn l1_data_fee(host: &mut MorphEvm<'_>, tx: &MorphTxEnv) -> HandlerResult { + if is_unencoded_rpc_simulation(host, tx) { + return Ok(U256::ZERO); + } let hardfork = host.config_spec_id(); let state = host.state_mut(); let l1_block_info = L1BlockInfo::try_fetch_with( @@ -628,6 +651,7 @@ fn deduct_token_fee( Ok(ChargedFee { l1_data_fee, token_fee: Some(AppliedTokenFee { + token_id, info: token_fee_info, rounding_credit, refund_counter, @@ -662,8 +686,10 @@ fn cool_loaded_state(state: &mut State<'_>) { /// Reimburse unused gas fees in ERC20 tokens. /// -/// Uses the token data cached from the deduction phase to ensure a consistent -/// price_ratio/scale, matching go-ethereum's `st.feeRate`/`st.tokenScale`. +/// Uses the exchange rate (`price_ratio`/`scale`) cached from the deduction phase +/// (matching go-ethereum's `st.feeRate`/`st.tokenScale`), while reloading the live +/// `(token_address, balance_slot)` routing target from `L2TokenRegistry` so mid-transaction +/// registry updates match go-ethereum's `refundGas()` (`[MR-03]`). fn reimburse_token_fee( host: &mut MorphEvm<'_>, caller: Address, @@ -674,6 +700,7 @@ fn reimburse_token_fee( let beneficiary = host.block().beneficiary; let hardfork = host.config_spec_id(); let AppliedTokenFee { + token_id, info, rounding_credit, .. @@ -703,15 +730,27 @@ fn reimburse_token_fee( return Ok(()); } + // Reload the live `(token_address, balance_slot)` from `L2TokenRegistry` without + // re-checking `is_active` (matching go-ethereum's `fees.GetTokenInfo` inside `refundGas`). + let state = host.state_mut(); + let Some((live_token_address, live_balance_slot)) = + TokenRegistryEntry::load_transfer_target_with( + |address, slot| state.storage_slot_untracked(&address, &slot), + token_id, + )? + else { + return Ok(()); + }; + // Attempt token refund. Matches go-ethereum's refundGas() which silently logs // and continues on failure: "Continue execution even if refund fails - refund // should not cause transaction to fail" (state_transition.go:698). - let refund_result = if let Some(balance_slot) = info.balance_slot { + let refund_result = if let Some(balance_slot) = live_balance_slot { transfer_erc20_with_slot( host, beneficiary, caller, - info.token_address, + live_token_address, token_amount_required, balance_slot, ) @@ -720,7 +759,7 @@ fn reimburse_token_fee( host, beneficiary, caller, - info.token_address, + live_token_address, token_amount_required, None, ) @@ -735,7 +774,7 @@ fn reimburse_token_fee( } tracing::error!( target: "morph::evm", - token = %info.token_address, + token = %live_token_address, %err, "failed to refund alt token gas, continuing execution" ); @@ -1173,6 +1212,7 @@ mod tests { U256::from(1), 1_000, AppliedTokenFee { + token_id: 1, info: TokenFeeInfo { token_address: REFUND_PROBE_TOKEN, is_active: true, @@ -1192,6 +1232,14 @@ mod tests { fn token_db_with_code(code: Bytes) -> InMemoryDB { let mut inner = InMemoryDB::default(); insert_contract(&mut inner, REFUND_PROBE_TOKEN, code); + let mut token_id_bytes = [0u8; 32]; + token_id_bytes[30..32].copy_from_slice(&1u16.to_be_bytes()); + let base = crate::token_fee::compute_mapping_slot(U256::from(151), &token_id_bytes); + inner.insert_account_storage( + &crate::token_fee::L2_TOKEN_REGISTRY_ADDRESS, + &base, + &U256::from_be_bytes(REFUND_PROBE_TOKEN.into_word().0), + ); inner } @@ -3450,6 +3498,7 @@ mod refund_rounding_tests { fn evm_after_deduction(spec: MorphHardfork) -> MorphEvm<'static> { let mut db = InMemoryDB::default(); db.insert_account_info(&TOKEN, AccountInfo::default()); + register_slot_mode_token(&mut db); db.insert_account_storage(&TOKEN, &slot_of(BENEFICIARY), &U256::from(VAULT_BALANCE)); db.insert_account_storage(&TOKEN, &slot_of(CALLER), &U256::ZERO); @@ -3472,6 +3521,7 @@ mod refund_rounding_tests { U256::from(1), gas_left, AppliedTokenFee { + token_id: FEE_TOKEN_ID, info: TokenFeeInfo { token_address: TOKEN, is_active: true, @@ -3647,6 +3697,7 @@ mod refund_rounding_tests { gas_price, unused_gas, AppliedTokenFee { + token_id: FEE_TOKEN_ID, info: TokenFeeInfo { token_address: TOKEN, is_active: true, @@ -3919,4 +3970,265 @@ mod refund_rounding_tests { let evm_no_prio_check = morph_evm(InMemoryDB::default(), env); assert!(validate_env(&evm_no_prio_check, &high_tip_tx).is_ok()); } + + #[test] + fn unencoded_rpc_simulation_charges_zero_l1_fee_only_when_eip3607_disabled() { + use crate::l1block::{ + GPO_BLOB_SCALAR_SLOT, GPO_COMMIT_SCALAR_SLOT, GPO_IS_CURIE_SLOT, GPO_L1_BASE_FEE_SLOT, + GPO_L1_BLOB_BASE_FEE_SLOT, L1_GAS_PRICE_ORACLE_ADDRESS, + }; + + let mut db = InMemoryDB::default(); + db.insert_account_storage( + &L1_GAS_PRICE_ORACLE_ADDRESS, + &GPO_L1_BASE_FEE_SLOT, + &U256::from(10_000_000_000u64), + ); + db.insert_account_storage( + &L1_GAS_PRICE_ORACLE_ADDRESS, + &GPO_L1_BLOB_BASE_FEE_SLOT, + &U256::from(5_000_000_000u64), + ); + db.insert_account_storage( + &L1_GAS_PRICE_ORACLE_ADDRESS, + &GPO_COMMIT_SCALAR_SLOT, + &U256::from(230_760_020_821u64), + ); + db.insert_account_storage( + &L1_GAS_PRICE_ORACLE_ADDRESS, + &GPO_BLOB_SCALAR_SLOT, + &U256::from(417_565_260u64), + ); + db.insert_account_storage( + &L1_GAS_PRICE_ORACLE_ADDRESS, + &GPO_IS_CURIE_SLOT, + &U256::from(1u64), + ); + + let unencoded_tx = MorphTxEnv { + rlp_bytes: Some(Bytes::new()), + ..Default::default() + }; + + // Consensus (`EIP3607` enabled): even an empty rlp_bytes still charges Curie commit fee. + let mut consensus_evm = morph_evm( + db.clone(), + morph_evm_env(MorphHardfork::Celadon, 1, 30_000_000, block()), + ); + assert!(l1_data_fee(&mut consensus_evm, &unencoded_tx).unwrap() > U256::ZERO); + + // RPC `validation: false` simulation (`!EIP3607` and empty `rlp_bytes`): zero L1 fee. + let mut sim_env = morph_evm_env(MorphHardfork::Celadon, 1, 30_000_000, block()); + sim_env.version.features.remove(EvmFeatures::EIP3607); + let mut sim_evm = morph_evm(db, sim_env); + assert_eq!( + l1_data_fee(&mut sim_evm, &unencoded_tx).unwrap(), + U256::ZERO + ); + } + + /// `[MR-03]` When the main transaction frame updates `L2TokenRegistry` for its own + /// `fee_token_id`, `reimburse_token_fee` must reload the live `(token_address, balance_slot)` + /// target while preserving the deduction-time `price_ratio` and `scale` (and skipping + /// reimbursement cleanly if `token_address` was cleared to zero). + #[test] + fn reimburse_token_fee_reloads_live_registry_target_and_keeps_charged_rate() { + use crate::token_fee::{L2_TOKEN_REGISTRY_ADDRESS, compute_mapping_slot}; + use alloy_consensus::transaction::Recovered; + use alloy_primitives::bytes; + use evm2::evm::AccountInfo; + + const TOKEN_ID: u16 = 1; + let caller = address!("1000000000000000000000000000000000000011"); + let fee_vault = address!("530000000000000000000000000000000000000a"); + let token_a = address!("53000000000000000000000000000000000000a1"); + let token_b = address!("53000000000000000000000000000000000000b2"); + + let mut token_key = [0u8; 32]; + token_key[30..32].copy_from_slice(&TOKEN_ID.to_be_bytes()); + let reg_base = compute_mapping_slot(U256::from(151u64), &token_key); + let price_slot = compute_mapping_slot(U256::from(153u64), &token_key); + + let addr_word = |addr: Address| -> U256 { + let mut w = [0u8; 32]; + w[12..32].copy_from_slice(addr.as_slice()); + U256::from_be_bytes(w) + }; + + // Registry runtime: writes up to four `(slot, value)` pairs from calldata: + // loop over 64-byte chunks, `SSTORE(CALLDATALOAD(offset), CALLDATALOAD(offset + 32))`. + // Simpler fixed 4-write runtime (256 bytes calldata): + // 0x00: 6020 35 5f 35 55 SSTORE(cd[0], cd[32]) + // 0x06: 6060 35 6040 35 55 SSTORE(cd[64], cd[96]) + // 0x0d: 60a0 35 6080 35 55 SSTORE(cd[128], cd[160]) + // 0x14: 60e0 35 60c0 35 55 00 SSTORE(cd[192], cd[224]); STOP + let registry_writer = bytes!("6020355f35556060356040355560a0356080355560e03560c0355500"); + + // Call-mode `token_b` runtime: minimal stateful ERC-20 storing balances directly at slot + // `uint256(uint160(addr))`, handling `balanceOf(address)` (`0x70a08231`) and + // `transfer(address,uint256)` (`0xa9059cbb`, updating both balances, emitting `LOG1` + // `Transfer` with `amount`, and returning `true`). + let call_token_b_code = bytes!( + "5f355f1a607014604c57602435803354033355806004355401600435555f527fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef60205fa160015f5260205ff35b600435545f5260205ff3" + ); + + let build_base_db = || { + let mut db = InMemoryDB::default(); + db.insert_account_info( + &L2_TOKEN_REGISTRY_ADDRESS, + AccountInfo::default().with_code(Bytecode::new_legacy(registry_writer.clone())), + ); + // Initial registry state for TOKEN_ID = 1: + // - tokenAddress = token_a + // - balanceSlot raw = 1 (Slot mode at mapping slot 0) + // - decimals = 18, isActive = true (`0x1201`) + // - scale = 1, priceRatio = 2 (1 token = 2 wei) + db.insert_account_storage(&L2_TOKEN_REGISTRY_ADDRESS, ®_base, &addr_word(token_a)); + db.insert_account_storage( + &L2_TOKEN_REGISTRY_ADDRESS, + &(reg_base + U256::from(1u64)), + &U256::from(1u64), + ); + db.insert_account_storage( + &L2_TOKEN_REGISTRY_ADDRESS, + &(reg_base + U256::from(2u64)), + &U256::from(0x1201u64), + ); + db.insert_account_storage( + &L2_TOKEN_REGISTRY_ADDRESS, + &(reg_base + U256::from(3u64)), + &U256::from(1u64), + ); + db.insert_account_storage(&L2_TOKEN_REGISTRY_ADDRESS, &price_slot, &U256::from(2u64)); + + // Fund caller with 1_000_000 units in `token_a` slot-0 mapping. + let caller_slot_a = compute_mapping_slot_for_address(U256::ZERO, caller); + db.insert_account_storage(&token_a, &caller_slot_a, &U256::from(1_000_000u64)); + db.insert_account_info( + &token_b, + AccountInfo::default().with_code(Bytecode::new_legacy(call_token_b_code.clone())), + ); + // Seed `fee_vault` on `token_b` so Call-mode reimbursement can transfer from vault -> caller. + db.insert_account_storage(&token_b, &addr_word(fee_vault), &U256::from(1_000_000u64)); + db + }; + + let make_calldata = |pairs: [(U256, U256); 4]| -> Bytes { + let mut out = Vec::with_capacity(256); + for (slot, val) in pairs { + out.extend_from_slice(&slot.to_be_bytes::<32>()); + out.extend_from_slice(&val.to_be_bytes::<32>()); + } + Bytes::from(out) + }; + + let mut blk = block(); + blk.beneficiary = fee_vault; + blk.basefee = U256::from(10u64); + + // 1. Mid-tx switch from Slot-mode `token_a` to Call-mode `token_b`, while ALSO setting + // `isActive = false` and `priceRatio = 0` in storage: + // - Deduction took `ceil(200_000 * 10 * 1 / 2) = 1_000_000` from `token_a` slot 0. + // - Reimbursement must route to Call-mode `token_b` (emitting 1 `Transfer` log on + // `token_b` with the exact pre-charged rate `unused_gas * 10 / 2`, NOT touching + // `token_a`'s caller slot back above 0), and receipt `ext.token_fee_info` keeps + // the deduction-time `price_ratio = 2`. + let calldata_switch = make_calldata([ + (reg_base, addr_word(token_b)), + (reg_base + U256::from(1u64), U256::ZERO), // balanceSlot raw = 0 -> Call mode + (reg_base + U256::from(2u64), U256::from(0x1200u64)), // isActive = false + (price_slot, U256::ZERO), // priceRatio = 0 + ]); + let tx_switch = Recovered::new_unchecked( + MorphTxEnv { + tx_type: MORPH_TX_TYPE_ID, + chain_id: Some(1), + kind: TxKind::Call(L2_TOKEN_REGISTRY_ADDRESS), + gas_limit: 200_000, + gas_price: 10, + gas_priority_fee: Some(0), + data: calldata_switch, + fee_token_id: Some(TOKEN_ID), + ..Default::default() + }, + caller, + ); + let mut evm = morph_evm( + build_base_db(), + morph_evm_env(MorphHardfork::Celadon, 1, 30_000_000, blk), + ); + let result = evm + .transact(&tx_switch) + .expect("switch tx must succeed") + .commit(); + assert!(result.status); + let unused_gas = 200_000 - result.tx_gas_used(); + let expected_refund_tokens = U256::from(unused_gas) * U256::from(10u64) / U256::from(2u64); + assert!(expected_refund_tokens > U256::ZERO); + + // `token_b` emitted the Call-mode refund log with `expected_refund_tokens` and credited caller. + assert_eq!(result.logs.len(), 1); + assert_eq!(result.logs[0].address, token_b); + assert_eq!( + U256::from_be_slice(result.logs[0].data.data.as_ref()), + expected_refund_tokens + ); + assert_eq!( + evm.state_mut() + .storage_slot_untracked(&token_b, &addr_word(caller)) + .unwrap(), + expected_refund_tokens + ); + // `token_a` caller slot remains 0 (refund did NOT go back to stale `token_a`). + let caller_slot_a = compute_mapping_slot_for_address(U256::ZERO, caller); + assert_eq!( + evm.state_mut() + .storage_slot_untracked(&token_a, &caller_slot_a) + .unwrap(), + U256::ZERO + ); + assert_eq!( + result.ext.token_fee_info.unwrap().price_ratio, + U256::from(2u64) + ); + + // 2. Mid-tx clearing `tokenAddress = Address::ZERO` skips reimbursement cleanly. + let calldata_clear = make_calldata([ + (reg_base, U256::ZERO), + (reg_base + U256::from(1u64), U256::ZERO), + (reg_base + U256::from(2u64), U256::ZERO), + (price_slot, U256::ZERO), + ]); + let tx_clear = Recovered::new_unchecked( + MorphTxEnv { + tx_type: MORPH_TX_TYPE_ID, + chain_id: Some(1), + kind: TxKind::Call(L2_TOKEN_REGISTRY_ADDRESS), + gas_limit: 200_000, + gas_price: 10, + gas_priority_fee: Some(0), + data: calldata_clear, + fee_token_id: Some(TOKEN_ID), + ..Default::default() + }, + caller, + ); + let mut evm_clear = morph_evm( + build_base_db(), + morph_evm_env(MorphHardfork::Celadon, 1, 30_000_000, blk), + ); + let clear_res = evm_clear + .transact(&tx_clear) + .expect("clearing tokenAddress mid-tx must not fail tx") + .commit(); + assert!(clear_res.status); + assert!(clear_res.logs.is_empty()); + assert_eq!( + evm_clear + .state_mut() + .storage_slot_untracked(&token_a, &caller_slot_a) + .unwrap(), + U256::ZERO + ); + } } diff --git a/crates/revm/src/lib.rs b/crates/revm/src/lib.rs index 65444a9f..ac64fed2 100644 --- a/crates/revm/src/lib.rs +++ b/crates/revm/src/lib.rs @@ -67,4 +67,4 @@ pub use token_fee::{ L2_TOKEN_REGISTRY_ADDRESS, TokenFeeInfo, TokenRegistryEntry, compute_mapping_slot, compute_mapping_slot_for_address, encode_balance_of_calldata, }; -pub use tx::{MorphAuthorization, MorphTxEnv, MorphTxExt}; +pub use tx::{MorphAuthorization, MorphTxEnv, MorphTxExt, encode_simulated_tx_for_l1_fee}; diff --git a/crates/revm/src/token_fee.rs b/crates/revm/src/token_fee.rs index 76b1d7ea..6a8e2360 100644 --- a/crates/revm/src/token_fee.rs +++ b/crates/revm/src/token_fee.rs @@ -106,6 +106,37 @@ impl TokenRegistryEntry { read_registry_entry(read, token_id) } + /// Load only the live `(token_address, balance_slot)` routing target for `token_id` + /// without checking `is_active` or reloading `price_ratio` / `scale`. + /// + /// Used during post-execution unused-gas reimbursement (`refundGas` in `morph-geth`): + /// if the main transaction frame updated `L2TokenRegistry` (`tokenAddress` or + /// `balanceSlot`), reimbursement routes to the live target while keeping the + /// deduction-time `price_ratio` and `scale` (returning `Ok(None)` when `tokenAddress == 0`). + pub fn load_transfer_target_with( + mut read: impl FnMut(Address, U256) -> Result, + token_id: u16, + ) -> Result)>, E> { + let mut token_id_bytes = [0u8; 32]; + token_id_bytes[30..32].copy_from_slice(&token_id.to_be_bytes()); + let base = compute_mapping_slot(TOKEN_REGISTRY_SLOT, &token_id_bytes); + + let slot_0 = read(L2_TOKEN_REGISTRY_ADDRESS, base)?; + let token_address = Address::from_word(slot_0.into()); + if token_address == Address::default() { + return Ok(None); + } + + let balance_slot_raw = read(L2_TOKEN_REGISTRY_ADDRESS, base + U256::from(1))?; + let balance_slot = if !balance_slot_raw.is_zero() { + Some(balance_slot_raw.saturating_sub(U256::from(1))) + } else { + None + }; + + Ok(Some((token_address, balance_slot))) + } + /// Reject registry entries that cannot produce a valid token-denominated fee. pub fn ensure_usable(self, token_id: u16) -> Result { if !self.is_active { diff --git a/crates/revm/src/tx.rs b/crates/revm/src/tx.rs index 69fa402d..add3032b 100644 --- a/crates/revm/src/tx.rs +++ b/crates/revm/src/tx.rs @@ -4,7 +4,7 @@ //! every transaction type, with token-fee fields where they apply. use alloy_consensus::{ - SignableTransaction, Transaction as AlloyTransaction, transaction::Recovered, + SignableTransaction, Signed, Transaction as AlloyTransaction, transaction::Recovered, }; use alloy_eips::{ Typed2718, @@ -25,6 +25,52 @@ const LEGACY_TX_TYPE: u8 = 0x00; /// EIP-2718 type byte of an EIP-2930 transaction. const EIP2930_TX_TYPE: u8 = 0x01; +/// Encodes a simulated transaction with a full-size placeholder signature for L1 +/// data fee sizing, without mutating the transaction itself. +/// +/// `TryIntoSimTx` attaches `Signature::new(U256::ZERO, U256::ZERO, false)` (3 RLP +/// bytes instead of 67 bytes) so `returnFullTransactions: true` exposes zero +/// `r`/`s`/`v` per the Ethereum `eth_simulateV1` spec. Using the same 64-byte +/// `0xff` + `yParity = 1` placeholder as [`MorphTxEnv::encode_for_l1_fee`] sizes the +/// L1 fee like a real signed transaction while keeping `tx`'s zero signature intact. +/// +/// The envelope type is kept as simulated, so a legacy or EIP-2930 call is priced as +/// that type. `eth_estimateGas` instead always sizes an EIP-1559, EIP-7702 or MorphTx +/// envelope (as geth does once a base fee exists), so for those two types the L1 fees +/// differ by the few bytes between the encodings. +pub fn encode_simulated_tx_for_l1_fee(tx: &MorphTxEnvelope) -> Bytes { + let placeholder_sig = Signature::new(U256::MAX, U256::MAX, true); + let envelope = match tx { + MorphTxEnvelope::Legacy(s) => MorphTxEnvelope::Legacy(Signed::new_unchecked( + s.tx().clone(), + placeholder_sig, + B256::ZERO, + )), + MorphTxEnvelope::Eip2930(s) => MorphTxEnvelope::Eip2930(Signed::new_unchecked( + s.tx().clone(), + placeholder_sig, + B256::ZERO, + )), + MorphTxEnvelope::Eip1559(s) => MorphTxEnvelope::Eip1559(Signed::new_unchecked( + s.tx().clone(), + placeholder_sig, + B256::ZERO, + )), + MorphTxEnvelope::Eip7702(s) => MorphTxEnvelope::Eip7702(Signed::new_unchecked( + s.tx().clone(), + placeholder_sig, + B256::ZERO, + )), + MorphTxEnvelope::Morph(s) => MorphTxEnvelope::Morph(Signed::new_unchecked( + s.tx().clone(), + placeholder_sig, + B256::ZERO, + )), + MorphTxEnvelope::L1Msg(_) => return tx.encoded_2718().into(), + }; + envelope.encoded_2718().into() +} + /// Owned EIP-7702 authorization stored in [`MorphTxEnv`]. #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub enum MorphAuthorization { @@ -1023,4 +1069,172 @@ mod tests { other => panic!("expected a recovered authorization, got {other:?}"), } } + + #[test] + fn encode_simulated_tx_for_l1_fee_uses_full_placeholder_sig_without_mutating_tx() { + use alloy_consensus::{TxEip1559, TxEip2930, TxEip7702, TxLegacy}; + use alloy_eips::{ + eip2718::Decodable2718, + eip7702::{Authorization, SignedAuthorization}, + }; + use alloy_primitives::{Sealed, address}; + use morph_primitives::TxL1Msg; + + let chain_id = 2818u64; + let to = address!("0000000000000000000000000000000000000002"); + let input = Bytes::from(vec![0xab; 64]); + let zero_sig = Signature::new(U256::ZERO, U256::ZERO, false); + let placeholder_sig = Signature::new(U256::MAX, U256::MAX, true); + let auth: SignedAuthorization = Authorization { + chain_id: U256::from(chain_id), + address: address!("0000000000000000000000000000000000000042"), + nonce: 1, + } + .into_signed(Signature::new(U256::from(1u64), U256::from(2u64), true)); + let sig_of = |env: &MorphTxEnvelope| match env { + MorphTxEnvelope::Legacy(s) => Some(*s.signature()), + MorphTxEnvelope::Eip2930(s) => Some(*s.signature()), + MorphTxEnvelope::Eip1559(s) => Some(*s.signature()), + MorphTxEnvelope::Eip7702(s) => Some(*s.signature()), + MorphTxEnvelope::Morph(s) => Some(*s.signature()), + MorphTxEnvelope::L1Msg(_) => None, + }; + + let cases = [ + ( + "legacy", + MorphTxEnvelope::Legacy(Signed::new_unchecked( + TxLegacy { + chain_id: Some(chain_id), + gas_price: 2_000_000_000, + gas_limit: 50_000, + to: TxKind::Call(to), + input: input.clone(), + ..Default::default() + }, + zero_sig, + B256::ZERO, + )), + false, + ), + ( + "eip2930", + MorphTxEnvelope::Eip2930(Signed::new_unchecked( + TxEip2930 { + chain_id, + gas_price: 2_000_000_000, + gas_limit: 50_000, + to: TxKind::Call(to), + input: input.clone(), + ..Default::default() + }, + zero_sig, + B256::ZERO, + )), + false, + ), + ( + "eip1559", + MorphTxEnvelope::Eip1559(Signed::new_unchecked( + TxEip1559 { + chain_id, + gas_limit: 50_000, + max_fee_per_gas: 2_000_000_000, + max_priority_fee_per_gas: 1_000_000_000, + to: TxKind::Call(to), + input: input.clone(), + ..Default::default() + }, + zero_sig, + B256::ZERO, + )), + true, + ), + ( + "eip7702", + MorphTxEnvelope::Eip7702(Signed::new_unchecked( + TxEip7702 { + chain_id, + gas_limit: 80_000, + max_fee_per_gas: 2_000_000_000, + max_priority_fee_per_gas: 1_000_000_000, + to, + authorization_list: vec![auth.clone()], + input: input.clone(), + ..Default::default() + }, + zero_sig, + B256::ZERO, + )), + false, + ), + ( + "morph_v1", + MorphTxEnvelope::Morph(Signed::new_unchecked( + TxMorph { + chain_id, + gas_limit: 50_000, + max_fee_per_gas: 2_000_000_000, + max_priority_fee_per_gas: 1_000_000_000, + to: TxKind::Call(to), + input: input.clone(), + fee_token_id: 1, + fee_limit: U256::from(10_000u64), + version: MORPH_TX_VERSION_1, + ..Default::default() + }, + zero_sig, + B256::ZERO, + )), + true, + ), + ( + "morph_v2", + MorphTxEnvelope::Morph(Signed::new_unchecked( + TxMorph { + chain_id, + gas_limit: 80_000, + max_fee_per_gas: 2_000_000_000, + max_priority_fee_per_gas: 1_000_000_000, + to: TxKind::Call(to), + input: input.clone(), + fee_token_id: 1, + version: MORPH_TX_VERSION_2, + authorization_list: vec![auth], + ..Default::default() + }, + zero_sig, + B256::ZERO, + )), + false, + ), + ]; + + for (label, tx, compare_tx_env) in cases { + let sized = encode_simulated_tx_for_l1_fee(&tx); + assert_eq!(sized.len(), tx.encoded_2718().len() + 64, "{label}"); + let decoded = MorphTxEnvelope::decode_2718(&mut sized.as_ref()).unwrap(); + assert_eq!(sig_of(&decoded), Some(placeholder_sig), "{label}"); + assert_eq!(sig_of(&tx), Some(zero_sig), "{label}"); + if compare_tx_env { + let env_encoded = MorphTxEnv::from_envelope(&tx).encode_for_l1_fee(chain_id); + assert_eq!(sized, env_encoded, "{label}"); + } + } + + let l1_msg = MorphTxEnvelope::L1Msg(Sealed::new_unchecked( + TxL1Msg { + queue_index: 1, + gas_limit: 50_000, + to, + input, + ..Default::default() + }, + B256::ZERO, + )); + assert_eq!( + encode_simulated_tx_for_l1_fee(&l1_msg), + Bytes::from(l1_msg.encoded_2718()) + ); + } } diff --git a/crates/rpc/Cargo.toml b/crates/rpc/Cargo.toml index fa8e54e0..2b4d6fe8 100644 --- a/crates/rpc/Cargo.toml +++ b/crates/rpc/Cargo.toml @@ -33,7 +33,6 @@ reth-rpc-server-types.workspace = true reth-metrics.workspace = true metrics.workspace = true reth-evm = { workspace = true, features = ["std", "witness"] } -reth-execution-types.workspace = true reth-provider.workspace = true reth-storage-api.workspace = true reth-tasks.workspace = true @@ -60,7 +59,6 @@ serde.workspace = true derive_more.workspace = true tokio.workspace = true evm2 = { workspace = true, features = ["std"] } -evm2-inspectors = { workspace = true, features = ["std"] } # Error handling thiserror.workspace = true diff --git a/crates/rpc/src/eth/call.rs b/crates/rpc/src/eth/call.rs index 06005ffb..f0150013 100644 --- a/crates/rpc/src/eth/call.rs +++ b/crates/rpc/src/eth/call.rs @@ -1,82 +1,71 @@ //! Morph `eth_call` / `eth_estimateGas` / `eth_simulateV1` overrides. //! -//! [`Call::caller_gas_allowance`] is overridden so `eth_estimateGas` caps -//! gas by `balance − value − l1_fee` (ETH path) or the fee token balance -//! (MorphTx `fee_token_id > 0`). `eth_call` and `eth_createAccessList` -//! are detected by the block gas limit check being disabled and keep the -//! plain ETH allowance, without the L1-fee extension. -//! -//! [`EstimateCall::estimate_gas_with`] is also overridden to fix three -//! upstream estimation defects: -//! 1. Cap balance allowance using `tx_env.gas_price` (`maxFeePerGas` for -//! dynamic-fee requests) instead of `effective_gas_price`. -//! 2. Guard the `is_basic_transfer` 21,000-gas shortcut with -//! `highest_gas_limit >= MIN_TRANSACTION_GAS` so sub-21k allowances or -//! explicit `gas < 21_000` cannot bypass the cap. -//! 3. Retry at `max_gas_limit` on revert / gas-too-high whenever -//! `highest_gas_limit < max_gas_limit`, covering EIP-1559 and MorphTx -//! requests whose legacy `gasPrice` field is absent. -//! -//! [`EthCall::simulate_v1`] is overridden so `eth_simulateV1` disables fee -//! charging (including Morph's non-zero L1 data fee) when `validation: false` -//! and passes each transaction's real EIP-2718 encoding when `validation: true` -//! so Curie `commit + blob` (and pre-Curie calldata) L1 fees are accurately -//! charged and validated. - -use crate::MorphEthApiError; -use crate::eth::{MorphEthApi, MorphNodeCore}; -use alloy_consensus::BlockHeader; -use alloy_eips::eip2718::{Encodable2718, WithEncoded}; +//! - [`EthCall::simulate_v1`] normalizes calls that combine Morph fields with +//! legacy `gasPrice` and delegates execution to the inner upstream +//! [`EthCall::simulate_v1`]; Morph L1 fee pricing is handled in +//! [`morph_evm::MorphBlockExecutor`] (`validation: true` placeholder encoding) +//! and `morph_revm` (`validation: false` empty envelope priced at zero L1 fee). +//! - [`EstimateCall::estimate_gas_with`] replaces `MorphEvmConfig::evm_env`'s +//! `tx_gas_limit_cap = header.gas_limit()` with `--rpc.gascap` (`0` = +//! unlimited) before applying block overrides so `blockOverrides.gasLimit` +//! values above `header.gas_limit()` take effect, while fixing three upstream +//! estimation defects: +//! 1. Cap balance allowance using `tx_env.gas_price` (`maxFeePerGas` for +//! dynamic-fee requests) instead of `effective_gas_price`. +//! 2. Guard the `is_basic_transfer` 21,000-gas shortcut with +//! `highest_gas_limit >= MIN_TRANSACTION_GAS` so sub-21k allowances or +//! explicit `gas < 21_000` cannot bypass the cap. +//! 3. Retry at `max_gas_limit` on revert / gas-too-high whenever +//! `highest_gas_limit < max_gas_limit`, covering EIP-1559 and MorphTx +//! requests whose legacy `gasPrice` field is absent. +//! - [`Call::caller_gas_allowance`] caps `eth_estimateGas` by +//! `balance − value − l1_fee` (ETH path) or a token-denominated limit +//! (MorphTx `fee_token_id > 0`), clamped to `call_gas_limit()` when non-zero. +//! `eth_call` and sibling call/trace RPCs (`!BLOCK_GAS_LIMIT_CHECK`) skip the +//! L1-fee extension and likewise clamp to `call_gas_limit()` when non-zero. + +use crate::eth::{MorphEthApi, MorphNodeCore, transaction::normalize_simulate_call}; +use crate::{MorphEthApiError, MorphTransactionRequest}; use alloy_network::TransactionBuilder; -use alloy_primitives::{Address, B256, TxKind, U256, U512}; -use alloy_rpc_types_eth::{ - BlockId, - simulate::{SimBlock, SimulatePayload, SimulatedBlock}, - state::EvmOverrides, -}; +use alloy_primitives::{Address, Bytes, TxKind, U256, U512}; +use alloy_rpc_types_eth::{BlockId, simulate::SimulatePayload, state::EvmOverrides}; use evm2::{ EvmFeatures, TxResult, - bytecode::Bytecode, - evm::{AccountInfo, CacheDB, Db}, - interpreter::{InstrStop, Word}, + evm::{CacheDB, Db}, + interpreter::InstrStop, registry::HandlerError, }; -use evm2_inspectors::transfer::TransferInspector; use morph_chainspec::{MorphChainSpec, MorphHardforks}; -use morph_revm::{L1BlockInfo, MorphEvmEnv, MorphTxExt, TokenFeeInfo}; -use reth_chainspec::{EthChainSpec, EthereumHardforks, MIN_TRANSACTION_GAS}; -use reth_errors::{ProviderError, RethError}; +use morph_revm::{ + L1BlockInfo, MorphEvmEnv, MorphTxEnv, MorphTxExt, TokenFeeInfo, TokenRegistryEntry, +}; +use reth_chainspec::MIN_TRANSACTION_GAS; +use reth_errors::ProviderError; use reth_evm::{ - BlockExecutionError, BundleState, ConfigureEvm, Database, Evm, EvmEnv, EvmEnvFor, EvmTypesFor, - TransactionEnvMut, TxEnvFor, + ConfigureEvm, Database, Evm, EvmEnv, EvmEnvFor, EvmTypesFor, TransactionEnvMut, TxEnvFor, database::StateProviderDatabase, - execute::{ - BlockBuilder, BlockBuilderOutcome, BlockExecutor, BlockTransactionResult, - map_database_error, - }, }; -use reth_execution_types::BundleSource; -use reth_primitives_traits::NodePrimitives; use reth_provider::ChainSpecProvider; use reth_rpc_convert::{RpcConvert, RpcTxReq}; use reth_rpc_eth_api::{ - AsEthApiError, EthApiTypes, FromEthApiError, FromEvmError, IntoEthApiError, RpcBlock, - RpcNodeCore, + AsEthApiError, EthApiTypes, FromEthApiError, FromEvmError, IntoEthApiError, RpcNodeCore, + RpcTypes, helpers::{ - Call, EthCall, LoadBlock, LoadPendingBlock, SpawnBlocking, + Call, EthCall, call::SimulatedBlocksResult, estimate::{EstimateCall, update_estimated_gas_range}, }, }; use reth_rpc_eth_types::{ EthApiError, RpcInvalidTransactionError, - cache::db::{apply_block_overrides, apply_state_overrides, apply_state_overrides_with_state}, + cache::db::{apply_block_overrides, apply_state_overrides}, error::api::{FromEvmHalt, FromRevert}, - simulate::{self, EthSimulateError, SimulatedState}, + simulate::EthSimulateError, }; use reth_rpc_server_types::constants::gas_oracle::{CALL_STIPEND_GAS, ESTIMATE_GAS_ERROR_RATIO}; -use reth_storage_api::{EvmStateProvider, StateProvider, noop::NoopProvider}; +use reth_storage_api::EvmStateProvider; use reth_tasks::cancel::is_cancelled; +use std::borrow::Cow; use tracing::trace; impl EthCall for MorphEthApi @@ -85,398 +74,29 @@ where N::Provider: ChainSpecProvider, Rpc: reth_rpc_convert::RpcConvert, + Rpc::Network: RpcTypes, MorphEthApiError: reth_rpc_eth_types::error::FromEvmError, { async fn simulate_v1( &self, - payload: SimulatePayload::Network>>, + mut payload: SimulatePayload::Network>>, block: Option, ) -> SimulatedBlocksResult { if payload.block_state_calls.len() > self.max_simulate_blocks() as usize { return Err(EthApiError::other(EthSimulateError::TooManyBlocks).into()); } - - let block = block.unwrap_or_default(); - - let SimulatePayload { - block_state_calls, - trace_transfers, - validation, - return_full_transactions, - } = payload; - - if block_state_calls.is_empty() { - return Err(EthApiError::InvalidParams(String::from("calls are empty.")).into()); + for sim_block in &mut payload.block_state_calls { + sim_block.calls = std::mem::take(&mut sim_block.calls) + .into_iter() + .map(normalize_simulate_call) + .collect::, _>>() + .map_err(Self::Error::from_eth_err)?; } - - let permit = self - .acquire_owned_blocking_io() + self.eth_api() + .simulate_v1(payload, block) .await - .map_err(|_| EthApiError::InternalEthError)?; - - let base_block = self - .recovered_block(block) - .await? - .ok_or_else(|| EthApiError::other(EthSimulateError::BlockNotFound { block }))?; - let parent = base_block.sealed_header().clone(); - let max_simulate_blocks = self.max_simulate_blocks(); - let state_at = if block.is_pending() { - block - } else { - parent.hash().into() - }; - - self.spawn_with_state_at_block(state_at, move |this, db| { - let _permit = permit; - let state_provider = db.db.into_inner().into_inner().0; - let mut db = CacheDB::new(Db::new(StateProviderDatabase::new( - (&state_provider).into_evm_state_provider(), - ))); - let mut parent = parent; - let mut simulation_state = this - .compute_state_root_for_eth_simulate() - .then(SimulatedState::default); - - let chain_id = this.provider().chain_spec().chain_id(); - - let block_state_calls = simulate::sanitize_chain( - block_state_calls, - &parent, - chain_id, - max_simulate_blocks, - )?; - - let mut blocks: Vec>> = - Vec::with_capacity(block_state_calls.len()); - - let call_gas_limit = this.call_gas_limit(); - let mut remaining_call_gas_limit = (call_gas_limit > 0).then_some(call_gas_limit); - - for block in block_state_calls { - let SimBlock { - block_overrides, - state_overrides, - calls, - } = block; - - let attributes = this - .pending_env_builder() - .pending_env_attributes(&parent, block_overrides.as_ref()) - .map_err(Self::Error::from_eth_err)?; - - let mut evm_env = this - .evm_config() - .next_evm_env(&parent, &attributes) - .map_err(RethError::other) - .map_err(Self::Error::from_eth_err)?; - - // Always disable EIP-3607 - evm_env.version_mut().features.remove(EvmFeatures::EIP3607); - - if !validation || !evm_env.version().feature(EvmFeatures::EIP8037) { - evm_env.version_mut().tx_gas_limit_cap = u64::MAX; - } - - if !validation { - // If not explicitly required, disable nonce check, basefee check, and - // fee charging (including Morph's non-zero L1 data fee and token fees) - // so zero-balance callers succeed and no phantom fees are debited/credited. - evm_env - .version_mut() - .features - .remove(EvmFeatures::NONCE_CHECK); - evm_env - .version_mut() - .features - .remove(EvmFeatures::BASE_FEE_CHECK); - evm_env - .version_mut() - .features - .remove(EvmFeatures::FEE_CHARGE); - evm_env.block_env_mut().basefee = U256::ZERO; - } - - evm_env.block_env_mut().prevrandao = U256::ZERO; - if !this - .provider() - .chain_spec() - .is_paris_active_at_block(evm_env.block_env().number.to()) - { - evm_env.block_env_mut().difficulty = parent.difficulty(); - } - - if let Some(block_overrides) = block_overrides { - if let Some(gas_limit_override) = block_overrides.gas_limit - && gas_limit_override > evm_env.block_env().gas_limit.to::() - && gas_limit_override > this.call_gas_limit() - { - return Err(EthApiError::other(EthSimulateError::GasLimitReached).into()); - } - apply_block_overrides(block_overrides, &mut db, &mut evm_env); - } - if let Some(ref state_overrides) = state_overrides { - let mut changes = simulation_state.as_ref().map(|_| BundleState::default()); - apply_state_overrides_with_state( - state_overrides.clone(), - &mut db, - changes.as_mut(), - ) - .map_err(Self::Error::from_eth_err)?; - if let Some(simulation_state) = simulation_state.as_mut() - && let Some(changes) = changes - { - simulation_state - .extend(&state_provider, &changes) - .map_err(Self::Error::from_eth_err)?; - } - } - - let chain_id = evm_env.chain_id(); - let build_bal = this - .provider() - .chain_spec() - .is_amsterdam_active_at_timestamp(evm_env.block_env().timestamp.to::()); - - let ctx = this - .evm_config() - .context_for_next_block(&parent, attributes) - .map_err(RethError::other) - .map_err(Self::Error::from_eth_err)?; - let map_err = |e: EthApiError| -> Self::Error { - match e.as_simulate_error() { - Some(sim_err) => Self::Error::from_eth_err(EthApiError::other(sim_err)), - None => Self::Error::from_eth_err(e), - } - }; - - // EIP-7708 already emits transfer logs: https://eips.ethereum.org/EIPS/eip-7708 - let trace_transfers = - trace_transfers && !evm_env.version().feature(EvmFeatures::EIP7708); - let mut evm = this.evm_config().evm_with_env(&mut db, evm_env.clone()); - if trace_transfers { - evm.set_inspector(TransferInspector::new(false).with_logs(true)); - } - let mut builder = this - .evm_config() - .create_block_builder(evm, evm_env, &parent, ctx); - if build_bal { - builder.executor_mut().enable_block_access_list_builder(); - } - - if let Some(ref state_overrides) = state_overrides { - simulate::apply_precompile_overrides(state_overrides, builder.evm_mut()) - .map_err(|e| Self::Error::from_eth_err(EthApiError::other(e)))?; - } - - let (result, results) = execute_simulated_transactions( - builder, - &*state_provider, - calls, - &mut remaining_call_gas_limit, - chain_id, - validation, - simulation_state.as_mut(), - this.converter(), - ) - .map_err(map_err)?; - - db.commit_source(&BundleSource(&result.execution_state)); - let simulated_header = result.block.clone_sealed_header(); - db.insert_block_hash( - &U256::from(simulated_header.number()), - &simulated_header.hash(), - ); - parent = simulated_header; - - let block = - simulate::build_simulated_block::>( - result.block, - results, - return_full_transactions.into(), - this.converter(), - )?; - - blocks.push(block); - } - - Ok(blocks) - }) - .await - } -} - -/// Adapter exposing [`Evm::account_info`] as a [`Database`] for [`simulate::resolve_transaction`]. -struct EvmAccountDb<'a, E>(&'a mut E); - -impl Database for EvmAccountDb<'_, E> { - type Error = BlockExecutionError; - - fn get_account(&mut self, address: &Address) -> Result, Self::Error> { - self.0.account_info(address) - } - - fn get_code_by_hash(&mut self, code_hash: &B256) -> Result { - self.0 - .state_db_mut() - .get_code_by_hash(code_hash) - .map_err(map_database_error) - } - - fn get_storage(&mut self, address: &Address, key: &Word) -> Result { - self.0 - .state_db_mut() - .get_storage(address, key) - .map_err(map_database_error) - } - - fn get_block_hash(&mut self, number: &Word) -> Result { - self.0 - .state_db_mut() - .get_block_hash(number) - .map_err(map_database_error) - } -} - -/// Executes simulated transactions, matching upstream `reth_rpc_eth_types::simulate::execute_transactions` -/// while preserving each transaction's real EIP-2718 encoding when `validation == true` so Morph charges -/// full Curie `commit + blob` (or pre-Curie calldata) L1 data fees. -#[expect(clippy::too_many_arguments, clippy::type_complexity)] -fn execute_simulated_transactions( - mut builder: S, - state_provider: impl StateProvider, - calls: Vec>, - remaining_call_gas_limit: &mut Option, - chain_id: u64, - validation: bool, - simulation_state: Option<&mut SimulatedState>, - converter: &T, -) -> Result<(BlockBuilderOutcome, Vec>), EthApiError> -where - S: BlockBuilder< - Primitives: NodePrimitives, - Executor: BlockExecutor>, - >, - T: RpcConvert, - EvmTypes: evm2::EvmTypes, -{ - if is_cancelled() { - return Err(EthApiError::InternalEthError); - } - builder.apply_pre_execution_changes()?; - - let mut results = Vec::with_capacity(calls.len()); - let mut cumulative_tx_gas_used: u64 = 0; - let mut block_regular_gas_used: u64 = 0; - let mut block_state_gas_used: u64 = 0; - let block_gas_limit = builder.evm_env().block_env().gas_limit.to::(); - let is_amsterdam = builder.evm_env().version().feature(EvmFeatures::EIP8037); - let tx_gas_limit_cap = builder.evm_env().version().tx_gas_limit_cap; - for mut call in calls { - if is_cancelled() { - return Err(EthApiError::InternalEthError); - } - let block_gas_remaining = if is_amsterdam { - let regular_available_gas = block_gas_limit.saturating_sub(block_regular_gas_used); - let state_available_gas = block_gas_limit.saturating_sub(block_state_gas_used); - if regular_available_gas >= tx_gas_limit_cap { - state_available_gas - } else { - regular_available_gas.min(state_available_gas) - } - } else { - block_gas_limit.saturating_sub(cumulative_tx_gas_used) - }; - let mut default_gas_limit = block_gas_remaining; - - if let Some(gas_limit) = call.as_ref().gas_limit() - && gas_limit > block_gas_remaining - { - return Err(EthApiError::other(EthSimulateError::BlockGasLimitExceeded)); - } - - if let Some(remaining_call_gas_limit) = *remaining_call_gas_limit { - if let Some(gas_limit) = call.as_ref().gas_limit() { - if gas_limit > remaining_call_gas_limit { - call.as_mut().set_gas_limit(remaining_call_gas_limit); - } - } else { - default_gas_limit = default_gas_limit.min(remaining_call_gas_limit); - } - } - - let block_base_fee = builder.evm_env().block_base_fee(); - let disable_nonce_check = !builder - .evm_env() - .version() - .feature(EvmFeatures::NONCE_CHECK); - let mut account_db = EvmAccountDb(builder.evm_mut()); - let tx = simulate::resolve_transaction( - call, - default_gas_limit, - block_base_fee, - chain_id, - disable_nonce_check, - &mut account_db, - converter, - )?; - // When `validation == true`, pass the real EIP-2718 encoding so Morph's L1 - // fee calculation charges the full commit + blob (Curie) or calldata - // (pre-Curie) fee. When `validation == false`, fee charging is disabled - // (`!EvmFeatures::FEE_CHARGE`), so an empty envelope avoids wasted encoding. - let encoded = if validation { - tx.encoded_2718().into() - } else { - Default::default() - }; - let tx = WithEncoded::new(encoded, tx); - - let mut tx_regular_gas_used = 0; - let gas_output = builder.execute_transaction_with_result_closure(tx, |output| { - let output = &output.result().result; - tx_regular_gas_used = output.execution_gas_spent(); - results.push(output.clone()) - })?; - - // The transfer tracer keeps the transaction's logs, with the synthetic transfer logs - // among them, outside the EVM's own logs. - // SAFETY: `TransferInspector` has no lifetime parameters. - if let Some(logs) = unsafe { - builder - .evm_mut() - .with_inspector(|inspector: &mut TransferInspector| inspector.take_logs()) - } && let Some(result) = results.last_mut() - { - result.logs = logs; - } - - let gas_used = gas_output.tx_gas_used(); - if let Some(remaining_call_gas_limit) = remaining_call_gas_limit.as_mut() { - if gas_used > *remaining_call_gas_limit { - return Err(EthApiError::other(EthSimulateError::GasLimitReached)); - } - *remaining_call_gas_limit -= gas_used; - } - - cumulative_tx_gas_used = cumulative_tx_gas_used.saturating_add(gas_used); - block_regular_gas_used = block_regular_gas_used.saturating_add(tx_regular_gas_used); - block_state_gas_used = block_state_gas_used.saturating_add(gas_output.state_gas_used()); + .map_err(Into::into) } - - let result = if let Some(simulation_state) = simulation_state { - builder.finish_with_state_root(&state_provider, |output| { - simulation_state - .extend(&state_provider, &output.state) - .map_err(BlockExecutionError::other)?; - state_provider - .state_root_with_updates(simulation_state.hashed_state().clone()) - .map(Some) - .map_err(BlockExecutionError::other) - })? - } else { - builder.finish(NoopProvider::default(), None)? - }; - - Ok((result, results)) } impl EstimateCall for MorphEthApi @@ -485,6 +105,7 @@ where N::Provider: ChainSpecProvider, Rpc: reth_rpc_convert::RpcConvert, + Rpc::Network: RpcTypes, MorphEthApiError: reth_rpc_eth_types::error::FromEvmError, { fn estimate_gas_with( @@ -506,6 +127,14 @@ where EvmFeatures::FEE_CHARGE | EvmFeatures::BALANCE_CHECK | EvmFeatures::BALANCE_TOP_UP, ); + // Morph does not enforce EIP-7825's 2^24 cap; `MorphEvmConfig::evm_env` seeds + // `tx_gas_limit_cap = header.gas_limit()` to neutralize Osaka's cap during block + // execution. Replacing it with `--rpc.gascap` (`0` = unlimited) before block overrides + // lets `blockOverrides.gasLimit` above the header limit take effect while bounding all + // estimation paths and diagnostic retries to `call_gas_limit()`. + let gas_cap = self.call_gas_limit(); + evm_env.version_mut().tx_gas_limit_cap = if gas_cap == 0 { u64::MAX } else { gas_cap }; + request.as_mut().take_nonce(); let tx_request_gas_limit = request.as_ref().gas_limit(); @@ -522,8 +151,6 @@ where let block_gas_limit = evm_env.block_env().gas_limit.to::(); let mut max_gas_limit = evm_env.version().tx_gas_caps().0.min(block_gas_limit); - - let gas_cap = self.call_gas_limit(); if gas_cap != 0 { max_gas_limit = max_gas_limit.min(gas_cap); } @@ -727,32 +354,35 @@ where evm_env: &EvmEnvFor<::Evm>, tx_env: &TxEnvFor<::Evm>, ) -> Result::Error> { - // eth_call / eth_createAccessList: no L1-fee cap. Token-fee callers - // can have zero ETH, so defer to the handler instead of the - // upstream ETH allowance. + // `eth_call` and sibling call/trace RPCs (`eth_callMany`, `eth_createAccessList`, + // `debug_traceCall*`, `trace_call*`) reach here via `prepare_call_env`, which disables + // `BLOCK_GAS_LIMIT_CHECK`: no L1-fee cap. Token-fee callers can hold zero ETH, so start + // from `u64::MAX`, and clamp both modes to `call_gas_limit()` when non-zero. if !evm_env .version() .feature(EvmFeatures::BLOCK_GAS_LIMIT_CHECK) { - if tx_env.fee_token_id.is_some_and(|id| id > 0) { - return Ok(u64::MAX); - } - let balance = db - .get_account(&tx_env.signer()) - .map_err(|e| MorphEthApiError::Eth(e.into()))? - .map(|account| account.balance) - .unwrap_or_default(); - let available = balance - .checked_sub(tx_env.value) - .ok_or(MorphEthApiError::InsufficientFundsForTransfer)?; - return Ok(gas_allowance_from_balance(available, tx_env.gas_price)); + let allowance = if tx_env.fee_token_id.is_some_and(|id| id > 0) { + u64::MAX + } else { + let balance = db + .get_account(&tx_env.signer()) + .map_err(|e| MorphEthApiError::Eth(e.into()))? + .map(|account| account.balance) + .unwrap_or_default(); + let available = balance + .checked_sub(tx_env.value) + .ok_or(MorphEthApiError::InsufficientFundsForTransfer)?; + gas_allowance_from_balance(available, tx_env.gas_price) + }; + return Ok(cap_call_gas_allowance(allowance, self.call_gas_limit())); } // eth_estimateGas path. let l1_fee = self.estimate_l1_fee(&mut db, evm_env, tx_env)?; - if let Some(fee_token_id) = tx_env.fee_token_id.filter(|id| *id > 0) { - return self.caller_gas_allowance_with_token( + let allowance = if let Some(fee_token_id) = tx_env.fee_token_id.filter(|id| *id > 0) { + load_caller_token_gas_allowance( &mut db, evm_env, tx_env.signer(), @@ -761,29 +391,28 @@ where fee_token_id, tx_env.fee_limit, tx_env.gas_price, - ); - } + )? + } else { + // allowance = (balance − value − l1_fee) / gas_price, done at wei + // precision so the remainder is not lost across the two + // subtractions. + let balance = db + .get_account(&tx_env.signer()) + .map_err(|e| MorphEthApiError::Eth(e.into()))? + .map(|acc| acc.balance) + .unwrap_or_default(); + let available = balance + .checked_sub(tx_env.value) + .ok_or(MorphEthApiError::InsufficientFundsForTransfer)?; + // Reject at `l1_fee >= available` so the RPC surfaces the real + // reason rather than a downstream "gas required exceeds allowance 0". + if l1_fee >= available { + return Err(MorphEthApiError::InsufficientFundsForL1Fee); + } + gas_allowance_from_balance(available - l1_fee, tx_env.gas_price) + }; - // allowance = (balance − value − l1_fee) / gas_price, done at wei - // precision so the remainder is not lost across the two - // subtractions. - let balance = db - .get_account(&tx_env.signer()) - .map_err(|e| MorphEthApiError::Eth(e.into()))? - .map(|acc| acc.balance) - .unwrap_or_default(); - let available = balance - .checked_sub(tx_env.value) - .ok_or(MorphEthApiError::InsufficientFundsForTransfer)?; - // Reject at `l1_fee >= available` so the RPC surfaces the real - // reason rather than a downstream "gas required exceeds allowance 0". - if l1_fee >= available { - return Err(MorphEthApiError::InsufficientFundsForL1Fee); - } - Ok(gas_allowance_from_balance( - available - l1_fee, - tx_env.gas_price, - )) + Ok(cap_call_gas_allowance(allowance, self.call_gas_limit())) } } @@ -816,58 +445,114 @@ where let chain_spec = self.provider().chain_spec(); let hardfork = chain_spec.morph_hardfork_at(block_number, timestamp); - let rlp_bytes = tx_env.rlp_bytes.as_ref().ok_or_else(|| { - EthApiError::InvalidParams("missing rlp bytes for l1 fee".to_string()) - })?; + let rlp_bytes = estimate_l1_fee_rlp_bytes(evm_env, tx_env)?; let l1_info = L1BlockInfo::try_fetch(db, hardfork).map_err(|err| { EthApiError::InvalidParams(format!("failed to estimate L1 data fee: {err}")) })?; - Ok(l1_info.calculate_tx_l1_cost(rlp_bytes, hardfork)) + Ok(l1_info.calculate_tx_l1_cost(&rlp_bytes, hardfork)) } +} - /// Allowance for MorphTx ERC20 fee-token callers: cap by token - /// balance, not by ETH balance. - #[allow(clippy::too_many_arguments)] - fn caller_gas_allowance_with_token( - &self, - db: &mut DB, - evm_env: &MorphEvmEnv, - caller: Address, - value: U256, - l1_fee: U256, - fee_token_id: u16, - fee_limit: Option, - gas_price: u128, - ) -> Result - where - DB: Database, - DB::Error: Into, - { - let token_fee_info = load_token_fee_info_for_allowance(db, fee_token_id, caller, evm_env)?; - - // ETH only needs to cover `value`; gas + L1 fee are paid in tokens. - let eth_balance = db - .get_account(&caller) - .map_err(|e| MorphEthApiError::Eth(e.into()))? - .map(|acc| acc.balance) - .unwrap_or_default(); - - token_gas_allowance( - eth_balance, - value, - &token_fee_info, - l1_fee, - fee_limit, - gas_price, - ) +/// Returns the EIP-2718 bytes used to size L1 data fees during `eth_estimateGas`. +/// +/// `EstimateCall::estimate_gas_with` constructs `tx_env` before clamping its gas limit +/// to `min(tx_gas_limit_cap, block_gas_limit)`. When an oversized `gas` or `blockOverrides.gasLimit` +/// exceeds that effective cap, re-encode with the capped gas limit so L1 fee sizing matches +/// `morph-geth`'s `DoEstimateGas` / `ToMessage(gasCap)`. +fn estimate_l1_fee_rlp_bytes<'a>( + evm_env: &MorphEvmEnv, + tx_env: &'a MorphTxEnv, +) -> Result, EthApiError> { + let effective_cap = evm_env + .version() + .tx_gas_caps() + .0 + .min(evm_env.block_env().gas_limit.saturating_to::()); + if tx_env.gas_limit > effective_cap { + let mut capped = tx_env.clone(); + capped.gas_limit = effective_cap; + return Ok(Cow::Owned(capped.encode_for_l1_fee(evm_env.chain_id()))); + } + tx_env + .rlp_bytes + .as_ref() + .map(Cow::Borrowed) + .ok_or_else(|| EthApiError::InvalidParams("missing rlp bytes for l1 fee".to_string())) +} + +/// Cap a call or estimation gas ceiling / allowance by the configured RPC gas cap (`--rpc.gascap`), +/// treating `0` as unlimited. +fn cap_call_gas_allowance(allowance: u64, gas_cap: u64) -> u64 { + if gas_cap == 0 { + allowance + } else { + allowance.min(gas_cap) + } +} + +/// Loads token registry metadata, validates token usability and `tx.value` ETH coverage +/// before executing any call-mode `balanceOf`, resolves `caller`'s token balance, and +/// computes the caller's gas allowance. +#[expect(clippy::too_many_arguments)] +fn load_caller_token_gas_allowance( + db: &mut DB, + evm_env: &MorphEvmEnv, + caller: Address, + value: U256, + l1_fee: U256, + fee_token_id: u16, + fee_limit: Option, + gas_price: u128, +) -> Result +where + DB: Database, + DB::Error: Into, +{ + let entry = TokenRegistryEntry::load(db, fee_token_id) + .map_err(|e| MorphEthApiError::Eth(e.into()))? + .ok_or(MorphEthApiError::InvalidFeeToken)? + .ensure_usable(fee_token_id) + .map_err(|_| MorphEthApiError::InvalidFeeToken)?; + + // ETH only needs to cover `value`; checking before call-mode `balanceOf` avoids + // spinning up an EVM when the caller cannot even cover `tx.value`. + let eth_balance = db + .get_account(&caller) + .map_err(|e| MorphEthApiError::Eth(e.into()))? + .map(|acc| acc.balance) + .unwrap_or_default(); + if eth_balance < value { + return Err(MorphEthApiError::InsufficientFundsForTransfer); } + + let token_fee_info = match entry.load_for_caller(db, caller, evm_env) { + Ok(info) => info, + Err(HandlerError::Database(db_err)) => { + if let Some(provider_err) = db_err.downcast_ref::() { + return Err(MorphEthApiError::from(provider_err.clone())); + } + return Err(MorphEthApiError::from(ProviderError::other(db_err))); + } + Err(HandlerError::Fatal(msg)) => return Err(MorphEthApiError::Internal(msg.to_string())), + Err(_) => return Err(MorphEthApiError::InvalidFeeToken), + }; + + token_gas_allowance( + eth_balance, + value, + &token_fee_info, + l1_fee, + fee_limit, + gas_price, + ) } /// Resolves fee-token metadata and `caller`'s balance (both direct-slot and call-mode `balanceOf`) /// for `eth_estimateGas`, preserving database/provider failures instead of masking them as /// [`MorphEthApiError::InvalidFeeToken`]. +#[cfg(test)] fn load_token_fee_info_for_allowance( db: &mut DB, fee_token_id: u16, @@ -1332,4 +1017,49 @@ mod tests { "DB failure must propagate as Eth error, got {err:?}" ); } + + #[test] + fn cap_call_gas_allowance_clamps_nonzero_and_leaves_zero_uncapped() { + let gas_cap = 50_000_000u64; + assert_eq!(cap_call_gas_allowance(u64::MAX, gas_cap), gas_cap); + assert_eq!(cap_call_gas_allowance(100_000_000, gas_cap), gas_cap); + assert_eq!(cap_call_gas_allowance(gas_cap, gas_cap), gas_cap); + assert_eq!(cap_call_gas_allowance(21_000, gas_cap), 21_000); + assert_eq!(cap_call_gas_allowance(0, gas_cap), 0); + assert_eq!(cap_call_gas_allowance(u64::MAX, 0), u64::MAX); + assert_eq!(cap_call_gas_allowance(100_000_000, 0), 100_000_000); + } + + #[test] + fn estimate_l1_fee_rlp_caps_oversized_gas_limit() { + use morph_chainspec::hardfork::MorphHardfork; + use morph_revm::{MorphBlockEnv, morph_evm_env}; + + let block_env = MorphBlockEnv { + gas_limit: U256::from(u64::MAX), + ..Default::default() + }; + let evm_env = morph_evm_env(MorphHardfork::Celadon, 2818, 50_000_000, block_env); + + let mut tx_capped = MorphTxEnv { + gas_limit: 50_000_000, + ..Default::default() + }; + let expected = tx_capped.encode_for_l1_fee(2818); + tx_capped.rlp_bytes = Some(expected.clone()); + + let mut tx_oversized = MorphTxEnv { + gas_limit: u64::MAX, + ..Default::default() + }; + let uncapped = tx_oversized.encode_for_l1_fee(2818); + tx_oversized.rlp_bytes = Some(uncapped.clone()); + + let sized = estimate_l1_fee_rlp_bytes(&evm_env, &tx_oversized).unwrap(); + assert_eq!(sized.as_ref(), &expected); + assert_eq!(uncapped.len() - sized.len(), 4); + + let borrowed = estimate_l1_fee_rlp_bytes(&evm_env, &tx_capped).unwrap(); + assert!(matches!(borrowed, Cow::Borrowed(_))); + } } diff --git a/crates/rpc/src/eth/transaction.rs b/crates/rpc/src/eth/transaction.rs index 5113449c..02a5726a 100644 --- a/crates/rpc/src/eth/transaction.rs +++ b/crates/rpc/src/eth/transaction.rs @@ -58,6 +58,38 @@ impl TryIntoSimTx for MorphTransactionRequest { } } +/// Normalizes one `eth_simulateV1` call before upstream resolves its defaults. +/// +/// geth's `ToMessage` keeps the Morph fields (`feeTokenID`, `reference`, `memo`) of a request +/// that uses legacy `gasPrice` and maps `gasPrice` onto both EIP-1559 fee caps, so a simulated +/// call is priced as the same MorphTx `eth_call` would execute. `TryIntoSimTx` cannot do this +/// itself: it also builds the transaction returned by `eth_fillTransaction`, which must keep +/// geth's `toTransaction` rule that legacy `gasPrice` produces a legacy transaction. Running +/// before upstream's `resolve_transaction` also means only fee fields the caller actually set +/// count as a conflict, not the zero defaults it fills in. +pub(crate) fn normalize_simulate_call( + mut request: MorphTransactionRequest, +) -> Result { + let Some(gas_price) = request.inner.gas_price else { + return Ok(request); + }; + let has_morph_fields = request.fee_token_id.is_some_and(|id| id.to::() > 0) + || is_nonzero_reference(normalize_reference(request.reference).as_ref()) + || request.memo.as_ref().is_some_and(|memo| !memo.is_empty()); + if !has_morph_fields { + return Ok(request); + } + if request.inner.max_fee_per_gas.is_some() || request.inner.max_priority_fee_per_gas.is_some() { + return Err(EthApiError::InvalidParams( + "both gasPrice and (maxFeePerGas or maxPriorityFeePerGas) specified".to_string(), + )); + } + request.inner.gas_price = None; + request.inner.max_fee_per_gas = Some(gas_price); + request.inner.max_priority_fee_per_gas = Some(gas_price); + Ok(request) +} + /// Builds and signs a transaction from an RPC request. /// /// Supports both standard Ethereum transactions and Morph fee token transactions. @@ -1779,4 +1811,107 @@ mod tests { }; assert!(ok_req.try_into_tx_env(&evm_env).is_ok()); } + + #[test] + fn simulate_call_normalization_keeps_morph_fields_with_legacy_gas_price() { + let base_inner = || TransactionRequest { + chain_id: Some(2818), + nonce: Some(3), + gas: Some(50_000), + gas_price: Some(2_000_000_000), + to: Some(TxKind::Call(address!( + "0000000000000000000000000000000000000002" + ))), + ..Default::default() + }; + let morph_req = || MorphTransactionRequest { + inner: base_inner(), + fee_token_id: Some(U64::from(1)), + fee_limit: Some(U256::from(1234)), + reference: Some(B256::repeat_byte(0xab)), + memo: Some(Bytes::from_static(b"sim")), + }; + + // `eth_simulateV1`: `feeTokenID`, `reference`, or `memo` with legacy `gasPrice` builds + // TxMorph with `max_fee_per_gas == max_priority_fee_per_gas == gasPrice`. + let normalized = normalize_simulate_call(morph_req()).expect("no fee conflict"); + assert_eq!(normalized.inner.gas_price, None); + match normalized + .try_into_sim_tx() + .expect("normalized call must build TxMorph") + { + MorphTxEnvelope::Morph(signed) => { + assert_eq!(signed.tx().fee_token_id, 1); + assert_eq!(signed.tx().fee_limit, U256::from(1234)); + assert_eq!(signed.tx().reference, Some(B256::repeat_byte(0xab))); + assert_eq!(signed.tx().memo, Some(Bytes::from_static(b"sim"))); + assert_eq!(signed.tx().max_fee_per_gas, 2_000_000_000); + assert_eq!(signed.tx().max_priority_fee_per_gas, 2_000_000_000); + } + other => panic!("expected MorphTx, got {other:?}"), + } + + // `eth_fillTransaction` converts the raw request: legacy `gasPrice` keeps building a + // legacy transaction, as geth's `toTransaction` does. + assert!(matches!( + morph_req().try_into_sim_tx().unwrap(), + MorphTxEnvelope::Legacy(_) + )); + + // Without Morph fields, normalization leaves legacy `gasPrice` untouched. + let legacy_req = MorphTransactionRequest { + inner: base_inner(), + fee_token_id: None, + fee_limit: None, + reference: None, + memo: None, + }; + let legacy_req = normalize_simulate_call(legacy_req).unwrap(); + assert_eq!(legacy_req.inner.gas_price, Some(2_000_000_000)); + assert!(matches!( + legacy_req.try_into_sim_tx().unwrap(), + MorphTxEnvelope::Legacy(_) + )); + + // `gasPrice` plus an explicit EIP-1559 fee field on a MorphTx is a conflict. + let mut conflicting = morph_req(); + conflicting.inner.max_fee_per_gas = Some(3_000_000_000); + assert!(matches!( + normalize_simulate_call(conflicting), + Err(EthApiError::InvalidParams(_)) + )); + } + + #[test] + fn simulate_call_normalization_accepts_legacy_gas_price_with_authorization_list() { + // Upstream `resolve_transaction` later fills unset EIP-1559 fields with zero for a + // 7702-shaped request; normalizing first must not mistake those for caller input. + let request = MorphTransactionRequest { + inner: TransactionRequest { + chain_id: Some(2818), + nonce: Some(0), + gas: Some(100_000), + gas_price: Some(1_000_000), + to: Some(TxKind::Call(address!( + "0000000000000000000000000000000000000002" + ))), + authorization_list: Some(vec![sample_signed_authorization()]), + ..Default::default() + }, + fee_token_id: Some(U64::from(1)), + fee_limit: None, + reference: None, + memo: None, + }; + let normalized = normalize_simulate_call(request).expect("only gasPrice was set"); + assert_eq!(normalized.inner.max_fee_per_gas, Some(1_000_000)); + assert_eq!(normalized.inner.max_priority_fee_per_gas, Some(1_000_000)); + match normalized.try_into_sim_tx().expect("must build a MorphTx") { + MorphTxEnvelope::Morph(signed) => { + assert_eq!(signed.tx().version, MORPH_TX_VERSION_2); + assert_eq!(signed.tx().authorization_list.len(), 1); + } + other => panic!("expected MorphTx, got {other:?}"), + } + } } diff --git a/crates/rpc/src/morph/handler.rs b/crates/rpc/src/morph/handler.rs index d655cf61..67bb9949 100644 --- a/crates/rpc/src/morph/handler.rs +++ b/crates/rpc/src/morph/handler.rs @@ -7,11 +7,12 @@ use jsonrpsee::{ types::{ErrorCode, ErrorObjectOwned}, }; use morph_reference_index::{ - CanonicalTip, ReferenceIndexError, ReferenceIndexHandle, ReferenceIndexPhase, - ReferenceIndexProgress, ReferenceQuery, ReferenceTransactionResult, + CanonicalTip, ReferenceIndexError, ReferenceIndexHandle, ReferenceIndexPhase, ReferenceQuery, + ReferenceTransactionResult, }; use reth_storage_api::{BlockNumReader, HeaderProvider}; use std::time::Duration; +use tokio::time::Instant; use tracing; const TARGET: &str = "morph::reference_index_rpc"; @@ -22,15 +23,34 @@ const TARGET: &str = "morph::reference_index_rpc"; /// this budget and return real data instead of forcing the client to retry. const INDEX_WAIT_TIMEOUT: Duration = Duration::from_millis(300); -/// Maximum block lag for which the RPC handler waits asynchronously for the -/// reference index to catch up. When the durable cursor lags further behind the -/// canonical tip (for example during large historical backfill), the handler -/// fails fast with `IndexBehind` instead of holding an async waiter open. +/// Poll cadence while waiting for the index cursor to reach the canonical tip. +const INDEX_WAIT_POLL_INTERVAL: Duration = Duration::from_millis(5); + +/// Maximum block lag for which a handler waits for the reference index to catch +/// up. A larger lag (a node catching up after downtime, or a deep historical +/// backfill) will not resolve within `INDEX_WAIT_TIMEOUT`, so the handler fails +/// fast instead of spending its whole budget on every request. const MAX_STEADY_STATE_LAG: u64 = 2; -fn should_fail_fast(progress: ReferenceIndexProgress, canonical_tip_number: u64) -> bool { +fn next_poll_delay(now: Instant, deadline: Instant) -> Option { + let remaining = deadline.saturating_duration_since(now); + (!remaining.is_zero()).then(|| INDEX_WAIT_POLL_INTERVAL.min(remaining)) +} + +/// Whether waiting cannot help. +/// +/// Waiting only pays off for the steady-state per-block lag: the phase +/// oscillates `Live <-> Backfill` for the newest block and the cursor catches up +/// within milliseconds. Rapid-sync `Deferred` (indexing intentionally paused), +/// the one-time `PreJade` activation boundary, `Repairing`, and any lag beyond +/// steady state all move on a much coarser timescale. +fn should_fail_fast( + phase: ReferenceIndexPhase, + indexed_to: Option, + canonical_tip_number: u64, +) -> bool { if matches!( - progress.phase, + phase, ReferenceIndexPhase::Deferred | ReferenceIndexPhase::PreJade | ReferenceIndexPhase::Repairing @@ -38,7 +58,7 @@ fn should_fail_fast(progress: ReferenceIndexProgress, canonical_tip_number: u64) return true; } - if let Some(indexed_to) = progress.indexed_to + if let Some(indexed_to) = indexed_to && canonical_tip_number.saturating_sub(indexed_to) > MAX_STEADY_STATE_LAG { return true; @@ -47,10 +67,17 @@ fn should_fail_fast(progress: ReferenceIndexProgress, canonical_tip_number: u64) false } +/// Outcome of one synchronous query attempt, run on the blocking pool. enum QueryAttempt { + /// The response is final. Ready(Vec), + /// The canonical tip moved while the query was bracketed; try again. TipChanged, - Behind { tip_number: u64 }, + /// The index cursor has not reached the canonical tip yet. + Behind { + tip_number: u64, + indexed_to: Option, + }, } fn query_once( @@ -80,29 +107,33 @@ where // to retry) — before Jade there is nothing to wait for. if ctx.reference_index.is_pre_jade(canonical_tip.timestamp) { let after = ctx.provider.chain_info()?; - if after == before { - return Ok(QueryAttempt::Ready(Vec::new())); - } - // The pre-Jade snapshot changed while it was bracketed. Do not - // query the index with the stale tip: rebuild a fresh canonical - // snapshot on the next iteration. - return Ok(QueryAttempt::TipChanged); + return Ok(if after == before { + QueryAttempt::Ready(Vec::new()) + } else { + // The pre-Jade snapshot changed while it was bracketed. Do not + // query the index with the stale tip: rebuild a fresh canonical + // snapshot on the next iteration. + QueryAttempt::TipChanged + }); } match ctx.reference_index.query_at(query, canonical_tip) { Ok(result) => { let after = ctx.provider.chain_info()?; - if after == before { - Ok(QueryAttempt::Ready(result)) + Ok(if after == before { + QueryAttempt::Ready(result) } else { // The tip advanced while we read; this snapshot no longer // matches a stable head. Retry against the new tip while the // wait budget allows, otherwise report behind. - Ok(QueryAttempt::TipChanged) - } + QueryAttempt::TipChanged + }) } Err(ReferenceIndexError::IndexBehind) => Ok(QueryAttempt::Behind { tip_number: canonical_tip.number, + // Read in the same blocking context as the query; the handler only + // needs it to tell a steady-state lag from one worth failing fast. + indexed_to: ctx.reference_index.indexed_to()?, }), Err(other) => Err(other), } @@ -220,22 +251,16 @@ where // The index runtime is asynchronous (PR #141 decoupled it from block // execution), so for a few milliseconds after a new block becomes the - // canonical tip the durable cursor still lags it. Run each synchronous - // provider + MDBX read on Tokio's blocking pool, and park asynchronously - // on the runtime's `watch` progress channel when waiting for steady-state - // catch-up — holding zero OS blocking threads and opening zero MDBX read - // transactions while waiting. - let deadline = tokio::time::Instant::now() + INDEX_WAIT_TIMEOUT; + // canonical tip the durable cursor still lags it. Rather than returning + // `IndexBehind` immediately — forcing the client into a retry loop — + // wait a bounded amount for the runtime to catch up. The read itself is + // synchronous MDBX/provider work and runs on the blocking pool; the wait + // between attempts is an async sleep, so a pending request holds no + // blocking thread. Every wait is bounded by `INDEX_WAIT_TIMEOUT`. + let deadline = Instant::now() + INDEX_WAIT_TIMEOUT; let mut wait = RpcWaitGuard::new(self); - let mut progress_rx = self.ctx.reference_index.subscribe_progress(); - let mut watch_closed = false; loop { - // Mark the latest published progress as seen BEFORE running the - // blocking read attempt so any commit/phase change occurring while - // `query_once` executes immediately wakes `progress_rx.changed()`. - let _ = *progress_rx.borrow_and_update(); - let ctx = self.ctx.clone(); let attempt = tokio::task::spawn_blocking(move || query_once(&ctx, query)) .await @@ -248,68 +273,23 @@ where match attempt { QueryAttempt::Ready(results) => return Ok(results), - QueryAttempt::TipChanged => { - if tokio::time::Instant::now() >= deadline { - wait.begin_wait(); - wait.mark_timed_out(); + QueryAttempt::TipChanged => {} + QueryAttempt::Behind { + tip_number, + indexed_to, + } => { + if should_fail_fast(self.ctx.reference_index.phase(), indexed_to, tip_number) { return Err(to_rpc_error(ReferenceIndexError::IndexBehind)); } - wait.begin_wait(); - tokio::task::yield_now().await; - } - QueryAttempt::Behind { tip_number } => { - let progress = self.ctx.reference_index.progress(); - if progress.unavailable { - return Err(to_rpc_error(ReferenceIndexError::IndexUnavailable)); - } - if should_fail_fast(progress, tip_number) || watch_closed { - return Err(to_rpc_error(ReferenceIndexError::IndexBehind)); - } - - wait.begin_wait(); - loop { - match tokio::time::timeout_at(deadline, progress_rx.changed()).await { - Ok(Ok(())) => { - let updated = self.ctx.reference_index.progress(); - if updated.unavailable { - return Err(to_rpc_error( - ReferenceIndexError::IndexUnavailable, - )); - } - if matches!( - updated.phase, - ReferenceIndexPhase::Deferred | ReferenceIndexPhase::Repairing - ) || updated.indexed_to.is_some_and(|cur| { - tip_number.saturating_sub(cur) > MAX_STEADY_STATE_LAG - }) { - return Err(to_rpc_error(ReferenceIndexError::IndexBehind)); - } - // Entering `Backfill` notifies before the batch commits; if - // the durable cursor is still strictly below `tip_number`, - // keep waiting for the actual commit instead of opening a - // doomed MDBX read transaction. - if updated.phase == ReferenceIndexPhase::Backfill - && updated.indexed_to.is_some_and(|cur| cur < tip_number) - { - continue; - } - break; - } - Ok(Err(_closed)) => { - // Runtime shut down (watch sender dropped): perform one - // final recheck in case a terminal commit or `Unavailable` - // transition happened immediately before shutdown, then exit. - watch_closed = true; - break; - } - Err(_elapsed) => { - wait.mark_timed_out(); - return Err(to_rpc_error(ReferenceIndexError::IndexBehind)); - } - } - } } } + + wait.begin_wait(); + let Some(delay) = next_poll_delay(Instant::now(), deadline) else { + wait.mark_timed_out(); + return Err(to_rpc_error(ReferenceIndexError::IndexBehind)); + }; + tokio::time::sleep(delay).await; } } } @@ -476,11 +456,19 @@ mod tests { } } + #[derive(Debug)] + struct ChainInfoGate { + call: usize, + calls: AtomicUsize, + reached: Arc, + released: Arc, + } + #[derive(Clone, Debug)] struct TestProvider { chain_info: Arc>>, headers: Arc>, - chain_info_calls: Arc, + gate: Option>, } impl TestProvider { @@ -491,16 +479,30 @@ mod tests { Self { chain_info: Arc::new(Mutex::new(chain_info.into_iter().collect())), headers: Arc::new(headers), - chain_info_calls: Arc::new(AtomicUsize::new(0)), + gate: None, } } - fn chain_info_calls(&self) -> usize { - self.chain_info_calls.load(Ordering::Acquire) + fn gate_chain_info_call(mut self, call: usize) -> (Self, Arc, Arc) { + let reached = Arc::new(Barrier::new(2)); + let released = Arc::new(Barrier::new(2)); + self.gate = Some(Arc::new(ChainInfoGate { + call, + calls: AtomicUsize::new(0), + reached: reached.clone(), + released: released.clone(), + })); + (self, reached, released) } fn info(&self) -> ChainInfo { - self.chain_info_calls.fetch_add(1, Ordering::AcqRel); + if let Some(gate) = &self.gate { + let call = gate.calls.fetch_add(1, Ordering::Relaxed) + 1; + if call == gate.call { + gate.reached.wait(); + gate.released.wait(); + } + } let mut infos = self.chain_info.lock().unwrap(); if infos.len() > 1 { infos.pop_front().unwrap() @@ -606,6 +608,7 @@ mod tests { block: CanonicalBlock { number: 0, hash, + parent_hash: B256::ZERO, timestamp: block_timestamp, transactions: Vec::new(), }, @@ -739,7 +742,7 @@ mod tests { #[tokio::test] async fn rapid_sync_deferred_fails_fast_without_burning_the_wait_budget() { // Rapid-sync `Deferred`: a post-Jade query must return `IndexBehind` - // promptly rather than waiting out the full `INDEX_WAIT_TIMEOUT`, since + // promptly rather than sleeping out the full `INDEX_WAIT_TIMEOUT`, since // the runtime will not catch up while indexing is intentionally paused. let dir = tempfile::tempdir().unwrap(); let hash = B256::repeat_byte(0x11); @@ -747,6 +750,7 @@ mod tests { block: CanonicalBlock { number: 0, hash, + parent_hash: B256::ZERO, timestamp: 100, transactions: Vec::new(), }, @@ -763,124 +767,102 @@ mod tests { }], BTreeMap::from([(hash, header(0, 100))]), ); - let outcomes = Arc::new(Mutex::new(Vec::new())); - let observed = outcomes.clone(); - let handler = MorphRpcHandler::new(MorphRpc::new(handle, provider.clone())) - .with_wait_observer(move |timed_out| { - observed.lock().unwrap().push(timed_out); - }); + let handler = MorphRpcHandler::new(MorphRpc::new(handle, provider)); - let started = std::time::Instant::now(); let error = handler .get_transaction_hashes_by_reference(args()) .await .unwrap_err(); - drop(runtime); assert_eq!(error.message(), "reference index is behind"); - assert!(started.elapsed() < Duration::from_millis(100)); - assert!(outcomes.lock().unwrap().is_empty()); - assert_eq!(provider.chain_info_calls(), 1); } #[test] - fn should_fail_fast_classifies_phases_and_steady_state_lag() { - let progress = |phase, indexed_to| ReferenceIndexProgress { - phase, - indexed_to, - unavailable: phase == ReferenceIndexPhase::Unavailable, - }; + fn poll_delay_never_exceeds_the_remaining_budget() { + let now = Instant::now(); + assert_eq!(next_poll_delay(now, now), None); + assert_eq!( + next_poll_delay(now, now + Duration::from_millis(2)), + Some(Duration::from_millis(2)) + ); + assert_eq!( + next_poll_delay(now, now + Duration::from_millis(10)), + Some(INDEX_WAIT_POLL_INTERVAL) + ); + } + + #[test] + fn should_fail_fast_classifies_phases_and_steady_state_lag() { assert!(should_fail_fast( - progress(ReferenceIndexPhase::Deferred, Some(10)), - 10 - )); - assert!(should_fail_fast( - progress(ReferenceIndexPhase::PreJade, None), + ReferenceIndexPhase::Deferred, + Some(10), 10 )); + assert!(should_fail_fast(ReferenceIndexPhase::PreJade, None, 10)); assert!(should_fail_fast( - progress(ReferenceIndexPhase::Repairing, Some(10)), + ReferenceIndexPhase::Repairing, + Some(10), 10 )); // Steady-state lag <= MAX_STEADY_STATE_LAG (2) is allowed to wait. + assert!(!should_fail_fast(ReferenceIndexPhase::Live, Some(10), 11)); assert!(!should_fail_fast( - progress(ReferenceIndexPhase::Live, Some(10)), - 11 - )); - assert!(!should_fail_fast( - progress(ReferenceIndexPhase::Backfill, Some(10)), + ReferenceIndexPhase::Backfill, + Some(10), 12 )); - assert!(!should_fail_fast( - progress(ReferenceIndexPhase::Backfill, None), - 1 - )); + assert!(!should_fail_fast(ReferenceIndexPhase::Backfill, None, 1)); // Lag > MAX_STEADY_STATE_LAG (2) fails fast. assert!(should_fail_fast( - progress(ReferenceIndexPhase::Backfill, Some(10)), - 13 - )); - assert!(should_fail_fast( - progress(ReferenceIndexPhase::Live, Some(10)), + ReferenceIndexPhase::Backfill, + Some(10), 13 )); } #[tokio::test] - async fn live_lag_wait_eventually_returns_behind_without_polling() { - let dir = tempfile::tempdir().unwrap(); + async fn lag_beyond_steady_state_fails_fast_without_waiting() { let indexed_hash = B256::repeat_byte(0x11); let head_hash = B256::repeat_byte(0x22); - let chain = TestChain { - block: CanonicalBlock { - number: 0, - hash: indexed_hash, - timestamp: 100, - transactions: Vec::new(), - }, - }; - let config = ReferenceIndexConfig::new(dir.path(), 2818, B256::ZERO, 0); - // Keep `runtime` alive so the watch sender stays open and the wait hits the deadline. - let (mut runtime, handle) = ReferenceIndexRuntime::new(config, chain); - runtime.synchronize_once(false).unwrap(); - + let (_dir, handle) = synced_handle(0, 100, indexed_hash); + // The canonical head is three blocks above the durable cursor: a node + // catching up, not the per-block steady-state lag. let provider = TestProvider::new( [ChainInfo { best_hash: head_hash, - best_number: 1, + best_number: 3, }], - BTreeMap::from([(head_hash, header(1, 101))]), + BTreeMap::from([(head_hash, header(3, 103))]), ); - let outcomes = Arc::new(Mutex::new(Vec::new())); - let observed = outcomes.clone(); - let handler = MorphRpcHandler::new(MorphRpc::new(handle, provider.clone())) - .with_wait_observer(move |timed_out| { - observed.lock().unwrap().push(timed_out); - }); + let handler = MorphRpcHandler::new(MorphRpc::new(handle, provider)); + let started = Instant::now(); let error = handler .get_transaction_hashes_by_reference(args()) .await .unwrap_err(); - drop(runtime); assert_eq!(error.message(), "reference index is behind"); - assert_eq!(*outcomes.lock().unwrap(), [true]); - // Only the initial read occurred; no polling reads during the 300ms wait. - assert_eq!(provider.chain_info_calls(), 1); + assert!( + started.elapsed() < Duration::from_millis(100), + "a lag beyond steady state must not burn the wait budget: {:?}", + started.elapsed() + ); } #[tokio::test] - async fn live_lag_wait_returns_from_the_same_request_after_runtime_catches_up() { + async fn lag_of_two_is_waited_out_until_the_index_catches_up() { let dir = tempfile::tempdir().unwrap(); let indexed_hash = B256::repeat_byte(0x11); - let head_hash = B256::repeat_byte(0x22); + let mid_hash = B256::repeat_byte(0x22); + let head_hash = B256::repeat_byte(0x33); let chain = GrowingTestChain::new(CanonicalBlock { number: 0, hash: indexed_hash, + parent_hash: B256::ZERO, timestamp: 100, transactions: Vec::new(), }); @@ -889,296 +871,85 @@ mod tests { runtime.synchronize_once(false).unwrap(); chain.push(CanonicalBlock { number: 1, - hash: head_hash, - timestamp: 101, - transactions: Vec::new(), - }); - - let provider = TestProvider::new( - [ChainInfo { - best_hash: head_hash, - best_number: 1, - }], - BTreeMap::from([(head_hash, header(1, 101))]), - ); - let catch_up = tokio::spawn(async move { - tokio::time::sleep(Duration::from_millis(40)).await; - tokio::task::spawn_blocking(move || { - runtime.synchronize_once(false).unwrap(); - runtime - }) - .await - .unwrap() - }); - let handler = MorphRpcHandler::new(MorphRpc::new(handle, provider.clone())); - - let results = handler - .get_transaction_hashes_by_reference(args()) - .await - .unwrap(); - let _runtime = catch_up.await.unwrap(); - - assert!(results.is_empty()); - // Attempt 1 (`before`) + Attempt 2 (`before` + `after`) = 3 calls; zero polling. - assert_eq!(provider.chain_info_calls(), 3); - } - - #[tokio::test] - async fn steady_state_lag_of_two_waits_and_succeeds_without_polling() { - let dir = tempfile::tempdir().unwrap(); - let hash0 = B256::repeat_byte(0x10); - let hash1 = B256::repeat_byte(0x11); - let hash2 = B256::repeat_byte(0x12); - let chain = GrowingTestChain::new(CanonicalBlock { - number: 0, - hash: hash0, - timestamp: 100, - transactions: Vec::new(), - }); - let config = ReferenceIndexConfig::new(dir.path(), 2818, B256::ZERO, 0); - let (mut runtime, handle) = ReferenceIndexRuntime::new(config, chain.clone()); - runtime.synchronize_once(false).unwrap(); - chain.push(CanonicalBlock { - number: 1, - hash: hash1, + hash: mid_hash, + parent_hash: indexed_hash, timestamp: 101, transactions: Vec::new(), }); chain.push(CanonicalBlock { number: 2, - hash: hash2, + hash: head_hash, + parent_hash: mid_hash, timestamp: 102, transactions: Vec::new(), }); let provider = TestProvider::new( [ChainInfo { - best_hash: hash2, + best_hash: head_hash, best_number: 2, }], - BTreeMap::from([(hash2, header(2, 102))]), + BTreeMap::from([(head_hash, header(2, 102))]), ); - let catch_up = tokio::spawn(async move { - tokio::time::sleep(Duration::from_millis(40)).await; - tokio::task::spawn_blocking(move || { - runtime.synchronize_once(false).unwrap(); - runtime - }) - .await - .unwrap() + let catch_up = std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(20)); + runtime.synchronize_once(false).unwrap(); }); - let handler = MorphRpcHandler::new(MorphRpc::new(handle, provider.clone())); - - let results = handler - .get_transaction_hashes_by_reference(args()) - .await - .unwrap(); - let _runtime = catch_up.await.unwrap(); - - assert!(results.is_empty()); - assert_eq!(provider.chain_info_calls(), 3); - } - - #[tokio::test] - async fn backfill_lag_above_two_fails_fast_without_waiting() { - let dir = tempfile::tempdir().unwrap(); - let hash0 = B256::repeat_byte(0x10); - let hash3 = B256::repeat_byte(0x13); - let chain = TestChain { - block: CanonicalBlock { - number: 0, - hash: hash0, - timestamp: 100, - transactions: Vec::new(), - }, - }; - let config = ReferenceIndexConfig::new(dir.path(), 2818, B256::ZERO, 0); - let (mut runtime, handle) = ReferenceIndexRuntime::new(config, chain); - runtime.synchronize_once(false).unwrap(); - - let provider = TestProvider::new( - [ChainInfo { - best_hash: hash3, - best_number: 3, - }], - BTreeMap::from([(hash3, header(3, 103))]), - ); - let outcomes = Arc::new(Mutex::new(Vec::new())); - let observed = outcomes.clone(); - let handler = MorphRpcHandler::new(MorphRpc::new(handle, provider.clone())) - .with_wait_observer(move |timed_out| { - observed.lock().unwrap().push(timed_out); - }); + let handler = MorphRpcHandler::new(MorphRpc::new(handle, provider)); - let started = std::time::Instant::now(); - let error = handler - .get_transaction_hashes_by_reference(args()) - .await - .unwrap_err(); - drop(runtime); + let result = handler.get_transaction_hashes_by_reference(args()).await; + catch_up.join().unwrap(); - assert_eq!(error.message(), "reference index is behind"); assert!( - started.elapsed() < Duration::from_millis(100), - "lag > 2 must fail fast without waiting" + result.is_ok(), + "a lag of two is steady state and must be waited out: {result:?}" ); - assert!(outcomes.lock().unwrap().is_empty()); - assert_eq!(provider.chain_info_calls(), 1); } #[tokio::test] - async fn repairing_phase_fails_fast_without_waiting() { - #[derive(Clone, Debug)] - struct PausingReorgChain { - blocks: Arc>>, - pause_on_hash_of: Arc>>, - entered_repair: Arc, - release_repair: Arc, - } - - impl CanonicalChain for PausingReorgChain { - fn head(&self) -> Result { - let blocks = self.blocks.lock().unwrap(); - let block = blocks.last().unwrap(); - Ok(CanonicalTip { - number: block.number, - hash: block.hash, - timestamp: block.timestamp, - }) - } - - fn canonical_hash(&self, number: u64) -> Result, ReferenceIndexError> { - let should_pause = { - let mut target = self.pause_on_hash_of.lock().unwrap(); - if *target == Some(number) { - *target = None; - true - } else { - false - } - }; - if should_pause { - self.entered_repair.wait(); - self.release_repair.wait(); - } - Ok(self - .blocks - .lock() - .unwrap() - .iter() - .find_map(|block| (block.number == number).then_some(block.hash))) - } - - fn block_timestamp(&self, number: u64) -> Result, ReferenceIndexError> { - Ok(self - .blocks - .lock() - .unwrap() - .iter() - .find_map(|block| (block.number == number).then_some(block.timestamp))) - } - - fn finalized_block_number(&self) -> Result, ReferenceIndexError> { - Ok(None) - } - - fn canonical_blocks( - &self, - range: RangeInclusive, - ) -> Result, ReferenceIndexError> { - Ok(self - .blocks - .lock() - .unwrap() - .iter() - .filter(|block| range.contains(&block.number)) - .cloned() - .collect()) - } - } - - let dir = tempfile::tempdir().unwrap(); - let entered_repair = Arc::new(Barrier::new(2)); - let release_repair = Arc::new(Barrier::new(2)); - let reorg_hash = B256::repeat_byte(0x99); - let chain = PausingReorgChain { - blocks: Arc::new(Mutex::new(vec![ - CanonicalBlock { - number: 0, - hash: B256::repeat_byte(0x10), - timestamp: 100, - transactions: Vec::new(), - }, - CanonicalBlock { - number: 1, - hash: B256::repeat_byte(0x11), - timestamp: 101, - transactions: Vec::new(), - }, - ])), - pause_on_hash_of: Arc::new(Mutex::new(None)), - entered_repair: entered_repair.clone(), - release_repair: release_repair.clone(), - }; - let config = ReferenceIndexConfig::new(dir.path(), 2818, B256::ZERO, 0); - let (mut runtime, handle) = ReferenceIndexRuntime::new(config, chain.clone()); - runtime.synchronize_once(false).unwrap(); - - // Trigger a reorg on block 1 and pause inside `reconcile_cursor` after - // `ReferenceIndexPhase::Repairing` has been published. - chain.blocks.lock().unwrap()[1].hash = reorg_hash; - *chain.pause_on_hash_of.lock().unwrap() = Some(1); - let repair_thread = std::thread::spawn(move || { - runtime.synchronize_once(false).unwrap(); - runtime - }); - entered_repair.wait(); - assert_eq!(handle.phase(), ReferenceIndexPhase::Repairing); - + async fn live_lag_wait_eventually_returns_behind() { + let indexed_hash = B256::repeat_byte(0x11); + let head_hash = B256::repeat_byte(0x22); + let (_dir, handle) = synced_handle(0, 100, indexed_hash); let provider = TestProvider::new( [ChainInfo { - best_hash: reorg_hash, + best_hash: head_hash, best_number: 1, }], - BTreeMap::from([(reorg_hash, header(1, 101))]), + BTreeMap::from([(head_hash, header(1, 101))]), ); - let outcomes = Arc::new(Mutex::new(Vec::new())); - let observed = outcomes.clone(); - let handler = MorphRpcHandler::new(MorphRpc::new(handle, provider.clone())) - .with_wait_observer(move |timed_out| { - observed.lock().unwrap().push(timed_out); - }); + let handler = MorphRpcHandler::new(MorphRpc::new(handle, provider)); - let started = std::time::Instant::now(); let error = handler .get_transaction_hashes_by_reference(args()) .await .unwrap_err(); - release_repair.wait(); - let _runtime = repair_thread.join().unwrap(); assert_eq!(error.message(), "reference index is behind"); - assert!(started.elapsed() < Duration::from_millis(100)); - assert!(outcomes.lock().unwrap().is_empty()); - assert_eq!(provider.chain_info_calls(), 1); } #[tokio::test] - async fn watch_sender_drop_wakes_waiter_and_exits_immediately() { + async fn live_lag_wait_returns_from_the_same_request_after_runtime_catches_up() { let dir = tempfile::tempdir().unwrap(); let indexed_hash = B256::repeat_byte(0x11); let head_hash = B256::repeat_byte(0x22); - let chain = TestChain { - block: CanonicalBlock { - number: 0, - hash: indexed_hash, - timestamp: 100, - transactions: Vec::new(), - }, - }; + let chain = GrowingTestChain::new(CanonicalBlock { + number: 0, + hash: indexed_hash, + parent_hash: B256::ZERO, + timestamp: 100, + transactions: Vec::new(), + }); let config = ReferenceIndexConfig::new(dir.path(), 2818, B256::ZERO, 0); - let (mut runtime, handle) = ReferenceIndexRuntime::new(config, chain); + let (mut runtime, handle) = ReferenceIndexRuntime::new(config, chain.clone()); runtime.synchronize_once(false).unwrap(); + chain.push(CanonicalBlock { + number: 1, + hash: head_hash, + parent_hash: indexed_hash, + timestamp: 101, + transactions: Vec::new(), + }); let provider = TestProvider::new( [ChainInfo { @@ -1187,35 +958,21 @@ mod tests { }], BTreeMap::from([(head_hash, header(1, 101))]), ); - let outcomes = Arc::new(Mutex::new(Vec::new())); - let observed = outcomes.clone(); - let handler = MorphRpcHandler::new(MorphRpc::new(handle, provider.clone())) - .with_wait_observer(move |timed_out| { - observed.lock().unwrap().push(timed_out); - }); - - // Drop the runtime while the RPC call is awaiting `progress_rx.changed()`. - let shutdown = tokio::spawn(async move { - tokio::time::sleep(Duration::from_millis(40)).await; - drop(runtime); + let (provider, second_attempt, catch_up_complete) = provider.gate_chain_info_call(2); + let catch_up = std::thread::spawn(move || { + second_attempt.wait(); + runtime.synchronize_once(false).unwrap(); + catch_up_complete.wait(); }); + let handler = MorphRpcHandler::new(MorphRpc::new(handle, provider)); - let started = std::time::Instant::now(); - let error = handler + let results = handler .get_transaction_hashes_by_reference(args()) .await - .unwrap_err(); - shutdown.await.unwrap(); + .unwrap(); + catch_up.join().unwrap(); - assert_eq!(error.message(), "reference index is behind"); - assert!( - started.elapsed() < Duration::from_millis(180), - "dropped watch sender must wake and exit before the 300ms timeout (elapsed {:?})", - started.elapsed() - ); - assert_eq!(*outcomes.lock().unwrap(), [false]); - // Initial read + one final recheck after sender drop. - assert_eq!(provider.chain_info_calls(), 2); + assert!(results.is_empty()); } #[tokio::test] @@ -1226,6 +983,7 @@ mod tests { let chain = GrowingTestChain::new(CanonicalBlock { number: 0, hash: indexed_hash, + parent_hash: B256::ZERO, timestamp: 100, transactions: Vec::new(), }); @@ -1235,6 +993,7 @@ mod tests { chain.push(CanonicalBlock { number: 1, hash: head_hash, + parent_hash: indexed_hash, timestamp: 101, transactions: Vec::new(), }); @@ -1246,25 +1005,19 @@ mod tests { }], BTreeMap::from([(head_hash, header(1, 101))]), ); - let catch_up = tokio::spawn(async move { - tokio::time::sleep(Duration::from_millis(200)).await; - tokio::task::spawn_blocking(move || { - runtime.synchronize_once(false).unwrap(); - runtime - }) - .await - .unwrap() + let catch_up = std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(200)); + runtime.synchronize_once(false).unwrap(); }); - let handler = MorphRpcHandler::new(MorphRpc::new(handle, provider.clone())); + let handler = MorphRpcHandler::new(MorphRpc::new(handle, provider)); let result = handler.get_transaction_hashes_by_reference(args()).await; - let _runtime = catch_up.await.unwrap(); + catch_up.join().unwrap(); assert!( result.is_ok(), "a live query should wait for a 200ms index catch-up: {result:?}" ); - assert_eq!(provider.chain_info_calls(), 3); } #[tokio::test] @@ -1275,6 +1028,7 @@ mod tests { let chain = GrowingTestChain::new(CanonicalBlock { number: 0, hash: indexed_hash, + parent_hash: B256::ZERO, timestamp: 100, transactions: Vec::new(), }); @@ -1284,6 +1038,7 @@ mod tests { chain.push(CanonicalBlock { number: 1, hash: head_hash, + parent_hash: indexed_hash, timestamp: 101, transactions: Vec::new(), }); @@ -1295,34 +1050,30 @@ mod tests { }], BTreeMap::from([(head_hash, header(1, 101))]), ); - let transition = tokio::spawn(async move { - tokio::time::sleep(Duration::from_millis(40)).await; - tokio::task::spawn_blocking(move || { - runtime.synchronize_once(true).unwrap(); - runtime - }) - .await - .unwrap() + let (provider, second_attempt, transition_complete) = provider.gate_chain_info_call(2); + let transition = std::thread::spawn(move || { + second_attempt.wait(); + runtime.synchronize_once(true).unwrap(); + transition_complete.wait(); }); let phase = handle.clone(); let outcomes = Arc::new(Mutex::new(Vec::new())); let observed_outcomes = outcomes.clone(); - let handler = MorphRpcHandler::new(MorphRpc::new(handle, provider.clone())) - .with_wait_observer(move |timed_out| { + let handler = MorphRpcHandler::new(MorphRpc::new(handle, provider)).with_wait_observer( + move |timed_out| { observed_outcomes.lock().unwrap().push(timed_out); - }); + }, + ); let error = handler .get_transaction_hashes_by_reference(args()) .await .unwrap_err(); - let _runtime = transition.await.unwrap(); + transition.join().unwrap(); assert_eq!(error.message(), "reference index is behind"); assert_eq!(phase.phase(), ReferenceIndexPhase::Deferred); assert_eq!(*outcomes.lock().unwrap(), [false]); - // Woke on watch transition to `Deferred` and exited without another blocking read. - assert_eq!(provider.chain_info_calls(), 1); } #[tokio::test] diff --git a/crates/rpc/src/morph/rpc.rs b/crates/rpc/src/morph/rpc.rs index 2e5d542d..6c30a2e8 100644 --- a/crates/rpc/src/morph/rpc.rs +++ b/crates/rpc/src/morph/rpc.rs @@ -42,9 +42,8 @@ pub trait MorphRpc { /// progress is reported as `"reference index is behind"`. /// /// Runs asynchronously: each MDBX/provider read executes on Tokio's - /// blocking pool, while any bounded steady-state catch-up wait parks on - /// the index runtime's `watch` progress channel without holding a blocking - /// thread or polling MDBX. + /// blocking pool, while the bounded steady-state catch-up wait sleeps + /// asynchronously between polls without holding a blocking thread. #[method(name = "getTransactionHashesByReference")] async fn get_transaction_hashes_by_reference( &self, diff --git a/crates/txpool/Cargo.toml b/crates/txpool/Cargo.toml index bf3b367e..da582bc0 100644 --- a/crates/txpool/Cargo.toml +++ b/crates/txpool/Cargo.toml @@ -14,7 +14,7 @@ workspace = true [dependencies] # Morph morph-chainspec.workspace = true -morph-evm.workspace = true +morph-evm = { workspace = true, features = ["std"] } morph-primitives = { workspace = true, features = ["reth-codec"] } morph-revm.workspace = true @@ -44,5 +44,5 @@ tracing.workspace = true [dev-dependencies] tokio.workspace = true tokio-stream = { workspace = true, features = ["sync"] } -reth-evm-ethereum.workspace = true +reth-evm-ethereum = { workspace = true, features = ["std"] } reth-provider = { workspace = true, features = ["test-utils"] } diff --git a/crates/txpool/src/transaction.rs b/crates/txpool/src/transaction.rs index 88b0ceb6..17df6783 100644 --- a/crates/txpool/src/transaction.rs +++ b/crates/txpool/src/transaction.rs @@ -138,15 +138,18 @@ impl PoolTransaction for MorphPooledTransaction { replacement: &Self, price_bumps: &PriceBumpConfig, ) -> bool { - // Upstream `PriceBumpConfig::is_replacement_underpriced` skips the priority-fee bump - // whenever `replacement_max_priority_fee_per_gas == 0`, allowing a dynamic-fee tx - // (EIP-1559 / EIP-7702 / MorphTx) with `tip == 0` to replace a `tip > 0` tx by only - // inflating `max_fee_per_gas`. On Morph's fixed low base fee, that downgrades the - // effective tip to zero, so reject it explicitly while preserving Legacy replacements - // (`max_priority_fee_per_gas() == None`) and `0 -> 0` tip replacements. - if self.max_priority_fee_per_gas().is_some_and(|tip| tip > 0) - && replacement.max_priority_fee_per_gas() == Some(0) - { + // Enforce the configured price bump uniformly on `priority_fee_or_price()` (`gas_price` + // for Legacy/EIP-2930, `max_priority_fee_per_gas` for EIP-1559/EIP-7702/MorphTx), + // matching `morph-geth`'s `GasTipCapCmp` rule. Upstream `PriceBumpConfig` skips the + // priority-fee check whenever either side reports `max_priority_fee_per_gas == 0` + // (including Legacy `None` and dynamic-fee `tip == 0`), which on Morph's low base fee + // would let a `tip == 0` or low-tip dynamic-fee tx downgrade the effective fee of a + // `tip > 0` or Legacy tx. + let price_bump = price_bumps.price_bump(self.ty()); + let required_tip = U256::from(self.priority_fee_or_price()) + .saturating_mul(U256::from(100u64) + U256::from(price_bump)) + .div_ceil(U256::from(100u64)); + if U256::from(replacement.priority_fee_or_price()) < required_tip { return true; } price_bumps.is_replacement_underpriced(self, replacement) @@ -611,10 +614,28 @@ mod tests { let legacy_bumped = create_legacy_pooled_tx_with_gas_price(11_000_000); assert!(!existing.is_replacement_underpriced(&legacy_bumped, &bumps)); - // Legacy -> EIP-1559 with >= 1.1x maxFee preserves upstream reth behavior + // Legacy -> EIP-1559 / MorphTx must bump `priority_fee_or_price()` (`gasPrice -> tip`) + // as well as `maxFeePerGas`, preventing effective-fee downgrades on Morph's low base fee. let legacy = create_legacy_pooled_tx_with_gas_price(10_000_000); - let eip1559_from_legacy = create_eip1559_pooled_tx(11_000_000, 2_000_000); - assert!(!legacy.is_replacement_underpriced(&eip1559_from_legacy, &bumps)); + let eip1559_low_tip_from_legacy = create_eip1559_pooled_tx(11_000_000, 2_000_000); + let morph_low_tip_from_legacy = create_morph_pooled_tx_with_fees(11_000_000, 2_000_000); + assert!(legacy.is_replacement_underpriced(&eip1559_low_tip_from_legacy, &bumps)); + assert!(legacy.is_replacement_underpriced(&morph_low_tip_from_legacy, &bumps)); + + let eip1559_bumped_from_legacy = create_eip1559_pooled_tx(11_000_000, 11_000_000); + let morph_bumped_from_legacy = create_morph_pooled_tx_with_fees(11_000_000, 11_000_000); + assert!(!legacy.is_replacement_underpriced(&eip1559_bumped_from_legacy, &bumps)); + assert!(!legacy.is_replacement_underpriced(&morph_bumped_from_legacy, &bumps)); + + // Legacy (0 gasPrice) -> EIP-1559 (0 tip, bumped maxFee) is allowed + let zero_legacy = create_legacy_pooled_tx_with_gas_price(0); + assert!(!zero_legacy.is_replacement_underpriced(&zero_1559_bumped, &bumps)); + + // Astronomical tips near `u128::MAX` do not wrap/saturate down below the existing tip. + let max_tip = create_morph_pooled_tx_with_fees(u128::MAX, u128::MAX); + let lower_tip = create_morph_pooled_tx_with_fees(u128::MAX, u128::MAX / 50); + assert!(max_tip.is_replacement_underpriced(&lower_tip, &bumps)); + assert!(max_tip.is_replacement_underpriced(&max_tip, &bumps)); } /// A MorphTx paying gas in an ERC20 token must report an ETH cost of `value` only. diff --git a/crates/txpool/src/validator.rs b/crates/txpool/src/validator.rs index 373064b8..a123db10 100644 --- a/crates/txpool/src/validator.rs +++ b/crates/txpool/src/validator.rs @@ -767,13 +767,24 @@ where // Compute the new L1/EVM validation state outside the write lock, then publish // `self.inner` and `self.block_info.head` together under the write lock so a // concurrent `current_validation_state` fallback cannot race and downgrade - // `self.inner` to an older block. + // `self.inner` or `self.block_info.head` to an older block. let refreshed = validation_state_for_header( self.client(), self.inner.evm_config(), new_tip_block.header(), ); let mut guard = self.block_info.head.write(); + if guard + .as_ref() + .is_some_and(|current| current.number > new_tip_block.number()) + && self.client().chain_info().is_ok_and(|tip| { + !tip.best_hash.is_zero() + && tip.best_hash != new_tip_block.hash() + && tip.best_number > new_tip_block.number() + }) + { + return; + } self.inner.on_new_head_block(new_tip_block); match refreshed { Ok(state) => *guard = Some(state.head), @@ -1174,6 +1185,21 @@ mod tests { "expected stale validation head to auto-refresh, got {outcome:?}" ); assert_eq!(validator.block_info().number(), 50); + + // A delayed `on_new_head_block` notification for an older superseded block must not + // downgrade `block_info` or `self.inner` back below the canonical tip. + let stale_block = SealedBlock::seal_slow(morph_primitives::Block::new( + head_at(2, 0, 100_000), + Default::default(), + )); + validator.on_new_head_block(&stale_block); + assert_eq!(validator.block_info().number(), 50); + let tx2 = pooled_morph_tx(2, 0, 200_000, 100, U256::ZERO, U256::ZERO); + assert!( + validator + .validate_one(TransactionOrigin::Local, tx2) + .is_valid() + ); } #[test] diff --git a/deny.toml b/deny.toml index 67162ea2..fe7af220 100644 --- a/deny.toml +++ b/deny.toml @@ -15,6 +15,12 @@ ignore = [ { id = "RUSTSEC-2026-0387", reason = "crypto-bigint 0.5 comes in through elliptic-curve 0.13 (k256/p256/ecdsa via alloy and reth); the fix is only in 0.7.6+, which needs the elliptic-curve 0.14 major upgrade upstream" }, # https://rustsec.org/advisories/RUSTSEC-2026-0441 pin-utils is unmaintained { id = "RUSTSEC-2026-0441", reason = "pulled in only by wasmtimer, a wasm32-only dependency of the alloy provider/transport crates, so it is not built for our targets; no maintained release to move to" }, + # https://rustsec.org/advisories/RUSTSEC-2026-0542 humantime is unmaintained + { id = "RUSTSEC-2026-0542", reason = "pulled in transitively by reth (reth-config/reth-cli-commands via humantime-serde); no patched release exists upstream" }, + # https://rustsec.org/advisories/RUSTSEC-2026-0543 chrono is unmaintained + { id = "RUSTSEC-2026-0543", reason = "pulled in transitively by reth (reth-tracing/reth-node-metrics/reth-node-ethstats); no patched release exists upstream" }, + # https://rustsec.org/advisories/RUSTSEC-2026-0620 curve25519-dalek AVX-512 backend arithmetic bug + { id = "RUSTSEC-2026-0620", reason = "curve25519-dalek 4.1.3 is pulled via ed25519-dalek 2.2.0 (enr/discv5); the fix (>=5.1.0) requires ed25519-dalek 3.x, which is not released. The bug only affects the AVX-512 backend, while we build on stable without avx512 cfg/target features; x25519 and the serial/simd backends are unaffected" }, ] # This section is considered when running `cargo deny check bans`. From 59edd1d553b96f806d5a9cc1ef84c5272c3cc1da Mon Sep 17 00:00:00 2001 From: panos Date: Fri, 4 Dec 2026 08:13:20 +0000 Subject: [PATCH 11/16] fix(revm): load the accounts behind protocol storage reads for execution witnesses The handler reads the L1 gas price oracle, the L2TokenRegistry entry and a slot-mode fee token's balance with untracked storage reads. evm2's untracked read caches the slot but not its account, and reth assembles debug_executionWitness from the cached accounts only, so the witness of a block with a token-fee MorphTx left out the registry (and, for a zero fee, the fee token) together with their storage proofs. go-ethereum's GetState loads the account before it reads a slot. Resolve the account through the same untracked path before reading the slot. Warmth and the journal are untouched, so execution and gas accounting do not change. Test fixtures now create the predeployed accounts that every Morph network has, since a cached absent account reads as empty storage. --- crates/evm/src/block/mod.rs | 5 + crates/node/tests/it/proof_history.rs | 46 ++++++- crates/revm/src/handler.rs | 178 +++++++++++++++++++++++++- 3 files changed, 223 insertions(+), 6 deletions(-) diff --git a/crates/evm/src/block/mod.rs b/crates/evm/src/block/mod.rs index 66bfaa3b..d5133a4d 100644 --- a/crates/evm/src/block/mod.rs +++ b/crates/evm/src/block/mod.rs @@ -807,6 +807,11 @@ mod tests { &U256::from(1_000_000u64), ); + // The registry is a predeploy, so it always exists in state. + db.insert_account_info( + &L2_TOKEN_REGISTRY_ADDRESS, + AccountInfo::default().with_nonce(1), + ); let token_id = 1u16; let mut token_id_bytes = [0u8; 32]; token_id_bytes[30..32].copy_from_slice(&token_id.to_be_bytes()); diff --git a/crates/node/tests/it/proof_history.rs b/crates/node/tests/it/proof_history.rs index 7d6aceee..72c80205 100644 --- a/crates/node/tests/it/proof_history.rs +++ b/crates/node/tests/it/proof_history.rs @@ -20,7 +20,8 @@ use morph_chainspec::MorphChainSpec; use morph_node::{ MorphAddOns, MorphNode, test_utils::{ - MorphTestNode, MorphTxBuilder, make_deploy_tx, morph_payload_attributes, wallet_at_index, + MorphTestNode, MorphTxBuilder, TEST_TOKEN_ID, make_deploy_tx, morph_payload_attributes, + wallet_at_index, }, }; use morph_payload_types::ExecutableL2Data; @@ -1484,3 +1485,46 @@ async fn proof_history_execution_witness_is_bounded_by_the_proof_window() -> eyr Ok(()) } + +/// A token-fee MorphTx prices its fee from the fee token's `L2TokenRegistry` entry, which the +/// handler reads outside the EVM. The witness must still carry the registry account and the +/// slots read from it, or a stateless re-execution of the block cannot charge the fee. +#[tokio::test(flavor = "multi_thread")] +async fn execution_witness_covers_the_token_registry_of_a_token_fee_morph_tx() -> eyre::Result<()> { + reth_tracing::init_test_tracing(); + + let mut env = setup(LaunchOpts::default()).await?; + let client = rpc_client(&env.node)?; + + let nonce = sender_nonce(&env.node)?; + let raw_tx = MorphTxBuilder::new(CHAIN_ID, signer(0), nonce) + .with_v0_token_fee(TEST_TOKEN_ID) + .build_signed()?; + let block_hash = include_tx(&mut env.node, raw_tx).await?; + wait_for_proof_tip(&client, 1).await?; + + let witness = execution_witness_by_hash(&client, block_hash).await?; + + let registry = alloy_primitives::address!("5300000000000000000000000000000000000021"); + assert!( + witness + .keys + .contains(&Bytes::copy_from_slice(registry.as_slice())), + "witness must carry the token registry account" + ); + + // `tokenRegistry[TEST_TOKEN_ID]` starts at keccak256(token_id ‖ 151) and holds the token + // address; the handler reads it first. + let mut preimage = [0u8; 64]; + preimage[30..32].copy_from_slice(&TEST_TOKEN_ID.to_be_bytes()); + preimage[32..].copy_from_slice(&U256::from(151).to_be_bytes::<32>()); + let token_info_slot = alloy_primitives::keccak256(preimage); + assert!( + witness + .keys + .contains(&Bytes::copy_from_slice(token_info_slot.as_slice())), + "witness must carry the registry slots the fee was priced from" + ); + + Ok(()) +} diff --git a/crates/revm/src/handler.rs b/crates/revm/src/handler.rs index d02a4cfb..09a1e702 100644 --- a/crates/revm/src/handler.rs +++ b/crates/revm/src/handler.rs @@ -27,7 +27,7 @@ use evm2::{ validate_nonce_not_overflow, validate_priority_fee, validate_tx_gas_limit_cap, warm_access_list, warm_base_accounts, }, - evm::State, + evm::{DbResult, State}, handler::GasSettlement, interpreter::{GasTracker, Host, Message, MessageExt, MessageKind, MessageResult, Word}, registry::{HandlerError, HandlerResult, TxRegistry, TxRequest, handler}, @@ -477,6 +477,24 @@ fn is_unencoded_rpc_simulation(host: &MorphEvm<'_>, tx: &MorphTxEnv) -> bool { && tx.rlp_bytes.as_ref().is_none_or(|bytes| bytes.is_empty()) } +/// Reads `slot` of `address` without warming or journaling either. +/// +/// go-ethereum's `StateDB.GetState` loads the account before it reads one of its slots, so an +/// execution witness built from what a block read carries the account together with its +/// storage. evm2's untracked slot read caches only the slot, and reth builds +/// `debug_executionWitness` from the accounts the execution cached, so the protocol's own reads +/// (the L1 gas price oracle, the token registry, a slot-mode fee token) would otherwise be left +/// out of the witness. The account is resolved through the same untracked path, which leaves +/// warmth and the journal untouched, so gas accounting does not change. +pub(crate) fn storage_slot_untracked_with_account( + state: &mut State<'_>, + address: &Address, + slot: &Word, +) -> DbResult { + state.account_info_untracked(address)?; + state.storage_slot_untracked(address, slot) +} + /// Fetches the L1 data fee parameters for this transaction and prices it. /// /// Must NOT use a per-block cache because the oracle can be updated by a regular transaction @@ -489,7 +507,7 @@ fn l1_data_fee(host: &mut MorphEvm<'_>, tx: &MorphTxEnv) -> HandlerResult let hardfork = host.config_spec_id(); let state = host.state_mut(); let l1_block_info = L1BlockInfo::try_fetch_with( - |slot| state.storage_slot_untracked(&L1_GAS_PRICE_ORACLE_ADDRESS, &slot), + |slot| storage_slot_untracked_with_account(state, &L1_GAS_PRICE_ORACLE_ADDRESS, &slot), hardfork, )?; let rlp_bytes = tx.rlp_bytes.as_ref().map(Bytes::as_ref).unwrap_or_default(); @@ -567,7 +585,7 @@ fn deduct_token_fee( let state = host.state_mut(); let token_registry_entry = TokenRegistryEntry::load_with( - |address, slot| state.storage_slot_untracked(&address, &slot), + |address, slot| storage_slot_untracked_with_account(state, &address, &slot), token_id, )? .ok_or(MorphInvalidTransaction::TokenNotRegistered(token_id))? @@ -735,7 +753,7 @@ fn reimburse_token_fee( let state = host.state_mut(); let Some((live_token_address, live_balance_slot)) = TokenRegistryEntry::load_transfer_target_with( - |address, slot| state.storage_slot_untracked(&address, &slot), + |address, slot| storage_slot_untracked_with_account(state, &address, &slot), token_id, )? else { @@ -943,7 +961,7 @@ fn load_token_fee_info( Some(slot) => { let state = host.state_mut(); read_balance_from_storage( - |address, slot| state.storage_slot_untracked(&address, &slot), + |address, slot| storage_slot_untracked_with_account(state, &address, &slot), entry.token_address(), caller, slot, @@ -1232,6 +1250,7 @@ mod tests { fn token_db_with_code(code: Bytes) -> InMemoryDB { let mut inner = InMemoryDB::default(); insert_contract(&mut inner, REFUND_PROBE_TOKEN, code); + insert_token_registry(&mut inner); let mut token_id_bytes = [0u8; 32]; token_id_bytes[30..32].copy_from_slice(&1u16.to_be_bytes()); let base = crate::token_fee::compute_mapping_slot(U256::from(151), &token_id_bytes); @@ -1407,6 +1426,17 @@ mod tests { assert_eq!(balance, U256::from_be_bytes(caller.into_word().0)); } + /// Puts the token registry in state, as it is on every Morph network, unless the test + /// already installed its own registry account. + fn insert_token_registry(db: &mut InMemoryDB) { + if !db.cache.accounts.contains_key(&L2_TOKEN_REGISTRY_ADDRESS) { + db.insert_account_info( + &L2_TOKEN_REGISTRY_ADDRESS, + AccountInfo::default().with_nonce(1), + ); + } + } + fn insert_test_fee_token(db: &mut InMemoryDB, token_id: u16, token: Address, is_active: bool) { insert_test_fee_token_config(db, token_id, token, is_active, U256::from(1), U256::from(1)); } @@ -1419,6 +1449,7 @@ mod tests { price_ratio: U256, scale: U256, ) { + insert_token_registry(db); let mut token_id_bytes = [0u8; 32]; token_id_bytes[30..32].copy_from_slice(&token_id.to_be_bytes()); let base = compute_mapping_slot(U256::from(151), &token_id_bytes); @@ -3268,6 +3299,132 @@ mod tests { b256!("6d2426d9b8d6f63ec1a38d3a4e7b88f318ebe9f0d837c4781852168c5bd2678e") ); } + + /// Addresses whose account, and whose storage, the backing database served. + #[derive(Debug, Default)] + struct ReadSet { + accounts: std::collections::HashSet
, + storage: std::collections::HashSet
, + } + + /// Records which accounts, and whose storage, execution reads from the backing database. + #[derive(Debug)] + struct ReadSetDb { + inner: InMemoryDB, + reads: Arc>, + } + + impl Database for ReadSetDb { + type Error = evm2::DatabaseError; + + fn get_account(&mut self, address: &Address) -> Result, Self::Error> { + self.reads.lock().unwrap().accounts.insert(*address); + DynDatabase::get_account(&mut self.inner, address) + } + + fn get_code_by_hash(&mut self, code_hash: &B256) -> Result { + DynDatabase::get_code_by_hash(&mut self.inner, code_hash) + } + + fn get_storage(&mut self, address: &Address, key: &Word) -> Result { + self.reads.lock().unwrap().storage.insert(*address); + DynDatabase::get_storage(&mut self.inner, address, key) + } + + fn get_block_hash(&mut self, number: &Word) -> Result { + DynDatabase::get_block_hash(&mut self.inner, number) + } + } + + /// Executes `tx` from [`FEE_REFUND_CALLER`] over `db` and returns, sorted, the addresses + /// whose storage the backing database served without also serving their account. + /// + /// reth assembles `debug_executionWitness` from the accounts the execution cached and only + /// carries storage for those accounts, so the slots of every address returned here are + /// missing from the witness. + fn storage_reads_without_account( + db: InMemoryDB, + block: MorphBlockEnv, + tx: MorphTxEnv, + ) -> Vec
{ + let reads = Arc::new(std::sync::Mutex::new(ReadSet::default())); + let database = ReadSetDb { + inner: db, + reads: Arc::clone(&reads), + }; + let mut evm = evm_on(Db::new(database), MorphHardfork::default(), block); + let result = + transact(&mut evm, tx, FEE_REFUND_CALLER).expect("token-fee MorphTx must execute"); + assert!(result.status, "expected success, got {result:?}"); + drop(evm); + + let reads = reads.lock().unwrap(); + let mut missing: Vec<_> = reads.storage.difference(&reads.accounts).copied().collect(); + missing.sort(); + missing + } + + /// Registers [`FEE_REFUND_TOKEN`] in slot mode, with its balances in a mapping at slot 0. + fn slot_mode_token_db(payer_token_balance: U256) -> InMemoryDB { + let mut db = InMemoryDB::default(); + db.insert_account_info(&FEE_REFUND_CALLER, AccountInfo::default()); + insert_contract(&mut db, FEE_REFUND_TOKEN, fee_refund_slotless_erc20_code()); + insert_test_fee_token(&mut db, FEE_REFUND_TOKEN_ID, FEE_REFUND_TOKEN, true); + + // The registry stores the balance mapping's slot plus one; zero means call mode. + let mut token_id = [0u8; 32]; + token_id[30..].copy_from_slice(&FEE_REFUND_TOKEN_ID.to_be_bytes()); + let base = compute_mapping_slot(U256::from(151), &token_id); + db.insert_account_storage( + &L2_TOKEN_REGISTRY_ADDRESS, + &(base + U256::from(1)), + &U256::from(1), + ); + db.insert_account_storage( + &FEE_REFUND_TOKEN, + &compute_mapping_slot_for_address(U256::ZERO, FEE_REFUND_CALLER), + &payer_token_balance, + ); + db + } + + /// go-ethereum's `GetState` loads the account before it reads a slot, so the gas price + /// oracle, the token registry and a slot-mode fee token all end up in the execution witness + /// with their storage. The handler's protocol reads must load the account too. + #[test] + fn protocol_storage_reads_also_read_the_account() { + let fee = U256::from(FEE_REFUND_TOKEN_FEE); + + // Call mode: `balanceOf` and `transfer` run the token, the registry is only read. + assert_eq!( + storage_reads_without_account(fee_refund_db(fee), fee_refund_block(), fee_refund_tx()), + Vec::
::new(), + "call-mode token fee" + ); + + // Slot mode: the fee moves through direct writes to the token's storage. + let db = slot_mode_token_db(fee); + assert_eq!( + storage_reads_without_account(db, fee_refund_block(), fee_refund_tx()), + Vec::
::new(), + "slot-mode token fee" + ); + + // A zero fee still reads the caller's token balance, but moves nothing. + let free_block = MorphBlockEnv { + basefee: U256::ZERO, + ..fee_refund_block() + }; + let free_tx = MorphTxEnv { + gas_price: 0, + ..fee_refund_tx() + }; + assert_eq!( + storage_reads_without_account(slot_mode_token_db(fee), free_block, free_tx), + Vec::
::new(), + "zero slot-mode token fee" + ); + } } /// Alt-token refund rounding, gated on Celadon. @@ -3333,6 +3490,11 @@ mod refund_rounding_tests { /// /// `balanceSlot` is stored one-based, so zero there means "call mode". fn register_slot_mode_token(db: &mut InMemoryDB) { + // The registry is a predeploy, so it always exists in state. + db.insert_account_info( + &L2_TOKEN_REGISTRY_ADDRESS, + AccountInfo::default().with_nonce(1), + ); let mut token_id_bytes = [0u8; 32]; token_id_bytes[30..32].copy_from_slice(&FEE_TOKEN_ID.to_be_bytes()); let base = compute_mapping_slot(U256::from(151), &token_id_bytes); @@ -3979,6 +4141,11 @@ mod refund_rounding_tests { }; let mut db = InMemoryDB::default(); + // The gas price oracle is a predeploy, so it always exists in state. + db.insert_account_info( + &L1_GAS_PRICE_ORACLE_ADDRESS, + AccountInfo::default().with_nonce(1), + ); db.insert_account_storage( &L1_GAS_PRICE_ORACLE_ADDRESS, &GPO_L1_BASE_FEE_SLOT, @@ -4102,6 +4269,7 @@ mod refund_rounding_tests { db.insert_account_storage(&L2_TOKEN_REGISTRY_ADDRESS, &price_slot, &U256::from(2u64)); // Fund caller with 1_000_000 units in `token_a` slot-0 mapping. + db.insert_account_info(&token_a, AccountInfo::default().with_nonce(1)); let caller_slot_a = compute_mapping_slot_for_address(U256::ZERO, caller); db.insert_account_storage(&token_a, &caller_slot_a, &U256::from(1_000_000u64)); db.insert_account_info( From c8e6d894742f8cffd572bd327231160d6565e869 Mon Sep 17 00:00:00 2001 From: panos Date: Fri, 4 Dec 2026 08:17:13 +0000 Subject: [PATCH 12/16] fix(evm): keep fee token Transfer logs in eth_simulateV1 with traceTransfers With traceTransfers, upstream eth_simulateV1 replaces each call's logs with the ones its TransferInspector collected. That inspector only collects logs through its log hook, which FeeFrameFilter suppresses inside fee frames, so the fee token's deduction and refund Transfer logs disappeared from the result even though the receipt carries them. Install TransferInspector without FeeFrameFilter. It only records logs and ETH transfers, and the fee frames move no ETH, so it now reports the receipt's logs plus the synthetic transfer logs. Call, prestate and other tracers still do not see the fee frames. The dependency sits behind the rpc feature, so zkVM builds are unchanged. --- Cargo.lock | 1 + crates/evm/Cargo.toml | 8 ++++- crates/evm/src/evm.rs | 60 ++++++++++++++++++++++++++++++++++++- crates/node/tests/it/rpc.rs | 51 ++++++++++++++++++------------- crates/revm/src/evm.rs | 7 +++-- 5 files changed, 101 insertions(+), 26 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index cb0fb300..006c9e72 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5349,6 +5349,7 @@ dependencies = [ "alloy-rpc-types-eth", "derive_more", "evm2", + "evm2-inspectors", "morph-chainspec", "morph-payload-types", "morph-primitives", diff --git a/crates/evm/Cargo.toml b/crates/evm/Cargo.toml index a484b6a9..79cef8b4 100644 --- a/crates/evm/Cargo.toml +++ b/crates/evm/Cargo.toml @@ -26,6 +26,7 @@ reth-primitives-traits.workspace = true reth-rpc-eth-api = { workspace = true, optional = true } evm2 = { workspace = true, features = ["std"] } +evm2-inspectors = { workspace = true, optional = true } alloy-consensus.workspace = true alloy-eip7928.workspace = true @@ -57,4 +58,9 @@ std = [ "reth-execution-types/std", ] engine = ["std", "dep:morph-payload-types"] -rpc = ["std", "dep:reth-rpc-eth-api", "morph-primitives/reth-codec"] +rpc = [ + "std", + "dep:evm2-inspectors", + "dep:reth-rpc-eth-api", + "morph-primitives/reth-codec", +] diff --git a/crates/evm/src/evm.rs b/crates/evm/src/evm.rs index a32550ca..01c74c16 100644 --- a/crates/evm/src/evm.rs +++ b/crates/evm/src/evm.rs @@ -13,6 +13,9 @@ use morph_revm::{FeeFrameFilter, MorphEvmEnv, MorphEvmTypes, MorphTxEnv}; use reth_evm::{BlockExecutionError, Evm}; use std::ops::{Deref, DerefMut}; +#[cfg(feature = "rpc")] +use evm2_inspectors::transfer::TransferInspector; + /// Marker for the EVM a [`crate::MorphEvmConfig`] creates. #[derive(Debug, Default, Clone, Copy)] #[non_exhaustive] @@ -115,10 +118,30 @@ where Some(Box::new(installed.0.into_inner())) } +/// Whether an inspector of type `I` is installed without [`FeeFrameFilter`]. +/// +/// `eth_simulateV1` reports the logs its `TransferInspector` collected in place of the EVM's own +/// logs (`simulate::execute_transactions`), so hiding the fee frames from it drops the fee +/// token's `Transfer` logs that the transaction's receipt carries. It only collects logs and ETH +/// transfers, and the fee frames move no ETH, so unfiltered it reports the receipt's logs plus +/// the synthetic ETH transfer logs. +fn sees_fee_frames() -> bool { + #[cfg(feature = "rpc")] + { + TypeId::of::() == TypeId::of::() + } + #[cfg(not(feature = "rpc"))] + { + false + } +} + /// A configured Morph EVM. /// /// Wraps the evm2 instance so that every inspector installed on it goes through -/// [`FeeFrameFilter`]: tracers must see a token-fee transaction without its fee frames. +/// [`FeeFrameFilter`]: tracers must see a token-fee transaction without its fee frames. The one +/// exception is the log collector of `eth_simulateV1`, which must report the fee logs a receipt +/// carries (see `sees_fee_frames`). #[expect(missing_debug_implementations)] pub struct MorphEvm<'a> { inner: morph_revm::MorphEvm<'a>, @@ -188,6 +211,9 @@ impl<'a> Evm for MorphEvm<'a> { I: Inspector + 'static, { self.unwrap_inspector = None; + if sees_fee_frames::() { + return Evm::transact_with_inspector(&mut self.inner, transaction, inspector); + } let (filter, result) = Evm::transact_with_inspector( &mut self.inner, transaction, @@ -200,6 +226,11 @@ impl<'a> Evm for MorphEvm<'a> { where I: Inspector + 'static, { + if sees_fee_frames::() { + Evm::set_inspector(&mut self.inner, inspector); + self.unwrap_inspector = None; + return; + } Evm::set_inspector( &mut self.inner, InstalledInspector(FeeFrameFilter::new(inspector)), @@ -413,4 +444,31 @@ mod tests { TypeId::of::>>() ); } + + /// `eth_simulateV1` installs `TransferInspector` through `Evm::set_inspector` and reads it + /// back with `Evm::with_inspector`; it must be installed as itself, not behind the filter. + #[cfg(feature = "rpc")] + #[test] + fn transfer_inspector_is_installed_without_the_fee_frame_filter() { + use evm2_inspectors::transfer::TransferInspector; + + let env = morph_evm_env( + MorphHardfork::default(), + 1, + 30_000_000, + MorphBlockEnv::default(), + ); + let mut evm = MorphEvm::new(InMemoryDB::default(), env); + Evm::set_inspector(&mut evm, TransferInspector::new(false).with_logs(true)); + + let installed: &dyn NonStaticAny = &**evm.inspector_mut().expect("inspector installed"); + assert_eq!(installed.type_id(), TypeId::of::()); + // SAFETY: `TransferInspector` has no lifetime parameters. + let found = unsafe { Evm::with_inspector::(&mut evm, |_| ()) }; + assert!(found.is_some()); + + let taken = Evm::take_inspector(&mut evm).expect("inspector was installed"); + let erased: &dyn NonStaticAny = &*taken; + assert_eq!(erased.type_id(), TypeId::of::()); + } } diff --git a/crates/node/tests/it/rpc.rs b/crates/node/tests/it/rpc.rs index eaac1b78..40c5766d 100644 --- a/crates/node/tests/it/rpc.rs +++ b/crates/node/tests/it/rpc.rs @@ -2283,32 +2283,41 @@ async fn eth_simulate_v1_morph_l1_fee_and_token_semantics() -> eyre::Result<()> .await .expect_err("token-fee MorphTx must fail when feeLimit omits Curie blob L1 fee"); + let mut token_fee_request = serde_json::json!({ + "blockStateCalls": [{ + "calls": [{ + "from": funded, + "to": recipient, + "gas": format!("{gas_limit:#x}"), + "maxFeePerGas": format!("{max_fee_per_gas:#x}"), + "maxPriorityFeePerGas": format!("{max_priority_fee_per_gas:#x}"), + "feeTokenID": format!("{TEST_TOKEN_ID:#x}"), + "feeLimit": format!("{:#x}", l2_max_fee + full_l1_fee * U256::from(2u64)), + "input": calldata.to_string(), + }], + }], + "validation": true, + }); let morph_blocks: Value = client - .request( - "eth_simulateV1", - ( - serde_json::json!({ - "blockStateCalls": [{ - "calls": [{ - "from": funded, - "to": recipient, - "gas": format!("{gas_limit:#x}"), - "maxFeePerGas": format!("{max_fee_per_gas:#x}"), - "maxPriorityFeePerGas": format!("{max_priority_fee_per_gas:#x}"), - "feeTokenID": format!("{TEST_TOKEN_ID:#x}"), - "feeLimit": format!("{:#x}", l2_max_fee + full_l1_fee * U256::from(2u64)), - "input": calldata.to_string(), - }], - }], - "validation": true, - }), - "latest", - ), - ) + .request("eth_simulateV1", (token_fee_request.clone(), "latest")) .await?; let morph_call = &morph_blocks[0]["calls"][0]; assert_eq!(morph_call["status"].as_str(), Some("0x1")); assert!(has_transfer_log(morph_call)); + + // With `traceTransfers`, upstream replaces the call's logs with the ones its transfer + // tracer collected. That tracer must still see the fee token's `Transfer` logs: the call + // moves no ETH, so the traced logs are exactly the untraced ones. + token_fee_request["traceTransfers"] = Value::Bool(true); + let traced_blocks: Value = client + .request("eth_simulateV1", (token_fee_request, "latest")) + .await?; + let traced_call = &traced_blocks[0]["calls"][0]; + assert_eq!(traced_call["status"].as_str(), Some("0x1")); + assert_eq!( + traced_call["logs"], morph_call["logs"], + "traceTransfers must keep the fee token's Transfer logs" + ); } // ------------------------------------------------------------------------- diff --git a/crates/revm/src/evm.rs b/crates/revm/src/evm.rs index 83688a8c..c42be2fe 100644 --- a/crates/revm/src/evm.rs +++ b/crates/revm/src/evm.rs @@ -201,9 +201,10 @@ pub fn morph_evm<'a>(database: impl DynDatabase + 'a, env: MorphEvmEnv) -> Morph /// /// go-ethereum wraps those calls in `OnSystemCallStart`/`OnSystemCallEnd`, so tracers do not see /// them as part of the transaction. evm2 inspects every message it runs, and exposes no way for -/// a handler to pause the inspector, so every inspector installed on a Morph EVM goes through -/// this filter, which ignores everything between the start and end of a -/// [`MorphMessageExt::fee_frame`] frame. +/// a handler to pause the inspector, so the inspectors installed on a Morph EVM go through this +/// filter, which ignores everything between the start and end of a +/// [`MorphMessageExt::fee_frame`] frame. `eth_simulateV1`'s log collector is installed without +/// it, because its logs replace the receipt's and must keep the fee token's `Transfer` logs. #[derive(Debug)] pub struct FeeFrameFilter { inner: I, From 82854d024f6b7d2dca1e6a2c1b98072bf4f9e98c Mon Sep 17 00:00:00 2001 From: panos Date: Fri, 4 Dec 2026 08:44:21 +0000 Subject: [PATCH 13/16] chore: spell workspace lint names in snake_case Cargo 1.100, the stable toolchain CI builds with, deprecates hyphenated lint names in `[lints]` tables. It warns once per lint for the workspace manifest and for each of the 16 member manifests inheriting the table, 187 warnings per build. Upstream reth has spelled them in snake_case since v1.0.0. Cargo still passes rustc every lint at the same level. --- Cargo.toml | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 6830c847..79c0e68b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -28,19 +28,19 @@ members = [ [workspace.lints] [workspace.lints.clippy] -dbg-macro = "warn" -manual-string-new = "warn" -uninlined-format-args = "warn" -use-self = "warn" -redundant-clone = "warn" -default-constructed-unit-structs = "allow" +dbg_macro = "warn" +manual_string_new = "warn" +uninlined_format_args = "warn" +use_self = "warn" +redundant_clone = "warn" +default_constructed_unit_structs = "allow" [workspace.lints.rust] -rust-2018-idioms = "warn" -unreachable-pub = "warn" -unused-must-use = "warn" -redundant-lifetimes = "warn" -unnameable-types = "warn" +rust_2018_idioms = "warn" +unreachable_pub = "warn" +unused_must_use = "warn" +redundant_lifetimes = "warn" +unnameable_types = "warn" [workspace.lints.rustdoc] all = "warn" From 4b258d29ca549a16e3956bfc5dbb28ba8eaf3da8 Mon Sep 17 00:00:00 2001 From: panos Date: Fri, 4 Dec 2026 08:45:33 +0000 Subject: [PATCH 14/16] chore: drop unused workspace dependencies Cargo 1.100 warns about every `[workspace.dependencies]` entry that no member inherits. 37 of these 38 were already unused on main; `alloy-sol-types` lost its last user in the evm2 migration. The resolved dependency graph and Cargo.lock are unchanged. --- Cargo.toml | 38 -------------------------------------- 1 file changed, 38 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 79c0e68b..0bb4f93d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -126,24 +126,18 @@ reth-cli-commands = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11. reth-cli-runner = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } reth-cli-util = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } reth-codecs = { version = "0.8.2", default-features = false } -reth-codecs-derive = "0.8.2" reth-consensus = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } reth-consensus-common = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } reth-db = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } reth-db-api = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } reth-e2e-test-utils = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } reth-engine-local = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } -reth-engine-primitives = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } reth-engine-tree = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } reth-errors = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } reth-exex = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } reth-exex-test-utils = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } reth-execution-errors = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } -reth-eth-wire-types = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } -reth-ethereum = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } reth-ethereum-cli = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } -reth-ethereum-consensus = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } -reth-ethereum-engine-primitives = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } reth-ethereum-primitives = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0", default-features = false } reth-evm = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0", default-features = false } reth-evm-ethereum = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0", default-features = false } @@ -155,7 +149,6 @@ reth-node-api = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } reth-node-builder = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } reth-node-core = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } reth-node-ethereum = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } -reth-node-metrics = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } reth-payload-builder = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } reth-payload-primitives = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } reth-payload-util = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } @@ -181,7 +174,6 @@ reth-transaction-pool = { git = "https://github.com/paradigmxyz/reth", tag = "v2 reth-zstd-compressors = { version = "0.8.2", default-features = false } reth-execution-cache = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } reth-trie-parallel = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } -reth-trie-sparse = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0", default-features = false } # evm2 has no release yet; this is the rev reth v2.11.0 declares, overridden by the # `[patch]` below to match reth's own `[patch]` section. @@ -189,16 +181,13 @@ evm2 = { git = "https://github.com/alloy-rs/evm2", rev = "66687c18b34d3bdbb899f5 evm2-inspectors = { git = "https://github.com/alloy-rs/evm2", rev = "66687c18b34d3bdbb899f5eb7605070615c03475", default-features = false } evm2-macros = { git = "https://github.com/alloy-rs/evm2", rev = "66687c18b34d3bdbb899f5eb7605070615c03475" } -alloy = { version = "2.5.0", default-features = false } alloy-consensus = { version = "2.5.0", default-features = false } -alloy-contract = { version = "2.5.0", default-features = false } alloy-eip7928 = { version = "0.4.10", default-features = false } alloy-eips = { version = "2.5.0", default-features = false } alloy-genesis = "2.5.0" alloy-hardforks = "0.4.11" alloy-network = { version = "2.5.0", default-features = false } alloy-primitives = { version = "1.6.1", default-features = false } -alloy-provider = { version = "2.5.0", default-features = false } alloy-rlp = "0.3.16" alloy-trie = "0.9.9" alloy-rpc-types-debug = "2.5.0" @@ -207,60 +196,33 @@ alloy-rpc-types-eth = { version = "2.5.0" } alloy-serde = "2.5.0" alloy-signer = "2.5.0" alloy-signer-local = "2.5.0" -alloy-sol-types = { version = "1.6.1", default-features = false } -alloy-transport = "2.5.0" alloy-chains = { version = "0.2.33", default-features = false } -crossbeam-channel = "0.5.13" -arbitrary = { version = "1.3", features = ["derive"] } -async-lock = "3.4.1" async-trait = "0.1.92" auto_impl = "1" -axum = "0.8.4" -base64 = "0.22" -blake3 = "1.8" bytes = "1.8" bincode = "2" clap = { version = "4.5.45", features = ["derive"] } -const-hex = { version = "1.15.0" } dashmap = "6.0" derive_more = { version = "2.0.0" } eyre = "0.6.14" futures = "0.3.31" -governor = "0.10.2" -indexmap = "2.11.0" -indicatif = "0.18" -itertools = "0.14.0" -jiff = { version = "0.2.15", default-features = false } jsonrpsee = { version = "0.26.0", features = ["server", "client", "macros"] } metrics = "0.24.0" mockall = "0.14" -p256 = "0.13" parking_lot = "0.12.4" -prometheus-client = "0.24.0" -proptest = "1.7" -proptest-arbitrary-interop = "0.1.0" rand = "0.8.5" -rand_core = "0.6.4" rayon = "1.10" serde = { version = "1.0.219", features = ["derive"] } serde_json = "1.0.142" -strum = { version = "0.27", default-features = false } sha2 = "0.10" tempfile = "3.20.0" -test-fuzz = "7" thiserror = "2.0.14" # TODO: restrict this to only the required features tokio = { version = "1.45.1", features = ["full"] } tokio-stream = "0.1.17" -tokio-util = "0.7.16" tracing = "0.1.41" -tracing-subscriber = "0.3.22" vergen = "10.0.1" vergen-git2 = "10.0.1" -criterion = "0.7.0" -test-case = "3" -pyroscope = "0.5.8" -pyroscope_pprofrs = "0.2.10" # Patches only take effect at the root workspace, so reth v2.11.0's own overrides are # repeated here. Keep both sections identical to the `[patch]` sections of the pinned reth From bd5ec4e075c3d01797de224b76bf1d0d7b7782fc Mon Sep 17 00:00:00 2001 From: panos-xyz Date: Sun, 6 Dec 2026 16:37:00 +0800 Subject: [PATCH 15/16] fix(revm): gate MorphTxEnv::uses_token_fee on MorphTx type Standard Ethereum transactions (0x00/0x01/0x02/0x04) carrying stray Morph fee fields in MorphTxEnv were charged upfront ETH in prepare() (which checked is_morph_tx() && token_id > 0) while execute() skipped ETH caller refund and beneficiary reward via None if tx.uses_token_fee() => {} because uses_token_fee() omitted is_morph_tx(). - Gate MorphTxEnv::uses_token_fee() and has_reference() on self.is_morph_tx(), and use tx.uses_token_fee() in prepare() so deduction and settlement share one predicate. - Route MorphEthApi::caller_gas_allowance through tx_env.uses_token_fee() on both eth_call and eth_estimateGas paths. - Populate MorphTx extension fields in morph-statetest schema only when tx.is_morph_tx(), matching morph-geth toMessage. --- bin/morph-statetest/src/schema.rs | 116 ++++++++++++++---- crates/revm/src/handler.rs | 86 ++++++++++++- crates/revm/src/tx.rs | 48 +++++++- crates/rpc/src/eth/call.rs | 192 ++++++++++++++++++++++-------- 4 files changed, 369 insertions(+), 73 deletions(-) diff --git a/bin/morph-statetest/src/schema.rs b/bin/morph-statetest/src/schema.rs index c85b3b68..1a07230e 100644 --- a/bin/morph-statetest/src/schema.rs +++ b/bin/morph-statetest/src/schema.rs @@ -353,28 +353,33 @@ impl MorphTransactionParts { ..Default::default() }; - if let Some(version) = self.version { - tx = tx.with_version(version); - } else if tx.is_morph_tx() && self.authorization_list.is_some() { - // Only V2 may carry an `authorizationList` field, so its presence - // (even `[]`) selects V2 instead of leaving the version unset, which - // the handler would treat as V0. Presence rather than length is the - // same convention `tx_type` uses to select 0x04. - tx = tx.with_version(MORPH_TX_VERSION_2); - } - if let Some(fee_token_id) = self.fee_token_id { - tx = tx.with_fee_token_id(fee_token_id); - } - if let Some(fee_limit) = self.fee_limit { - tx = tx.with_fee_limit(fee_limit); - } - if let Some(reference) = self.reference { - tx = tx.with_reference(reference); - } - if let Some(memo) = &self.memo - && !memo.is_empty() - { - tx = tx.with_memo(memo.clone()); + // Match morph-geth `tests/state_test_util.go` (`toMessage`): MorphTx extension fields + // (`version`, `feeTokenID`, `feeLimit`, `reference`, `memo`) are only populated when + // `type == 0x7f`; standard transactions carrying them in negative/fuzz fixtures ignore them. + if tx.is_morph_tx() { + if let Some(version) = self.version { + tx = tx.with_version(version); + } else if self.authorization_list.is_some() { + // Only V2 may carry an `authorizationList` field, so its presence + // (even `[]`) selects V2 instead of leaving the version unset, which + // the handler would treat as V0. Presence rather than length is the + // same convention `tx_type` uses to select 0x04. + tx = tx.with_version(MORPH_TX_VERSION_2); + } + if let Some(fee_token_id) = self.fee_token_id { + tx = tx.with_fee_token_id(fee_token_id); + } + if let Some(fee_limit) = self.fee_limit { + tx = tx.with_fee_limit(fee_limit); + } + if let Some(reference) = self.reference { + tx = tx.with_reference(reference); + } + if let Some(memo) = &self.memo + && !memo.is_empty() + { + tx = tx.with_memo(memo.clone()); + } } if let Some(txbytes) = txbytes { tx = tx.with_rlp_bytes(txbytes); @@ -707,4 +712,71 @@ mod tests { ), } } + + #[test] + fn standard_typed_tx_ignores_morph_extension_fields() { + for (tx_type_json, fee_fields) in [ + ("0x1", r#""gasPrice": "0x10","#), + ( + "0x2", + r#""maxFeePerGas": "0x10", "maxPriorityFeePerGas": "0x1","#, + ), + ] { + let raw = format!( + r#"{{ + "case": {{ + "env": {{ + "currentChainID": "0x1", + "currentCoinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "currentDifficulty": "0x20000", + "currentGasLimit": "0x1c9c380", + "currentNumber": "0x1", + "currentTimestamp": "0x3e8", + "currentBaseFee": "0x0" + }}, + "pre": {{}}, + "transaction": {{ + "type": "{tx_type_json}", + "nonce": "0x0", + {fee_fields} + "gasLimit": ["0x7a1200"], + "to": "0x00000000000000000000000000000000000000f1", + "value": ["0x0"], + "data": ["0x"], + "accessLists": [null], + "feeTokenID": "0x1", + "feeLimit": "0xf4240", + "version": "0x0", + "reference": "0x00000000000000000000000000000000000000000000000000000000000000aa", + "memo": "0xdeadbeef", + "secretKey": "0x45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8" + }}, + "post": {{ + "Jade": [{{ + "indexes": {{ "data": 0, "gas": 0, "value": 0 }}, + "hash": "0x0000000000000000000000000000000000000000000000000000000000000000", + "logs": "0x0000000000000000000000000000000000000000000000000000000000000000", + "expectException": null + }}] + }} + }} + }}"# + ); + let suite: MorphTestSuite = serde_json::from_str(&raw).expect("suite should parse"); + let unit = suite.0.values().next().unwrap(); + let post = &unit.post["Jade"][0]; + let tx = unit + .morph_tx_env(post, MorphHardfork::Jade) + .expect("tx env should build") + .env; + + assert!(!tx.is_morph_tx()); + assert!(!tx.uses_token_fee()); + assert_eq!(tx.version, None); + assert_eq!(tx.fee_token_id, None); + assert_eq!(tx.fee_limit, None); + assert_eq!(tx.reference, None); + assert_eq!(tx.memo, None); + } + } } diff --git a/crates/revm/src/handler.rs b/crates/revm/src/handler.rs index 09a1e702..8cfe89b9 100644 --- a/crates/revm/src/handler.rs +++ b/crates/revm/src/handler.rs @@ -178,8 +178,8 @@ fn prepare(req: &mut MorphTxRequest<'_, '_>) -> HandlerResult { validate_intrinsic_gas(tx.gas_limit, intrinsic, 0)?; validate_floor_gas(tx.gas_limit, floor_gas)?; - let token_id = tx.fee_token_id.unwrap_or_default(); - let charged = if tx.is_morph_tx() && token_id > 0 { + let charged = if tx.uses_token_fee() { + let token_id = tx.fee_token_id.unwrap_or_default(); deduct_token_fee(host, tx, caller, gas_price, token_id)? } else { deduct_eth_fee(host, tx, caller)? @@ -4399,4 +4399,86 @@ mod refund_rounding_tests { U256::ZERO ); } + + /// Regression test: if a standard typed `MorphTxEnv` (`0x00`/`0x01`/`0x02`) is constructed + /// with `fee_token_id: Some(> 0)`, `prepare` charges ETH and `execute` must still refund + /// unused ETH to `caller` and pay the ETH fee + L1 data fee to `beneficiary` instead of + /// short-circuiting on `None if tx.uses_token_fee() => {}` and burning the upfront deduction. + #[test] + fn standard_tx_with_stray_fee_token_id_still_refunds_caller_and_pays_beneficiary() { + let caller = address!("1000000000000000000000000000000000000001"); + let callee = address!("1000000000000000000000000000000000000002"); + let beneficiary = address!("2adc25665018aa1fe0e6bc666dac8fc2697ff9ba"); + let initial_balance = U256::from(1_000_000_000u64); + + for tx_type in [LEGACY_TX_TYPE, EIP2930_TX_TYPE, EIP1559_TX_TYPE] { + let mut db = InMemoryDB::default(); + db.insert_account_info( + &caller, + AccountInfo::default().with_balance(initial_balance), + ); + + let blk = MorphBlockEnv { + number: U256::from(1u64), + beneficiary, + timestamp: U256::from(1_000u64), + gas_limit: U256::from(30_000_000u64), + basefee: U256::ZERO, + ..Default::default() + }; + let mut evm = morph_evm(db, morph_evm_env(MorphHardfork::Jade, 1, 30_000_000, blk)); + + let gas_limit = 100_000u64; + let gas_price = 16u128; + let tx = Recovered::new_unchecked( + MorphTxEnv { + tx_type, + chain_id: Some(1), + kind: TxKind::Call(callee), + gas_limit, + gas_price, + gas_priority_fee: (tx_type == EIP1559_TX_TYPE).then_some(1), + fee_token_id: Some(1), + fee_limit: Some(U256::from(1_000_000u64)), + version: Some(0), + ..Default::default() + }, + caller, + ); + + let effective_price = U256::from(tx.inner().effective_gas_price_at(0)); + let result = evm + .transact(&tx) + .expect("standard tx must execute on ETH path") + .commit(); + assert!(result.status); + assert_eq!(result.tx_gas_used(), 21_000); + assert!(result.ext.token_fee_info.is_none()); + + let expected_fee = + effective_price * U256::from(result.tx_gas_used()) + result.ext.l1_data_fee; + let caller_after = evm + .state_mut() + .account_info_untracked(&caller) + .unwrap() + .unwrap() + .balance; + let beneficiary_after = evm + .state_mut() + .account_info_untracked(&beneficiary) + .unwrap() + .unwrap() + .balance; + + assert_eq!( + caller_after, + initial_balance - expected_fee, + "tx_type {tx_type:#x}: unused gas must be refunded to caller" + ); + assert_eq!( + beneficiary_after, expected_fee, + "tx_type {tx_type:#x}: spent gas + L1 fee must be paid to beneficiary" + ); + } + } } diff --git a/crates/revm/src/tx.rs b/crates/revm/src/tx.rs index add3032b..246efa4c 100644 --- a/crates/revm/src/tx.rs +++ b/crates/revm/src/tx.rs @@ -601,12 +601,12 @@ impl MorphTxExt for MorphTxEnv { #[inline] fn uses_token_fee(&self) -> bool { - self.fee_token_id.is_some_and(|id| id > 0) + self.is_morph_tx() && self.fee_token_id.is_some_and(|id| id > 0) } #[inline] fn has_reference(&self) -> bool { - self.reference.is_some() + self.is_morph_tx() && self.reference.is_some() } } @@ -645,6 +645,50 @@ mod tests { assert!(!tx.is_l1_msg()); } + #[test] + fn morph_tx_ext_gates_token_fee_and_reference_on_morph_tx_type() { + let reference = B256::with_last_byte(0xaa); + for tx_type in [ + LEGACY_TX_TYPE, + EIP2930_TX_TYPE, + EIP1559_TX_TYPE, + EIP7702_TX_TYPE, + L1_TX_TYPE_ID, + ] { + let non_morph = MorphTxEnv { + tx_type, + fee_token_id: Some(1), + reference: Some(reference), + ..Default::default() + }; + assert!( + !non_morph.uses_token_fee(), + "non-MorphTx type {tx_type:#x} must never report uses_token_fee()" + ); + assert!( + !non_morph.has_reference(), + "non-MorphTx type {tx_type:#x} must never report has_reference()" + ); + } + + let morph_eth_fee = MorphTxEnv { + tx_type: MORPH_TX_TYPE_ID, + fee_token_id: Some(0), + reference: Some(reference), + ..Default::default() + }; + assert!(!morph_eth_fee.uses_token_fee()); + assert!(morph_eth_fee.has_reference()); + + let morph_token_fee = MorphTxEnv { + tx_type: MORPH_TX_TYPE_ID, + fee_token_id: Some(1), + ..Default::default() + }; + assert!(morph_token_fee.uses_token_fee()); + assert!(!morph_token_fee.has_reference()); + } + #[test] fn typed_2718_reports_the_type_byte() { let tx = MorphTxEnv { diff --git a/crates/rpc/src/eth/call.rs b/crates/rpc/src/eth/call.rs index f0150013..135ba936 100644 --- a/crates/rpc/src/eth/call.rs +++ b/crates/rpc/src/eth/call.rs @@ -362,57 +362,24 @@ where .version() .feature(EvmFeatures::BLOCK_GAS_LIMIT_CHECK) { - let allowance = if tx_env.fee_token_id.is_some_and(|id| id > 0) { - u64::MAX - } else { - let balance = db - .get_account(&tx_env.signer()) - .map_err(|e| MorphEthApiError::Eth(e.into()))? - .map(|account| account.balance) - .unwrap_or_default(); - let available = balance - .checked_sub(tx_env.value) - .ok_or(MorphEthApiError::InsufficientFundsForTransfer)?; - gas_allowance_from_balance(available, tx_env.gas_price) - }; - return Ok(cap_call_gas_allowance(allowance, self.call_gas_limit())); + return call_gas_allowance( + &mut db, + tx_env.inner(), + tx_env.signer(), + self.call_gas_limit(), + ); } // eth_estimateGas path. let l1_fee = self.estimate_l1_fee(&mut db, evm_env, tx_env)?; - - let allowance = if let Some(fee_token_id) = tx_env.fee_token_id.filter(|id| *id > 0) { - load_caller_token_gas_allowance( - &mut db, - evm_env, - tx_env.signer(), - tx_env.value, - l1_fee, - fee_token_id, - tx_env.fee_limit, - tx_env.gas_price, - )? - } else { - // allowance = (balance − value − l1_fee) / gas_price, done at wei - // precision so the remainder is not lost across the two - // subtractions. - let balance = db - .get_account(&tx_env.signer()) - .map_err(|e| MorphEthApiError::Eth(e.into()))? - .map(|acc| acc.balance) - .unwrap_or_default(); - let available = balance - .checked_sub(tx_env.value) - .ok_or(MorphEthApiError::InsufficientFundsForTransfer)?; - // Reject at `l1_fee >= available` so the RPC surfaces the real - // reason rather than a downstream "gas required exceeds allowance 0". - if l1_fee >= available { - return Err(MorphEthApiError::InsufficientFundsForL1Fee); - } - gas_allowance_from_balance(available - l1_fee, tx_env.gas_price) - }; - - Ok(cap_call_gas_allowance(allowance, self.call_gas_limit())) + estimate_gas_allowance( + &mut db, + evm_env, + tx_env.inner(), + tx_env.signer(), + l1_fee, + self.call_gas_limit(), + ) } } @@ -492,6 +459,84 @@ fn cap_call_gas_allowance(allowance: u64, gas_cap: u64) -> u64 { } } +/// Computes the caller's gas allowance on `eth_call` and sibling call/trace paths +/// (`!BLOCK_GAS_LIMIT_CHECK`), where L1 fees are not capped. +fn call_gas_allowance( + db: &mut DB, + tx_env: &MorphTxEnv, + caller: Address, + gas_cap: u64, +) -> Result +where + DB: Database, + DB::Error: Into, +{ + let allowance = if tx_env.uses_token_fee() { + u64::MAX + } else { + let balance = db + .get_account(&caller) + .map_err(|e| MorphEthApiError::Eth(e.into()))? + .map(|account| account.balance) + .unwrap_or_default(); + let available = balance + .checked_sub(tx_env.value) + .ok_or(MorphEthApiError::InsufficientFundsForTransfer)?; + gas_allowance_from_balance(available, tx_env.gas_price) + }; + Ok(cap_call_gas_allowance(allowance, gas_cap)) +} + +/// Computes the caller's gas allowance on `eth_estimateGas` (`BLOCK_GAS_LIMIT_CHECK`), +/// accounting for `l1_fee` in either ERC20 tokens (`MorphTx` with `fee_token_id > 0`) or ETH. +fn estimate_gas_allowance( + db: &mut DB, + evm_env: &MorphEvmEnv, + tx_env: &MorphTxEnv, + caller: Address, + l1_fee: U256, + gas_cap: u64, +) -> Result +where + DB: Database, + DB::Error: Into, +{ + let allowance = if tx_env.uses_token_fee() + && let Some(fee_token_id) = tx_env.fee_token_id + { + load_caller_token_gas_allowance( + db, + evm_env, + caller, + tx_env.value, + l1_fee, + fee_token_id, + tx_env.fee_limit, + tx_env.gas_price, + )? + } else { + // allowance = (balance − value − l1_fee) / gas_price, done at wei + // precision so the remainder is not lost across the two + // subtractions. + let balance = db + .get_account(&caller) + .map_err(|e| MorphEthApiError::Eth(e.into()))? + .map(|acc| acc.balance) + .unwrap_or_default(); + let available = balance + .checked_sub(tx_env.value) + .ok_or(MorphEthApiError::InsufficientFundsForTransfer)?; + // Reject at `l1_fee >= available` so the RPC surfaces the real + // reason rather than a downstream "gas required exceeds allowance 0". + if l1_fee >= available { + return Err(MorphEthApiError::InsufficientFundsForL1Fee); + } + gas_allowance_from_balance(available - l1_fee, tx_env.gas_price) + }; + + Ok(cap_call_gas_allowance(allowance, gas_cap)) +} + /// Loads token registry metadata, validates token usability and `tx.value` ETH coverage /// before executing any call-mode `balanceOf`, resolves `caller`'s token balance, and /// computes the caller's gas allowance. @@ -1062,4 +1107,57 @@ mod tests { let borrowed = estimate_l1_fee_rlp_bytes(&evm_env, &tx_capped).unwrap(); assert!(matches!(borrowed, Cow::Borrowed(_))); } + + #[test] + fn non_morph_tx_with_stray_fee_token_id_stays_on_eth_allowance_paths() { + use evm2::evm::{AccountInfo, InMemoryDB}; + use morph_chainspec::hardfork::MorphHardfork; + use morph_primitives::MORPH_TX_TYPE_ID; + use morph_revm::MorphBlockEnv; + + let caller = Address::with_last_byte(0x11); + let mut db = InMemoryDB::default(); + db.insert_account_info( + &caller, + AccountInfo::default().with_balance(U256::from(1_000u64)), + ); + let env = MorphEvmEnv::new(MorphHardfork::Jade, MorphBlockEnv::default(), 2818); + + // Standard EIP-1559 tx (`0x02`) carrying `fee_token_id: Some(1)` must NOT take the + // `u64::MAX` / token-registry paths (token 1 is not even registered in `db`). + let standard_tx = MorphTxEnv { + tx_type: 0x02, + gas_price: 10, + fee_token_id: Some(1), + ..Default::default() + }; + assert_eq!( + call_gas_allowance(&mut db, &standard_tx, caller, 0).unwrap(), + 100 + ); + assert_eq!( + estimate_gas_allowance(&mut db, &env, &standard_tx, caller, U256::from(200u64), 0) + .unwrap(), + 80 + ); + + // By contrast, an actual MorphTx (`0x7f`) with `fee_token_id: Some(1)` enters the + // token-fee branches (`u64::MAX` on `eth_call`, `InvalidFeeToken` on `eth_estimateGas` + // when token 1 is unregistered). + let morph_tx = MorphTxEnv { + tx_type: MORPH_TX_TYPE_ID, + gas_price: 10, + fee_token_id: Some(1), + ..Default::default() + }; + assert_eq!( + call_gas_allowance(&mut db, &morph_tx, caller, 0).unwrap(), + u64::MAX + ); + assert!(matches!( + estimate_gas_allowance(&mut db, &env, &morph_tx, caller, U256::from(200u64), 0) + .unwrap_err(), + MorphEthApiError::InvalidFeeToken + )); + } } From 844436241ac9511b8ecb6014ff1d86198f4c0111 Mon Sep 17 00:00:00 2001 From: panos-xyz Date: Sun, 6 Dec 2026 16:37:00 +0800 Subject: [PATCH 16/16] fix(statetest): emit EIP-3155 error field and omit unknown opName Emit step_end fault/revert markers as EIP-3155 "error" strings (such as OpcodeNotFound, NotActivated, InvalidFEOpcode, OutOfGas, Revert) while keeping normal STOP/RETURN and pre-child CALL/CREATE flushes error-free, and omit "opName" when OpCode::new(op) is None instead of emitting "UNKNOWN". --- bin/morph-statetest/src/trace.rs | 298 ++++++++++++++++++++++++++++--- 1 file changed, 271 insertions(+), 27 deletions(-) diff --git a/bin/morph-statetest/src/trace.rs b/bin/morph-statetest/src/trace.rs index eb3afa93..559afba6 100644 --- a/bin/morph-statetest/src/trace.rs +++ b/bin/morph-statetest/src/trace.rs @@ -2,16 +2,15 @@ //! //! Streams one JSON struct log per executed opcode, in the line format of `geth --json`. +use alloy_primitives::U256; use evm2::{ EvmTypesHost, Inspector, - interpreter::{Interpreter, Message, MessageResult, opcode::OpCode}, + interpreter::{InstrStop, Interpreter, Message, MessageResult, opcode::OpCode}, }; -use serde_json::json; +use serde::Serialize; use std::io::Write; -use alloy_primitives::U256; - -/// Per-opcode state captured in `step`, emitted once its gas cost is known. +/// Per-opcode state captured in `step`, emitted once its gas cost and stop outcome are known. #[derive(Debug)] struct PendingStep { pc: usize, @@ -23,6 +22,25 @@ struct PendingStep { refund: i64, } +/// One serialized EIP-3155 struct-log line. +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct TraceStep<'a> { + pc: usize, + op: u8, + gas: String, + gas_cost: String, + stack: &'a [U256], + depth: u64, + return_data: &'static str, + refund: String, + mem_size: usize, + #[serde(skip_serializing_if = "Option::is_none")] + op_name: Option<&'static str>, + #[serde(skip_serializing_if = "Option::is_none")] + error: Option, +} + /// EIP-3155 struct-log tracer writing to `out`. #[derive(Debug)] pub(crate) struct Eip3155Tracer { @@ -35,29 +53,41 @@ impl Eip3155Tracer { Self { out, pending: None } } - /// Emits the pending step with the gas spent since it was captured. + /// Emits the pending step with the gas spent since it was captured and any fault/revert marker. /// - /// CALL- and CREATE-family opcodes never reach `step_end`: dispatch unwinds into the frame - /// machinery instead, so their step is flushed from the `call`/`create` hooks. - fn flush_pending(&mut self, interp: &mut Interpreter<'_, '_, T>) { + /// CALL- and CREATE-family opcodes that enter a child frame never reach `step_end` before the + /// child executes: dispatch unwinds into the frame machinery instead, so their step is flushed + /// from the `call`/`create` hooks with `error = None`. + fn flush_pending( + &mut self, + interp: &mut Interpreter<'_, '_, T>, + error: Option, + ) { let Some(step) = self.pending.take() else { return; }; - let gas_cost = step.gas.saturating_sub(interp.gas().remaining()); - let line = json!({ - "pc": step.pc, - "op": step.op, - "gas": format!("{:#x}", step.gas), - "gasCost": format!("{gas_cost:#x}"), - "stack": step.stack, - "depth": u64::from(step.depth) + 1, - "returnData": "0x", - "refund": format!("{:#x}", step.refund.max(0)), - "memSize": step.mem_size, - "opName": OpCode::new_or_unknown(step.op).as_str(), - }); - // Diagnostic output only: a broken pipe must not abort execution. - let _ = writeln!(self.out, "{line}"); + let gas_cost = if error.is_some() && interp.result().is_err_and(InstrStop::is_out_of_gas) { + step.gas + } else { + step.gas.saturating_sub(interp.gas().remaining()) + }; + let line = TraceStep { + pc: step.pc, + op: step.op, + gas: format!("{:#x}", step.gas), + gas_cost: format!("{gas_cost:#x}"), + stack: &step.stack, + depth: u64::from(step.depth) + 1, + return_data: "0x", + refund: format!("{:#x}", step.refund.max(0)), + mem_size: step.mem_size, + op_name: OpCode::new(step.op).map(OpCode::as_str), + error, + }; + if let Ok(encoded) = serde_json::to_string(&line) { + // Diagnostic output only: a broken pipe must not abort execution. + let _ = writeln!(self.out, "{encoded}"); + } } } @@ -75,7 +105,12 @@ impl Inspector for Eip3155Tracer { } fn step_end(&mut self, interp: &mut Interpreter<'_, '_, T>) { - self.flush_pending(interp); + let error = interp + .result() + .err() + .filter(|stop| !stop.is_success() && !matches!(stop, InstrStop::Reload)) + .map(|stop| format!("{stop:?}")); + self.flush_pending(interp, error); } fn call( @@ -83,7 +118,7 @@ impl Inspector for Eip3155Tracer { interp: &mut Interpreter<'_, '_, T>, _message: &mut Message, ) -> Option> { - self.flush_pending(interp); + self.flush_pending(interp, None); None } @@ -92,7 +127,216 @@ impl Inspector for Eip3155Tracer { interp: &mut Interpreter<'_, '_, T>, _message: &mut Message, ) -> Option> { - self.flush_pending(interp); + self.flush_pending(interp, None); None } } + +#[cfg(test)] +mod tests { + use super::*; + use alloy_consensus::transaction::Recovered; + use alloy_primitives::{Address, Bytes, TxKind, address}; + use evm2::{ + bytecode::Bytecode, + evm::{AccountInfo, InMemoryDB}, + interpreter::opcode::op, + }; + use morph_chainspec::hardfork::MorphHardfork; + use morph_revm::{FeeFrameFilter, MorphBlockEnv, MorphTxEnv, morph_evm, morph_evm_env}; + use serde_json::Value; + + const CALLER: Address = address!("1000000000000000000000000000000000000001"); + const CALLEE: Address = address!("1000000000000000000000000000000000000002"); + const CHILD: Address = address!("1000000000000000000000000000000000000003"); + + fn run_trace(fork: MorphHardfork, gas_limit: u64, code: &[u8]) -> Vec { + let mut db = InMemoryDB::default(); + db.insert_account_info( + &CALLER, + AccountInfo::default().with_balance(U256::from(1u128 << 60)), + ); + db.insert_account_info( + &CALLEE, + AccountInfo::default().with_code(Bytecode::new_legacy(Bytes::copy_from_slice(code))), + ); + run_trace_with_db(fork, gas_limit, db) + } + + fn run_trace_with_db(fork: MorphHardfork, gas_limit: u64, db: InMemoryDB) -> Vec { + let block = MorphBlockEnv { + number: U256::from(1u64), + gas_limit: U256::from(30_000_000u64), + timestamp: U256::from(1_000u64), + ..Default::default() + }; + let mut evm = morph_evm(db, morph_evm_env(fork, 1, 30_000_000, block)); + let tx = Recovered::new_unchecked( + MorphTxEnv { + tx_type: 0x02, + chain_id: Some(1), + kind: TxKind::Call(CALLEE), + gas_limit, + gas_price: 1, + gas_priority_fee: Some(1), + ..Default::default() + }, + CALLER, + ); + + let mut buf = Vec::new(); + { + let mut tracer = FeeFrameFilter::new(Eip3155Tracer::new(&mut buf)); + let _ = evm.transact_with_inspector(&tx, &mut tracer); + } + String::from_utf8(buf) + .unwrap() + .lines() + .map(|line| serde_json::from_str::(line).unwrap()) + .collect() + } + + #[test] + fn normal_stop_and_return_steps_omit_error() { + let stop_steps = run_trace(MorphHardfork::Jade, 100_000, &[op::PUSH1, 0x01, op::STOP]); + assert_eq!(stop_steps.len(), 2); + assert_eq!(stop_steps[0]["opName"], "PUSH1"); + assert!(stop_steps[0].get("error").is_none()); + assert_eq!(stop_steps[1]["opName"], "STOP"); + assert!(stop_steps[1].get("error").is_none()); + + let return_steps = run_trace( + MorphHardfork::Jade, + 100_000, + &[op::PUSH1, 0x00, op::PUSH1, 0x00, op::RETURN], + ); + assert_eq!(return_steps.len(), 3); + assert_eq!(return_steps[2]["opName"], "RETURN"); + assert!(return_steps[2].get("error").is_none()); + } + + #[test] + fn invalid_disabled_and_undefined_opcodes_emit_eip3155_errors_and_omit_unknown_opname() { + // 0xFE (`INVALID`) keeps `opName: "INVALID"` and tags `error: "InvalidFEOpcode"`. + let fe_steps = run_trace(MorphHardfork::Jade, 100_000, &[op::INVALID]); + assert_eq!(fe_steps.len(), 1); + assert_eq!(fe_steps[0]["op"], u64::from(op::INVALID)); + assert_eq!(fe_steps[0]["opName"], "INVALID"); + assert_eq!(fe_steps[0]["error"], "InvalidFEOpcode"); + + // Morph-disabled (`SELFDESTRUCT`, `BLOBHASH`, `BLOBBASEFEE`) and fork-unactivated + // (`SLOTNUM`, `DUPN` on Jade) opcodes emit `error: "NotActivated"`. + for disabled in [ + op::SELFDESTRUCT, + op::BLOBHASH, + op::BLOBBASEFEE, + op::SLOTNUM, + op::DUPN, + ] { + let steps = run_trace(MorphHardfork::Jade, 100_000, &[disabled]); + assert_eq!(steps.len(), 1, "opcode {disabled:#x}"); + assert_eq!(steps[0]["op"], u64::from(disabled)); + assert!( + steps[0].get("opName").is_some(), + "known opcode {disabled:#x} keeps its table name alongside NotActivated" + ); + assert_eq!(steps[0]["error"], "NotActivated", "opcode {disabled:#x}"); + } + + // Undefined opcode byte (`0x0c`) omits `opName` entirely (never `"UNKNOWN"`) and emits + // `error: "OpcodeNotFound"`. + let undef_steps = run_trace(MorphHardfork::Celadon, 100_000, &[0x0c]); + assert_eq!(undef_steps.len(), 1); + assert_eq!(undef_steps[0]["op"], 0x0c); + assert!( + undef_steps[0].get("opName").is_none(), + "undefined opcode must omit opName, got {:?}", + undef_steps[0] + ); + assert_eq!(undef_steps[0]["error"], "OpcodeNotFound"); + } + + #[test] + fn revert_stack_underflow_and_oog_emit_error() { + let revert_steps = run_trace( + MorphHardfork::Jade, + 100_000, + &[op::PUSH1, 0x00, op::PUSH1, 0x00, op::REVERT], + ); + assert_eq!(revert_steps.last().unwrap()["opName"], "REVERT"); + assert_eq!(revert_steps.last().unwrap()["error"], "Revert"); + + let underflow_steps = run_trace(MorphHardfork::Jade, 100_000, &[op::POP]); + assert_eq!(underflow_steps.len(), 1); + assert_eq!(underflow_steps[0]["opName"], "POP"); + assert_eq!(underflow_steps[0]["error"], "StackUnderflow"); + + // Intrinsic gas is 21,000; 21,002 leaves 2 gas for `PUSH1` (cost 3) -> `OutOfGas`. + let oog_steps = run_trace(MorphHardfork::Jade, 21_002, &[op::PUSH1, 0x01]); + assert_eq!(oog_steps.len(), 1); + assert_eq!(oog_steps[0]["opName"], "PUSH1"); + assert_eq!(oog_steps[0]["gas"], "0x2"); + assert_eq!(oog_steps[0]["gasCost"], "0x2"); + assert_eq!(oog_steps[0]["error"], "OutOfGas"); + } + + #[test] + fn nested_call_flushes_parent_without_error_before_faulting_child_step() { + // Parent: STATICCALL(gas=50_000, addr=CHILD, argsOffset=0, argsSize=0, retOffset=0, retSize=0), STOP + let mut parent = vec![ + op::PUSH1, + 0x00, // retSize + op::PUSH1, + 0x00, // retOffset + op::PUSH1, + 0x00, // argsSize + op::PUSH1, + 0x00, // argsOffset + op::PUSH20, + ]; + parent.extend_from_slice(CHILD.as_slice()); + parent.extend_from_slice(&[ + op::PUSH2, + 0xc3, + 0x50, // 50,000 gas + op::STATICCALL, + op::STOP, + ]); + + let mut db = InMemoryDB::default(); + db.insert_account_info( + &CALLER, + AccountInfo::default().with_balance(U256::from(1u128 << 60)), + ); + db.insert_account_info( + &CALLEE, + AccountInfo::default().with_code(Bytecode::new_legacy(Bytes::from(parent))), + ); + db.insert_account_info( + &CHILD, + AccountInfo::default().with_code(Bytecode::new_legacy(Bytes::from_static(&[0x0c]))), + ); + + let steps = run_trace_with_db(MorphHardfork::Jade, 200_000, db); + let staticcall_idx = steps + .iter() + .position(|s| s.get("opName").and_then(Value::as_str) == Some("STATICCALL")) + .expect("STATICCALL step present"); + + assert_eq!(steps[staticcall_idx]["depth"], 1); + assert!(steps[staticcall_idx].get("error").is_none()); + + // Immediately following step is child's faulting undefined opcode at depth 2. + let child_step = &steps[staticcall_idx + 1]; + assert_eq!(child_step["depth"], 2); + assert_eq!(child_step["op"], 0x0c); + assert!(child_step.get("opName").is_none()); + assert_eq!(child_step["error"], "OpcodeNotFound"); + + // Parent resumes at STOP (depth 1, no error). + let final_step = &steps[staticcall_idx + 2]; + assert_eq!(final_step["depth"], 1); + assert_eq!(final_step["opName"], "STOP"); + assert!(final_step.get("error").is_none()); + } +}