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 4937c224..006c9e72 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", @@ -101,9 +111,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 +127,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 +181,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 +208,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 +227,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 +271,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 +288,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 +314,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 +350,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 +384,7 @@ dependencies = [ "hashbrown 0.17.0", "indexmap 2.14.0", "itoa", - "k256", + "k256 0.13.4", "keccak-asm", "paste", "proptest", @@ -395,9 +400,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 +429,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 +445,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 +489,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 +515,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 +528,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 +540,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 +552,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 +567,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 +580,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 +600,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 +620,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 +632,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 +658,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 +684,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 +696,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 +722,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 +800,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 +813,7 @@ dependencies = [ "parking_lot", "serde", "serde_json", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "tower", "tracing", @@ -816,9 +823,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 +839,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 +849,7 @@ dependencies = [ "bytes", "futures", "interprocess", + "memchr", "pin-project", "serde", "serde_json", @@ -852,9 +860,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 +879,9 @@ dependencies = [ [[package]] name = "alloy-trie" -version = "0.9.5" +version = "0.9.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f14b5d9b2c2173980202c6ff470d96e7c5e202c65a9f67884ad565226df7fbb" +checksum = "70c7c04b6e5a7a2325f53d38c319a47d01c3609b44845ac2801bac9643fe26b9" dependencies = [ "alloy-primitives", "alloy-rlp", @@ -885,15 +893,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", @@ -946,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]] @@ -957,7 +965,7 @@ checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" dependencies = [ "anstyle", "once_cell_polyfill", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -1034,7 +1042,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 +1059,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 +1079,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 +1100,7 @@ dependencies = [ "digest 0.10.7", "educe", "itertools 0.13.0", - "num-bigint", + "num-bigint 0.4.6", "num-traits", "paste", "zeroize", @@ -1110,7 +1118,7 @@ dependencies = [ "ark-std 0.6.0", "digest 0.10.7", "educe", - "num-bigint", + "num-bigint 0.4.6", "num-traits", "zeroize", ] @@ -1161,7 +1169,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 +1181,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 +1194,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 +1207,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 +1241,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 +1281,7 @@ checksum = "adb7b85a02b83d2f22f89bd5cac66c9c89474240cb6207cb1efc16d098e822a5" dependencies = [ "ark-std 0.4.0", "digest 0.10.7", - "num-bigint", + "num-bigint 0.4.6", ] [[package]] @@ -1285,7 +1293,7 @@ dependencies = [ "ark-std 0.5.0", "arrayvec", "digest 0.10.7", - "num-bigint", + "num-bigint 0.4.6", ] [[package]] @@ -1297,7 +1305,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", ] @@ -1352,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" @@ -1508,6 +1524,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" @@ -1530,6 +1552,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" @@ -1583,7 +1611,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 +1662,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 +1677,6 @@ checksum = "1bc2832c24239b0141d5674bb9174f9d68a8b5b3f2753311927c172ca46f7e9c" dependencies = [ "funty", "radium", - "serde", "tap", "wyz", ] @@ -1666,6 +1693,7 @@ dependencies = [ "cfg-if", "constant_time_eq", "cpufeatures 0.3.0", + "rayon-core", ] [[package]] @@ -1694,6 +1722,7 @@ checksum = "dcdb4c7013139a150f9fc55d123186dbfaba0d912817466282c73ac49e71fb45" dependencies = [ "cc", "glob", + "serde", "threadpool", "zeroize", ] @@ -1926,7 +1955,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]] @@ -1989,6 +2029,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 +2044,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 +2059,7 @@ checksum = "74b169b26623ff17e9db37a539fe4f15342080df39f129ef7631df7683d6d9d4" dependencies = [ "bitvec", "coins-bip32", - "hmac", + "hmac 0.12.1", "once_cell", "pbkdf2", "rand 0.8.6", @@ -2091,8 +2137,8 @@ dependencies = [ "compression-core", "flate2", "memchr", - "zstd", - "zstd-safe", + "zstd 0.13.4", + "zstd-safe 7.4.0", ] [[package]] @@ -2128,6 +2174,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" @@ -2170,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" @@ -2196,6 +2238,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 +2341,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 +2380,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" @@ -2339,7 +2403,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" dependencies = [ "generic-array", - "rand_core 0.6.4", "typenum", ] @@ -2349,7 +2412,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]] @@ -2358,20 +2423,40 @@ 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]] +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" +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", @@ -2499,7 +2584,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 +2604,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", ] @@ -2588,12 +2683,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" @@ -2610,7 +2699,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 +2711,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]] @@ -2648,14 +2739,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", @@ -2668,7 +2760,7 @@ dependencies = [ "more-asserts", "multiaddr", "parking_lot", - "rand 0.8.6", + "rand 0.10.2", "smallvec", "socket2", "tokio", @@ -2727,36 +2819,51 @@ 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]] 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", - "signature", + "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", ] @@ -2788,37 +2895,57 @@ 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", ] [[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", - "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", ] @@ -2855,7 +2982,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]] @@ -2910,10 +3037,80 @@ dependencies = [ ] [[package]] -name = "evmap" -version = "11.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b8874945f036109c72242964c1174cf99434e30cfa45bf45fedc983f50046f8" +name = "evm2" +version = "0.1.0" +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", + "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://github.com/DaniPopes/evm2?rev=66687c18b34d3bdbb899f5eb7605070615c03475#66687c18b34d3bdbb899f5eb7605070615c03475" +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://github.com/DaniPopes/evm2?rev=66687c18b34d3bdbb899f5eb7605070615c03475#66687c18b34d3bdbb899f5eb7605070615c03475" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "evmap" +version = "11.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b8874945f036109c72242964c1174cf99434e30cfa45bf45fedc983f50046f8" dependencies = [ "hashbag", "left-right", @@ -2979,11 +3176,21 @@ 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" +version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" +checksum = "64cd1e32ddd350061ae6edb1b082d7c54915b5c672c389143b9a63403a109f24" [[package]] name = "filetime" @@ -3076,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", ] @@ -3228,8 +3435,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]] @@ -3286,11 +3493,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", ] @@ -3300,7 +3506,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 +3570,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" @@ -3406,12 +3623,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" @@ -3453,21 +3664,11 @@ dependencies = [ [[package]] name = "hashlink" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea0b22561a9c04a7cb1a302c013e0259cd3b4bb619f145b32f72b8b4bcbed230" -dependencies = [ - "hashbrown 0.16.1", -] - -[[package]] -name = "hdrhistogram" -version = "7.5.4" +version = "0.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "765c9198f173dd59ce26ff9f95ef0aafd0a0fe01fb9d72841bc5066a4c06511d" +checksum = "a596f1b20ed2cc5ecac41a164aaebc7258057060f06c0cf7a2ba3991ee7990fb" dependencies = [ - "byteorder", - "num-traits", + "hashbrown 0.17.0", ] [[package]] @@ -3499,9 +3700,9 @@ dependencies = [ [[package]] name = "hickory-net" -version = "0.26.1" +version = "0.26.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2295ed2f9c31e471e1428a8f88a3f0e1f4b27c15049592138d1eebe9c35b183" +checksum = "ea9b43710d47761c90da994eeec7e1bee50095f2b4bcdfd42acd67ca5f814e47" dependencies = [ "async-trait", "cfg-if", @@ -3514,7 +3715,7 @@ dependencies = [ "ipnet", "jni 0.22.4", "rand 0.10.2", - "thiserror 2.0.18", + "thiserror 2.0.21", "tinyvec", "tokio", "tracing", @@ -3523,9 +3724,9 @@ dependencies = [ [[package]] name = "hickory-proto" -version = "0.26.1" +version = "0.26.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0bab31817bfb44672a252e97fe81cd0c18d1b2cf892108922f6818820df8c643" +checksum = "927c672dc4fd1e4b7cfcb7b751fe1d5766638080b8d243b78165ef660c2061e7" dependencies = [ "data-encoding", "idna", @@ -3536,7 +3737,7 @@ dependencies = [ "rand 0.10.2", "ring", "serde", - "thiserror 2.0.18", + "thiserror 2.0.21", "tinyvec", "tracing", "url", @@ -3544,9 +3745,9 @@ dependencies = [ [[package]] name = "hickory-resolver" -version = "0.26.1" +version = "0.26.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0d58d28879ceecde6607729660c2667a081ccdc082e082675042793960f178c" +checksum = "e847eb9a1b4e6bd038c2ff9400aff8ba02b450baa7f691bc56359c9af0418145" dependencies = [ "cfg-if", "futures-util", @@ -3564,18 +3765,18 @@ dependencies = [ "serde", "smallvec", "system-configuration", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "tracing", ] [[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", + "hmac 0.13.0", ] [[package]] @@ -3587,6 +3788,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 +3830,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 +3870,9 @@ version = "0.4.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "818356c5132c1fede50f837ca96afbe78ff42413047f4abb886217845e1b6c8c" dependencies = [ + "subtle", "typenum", + "zeroize", ] [[package]] @@ -3707,19 +3913,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 +4191,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", ] @@ -4021,6 +4214,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" @@ -4208,7 +4410,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 +4513,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 +4541,7 @@ dependencies = [ "rustc-hash", "serde", "serde_json", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "tokio-stream", "tower", @@ -4364,7 +4566,7 @@ dependencies = [ "rustls-platform-verifier 0.5.3", "serde", "serde_json", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "tower", "url", @@ -4402,7 +4604,7 @@ dependencies = [ "serde", "serde_json", "soketto", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "tokio-stream", "tokio-util", @@ -4419,7 +4621,7 @@ dependencies = [ "http", "serde", "serde_json", - "thiserror 2.0.18", + "thiserror 2.0.21", ] [[package]] @@ -4461,7 +4663,7 @@ dependencies = [ "pem", "serde", "serde_json", - "signature", + "signature 2.2.0", "simple_asn1", ] @@ -4472,12 +4674,28 @@ 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", + "signature 3.0.0", + "wnaf", ] [[package]] @@ -4488,7 +4706,7 @@ checksum = "bde5057d6143cc94e861d90f591b9303d6716c6b9602309150bd068853c10899" dependencies = [ "hashbrown 0.16.1", "portable-atomic", - "thiserror 2.0.18", + "thiserror 2.0.21", ] [[package]] @@ -4551,7 +4769,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", ] @@ -4614,19 +4832,19 @@ 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", + "k256 0.14.0", "multihash", - "quick-protobuf", - "sha2 0.10.9", - "thiserror 2.0.18", + "prost", + "sha2 0.11.0", + "thiserror 2.0.21", "tracing", "zeroize", ] @@ -4648,7 +4866,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", @@ -4671,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", @@ -4687,7 +4905,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 +5126,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 +5156,7 @@ dependencies = [ "crossbeam-utils", "hashbrown 0.16.1", "metrics", - "quanta", + "quanta 0.12.6", "rand 0.9.4", "rand_xoshiro", "rapidhash", @@ -4951,16 +5169,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" @@ -5061,17 +5269,17 @@ checksum = "1fafa6961cabd9c63bcd77a45d7e3b7f3b552b70417831fb0f56db717e72407e" [[package]] name = "morph-chainspec" -version = "1.5.0" +version = "2.0.0" 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", @@ -5084,11 +5292,10 @@ dependencies = [ [[package]] name = "morph-consensus" -version = "1.5.0" +version = "2.0.0" dependencies = [ "alloy-consensus", "alloy-eips", - "alloy-evm", "alloy-genesis", "alloy-primitives", "alloy-rlp", @@ -5096,14 +5303,15 @@ 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]] name = "morph-engine-api" -version = "1.5.0" +version = "2.0.0" dependencies = [ "alloy-consensus", "alloy-eips", @@ -5125,20 +5333,23 @@ dependencies = [ "reth-provider", "reth-rpc-api", "serde_json", - "thiserror 2.0.18", + "thiserror 2.0.21", + "tokio", "tracing", ] [[package]] name = "morph-evm" -version = "1.5.0" +version = "2.0.0" dependencies = [ "alloy-consensus", - "alloy-evm", + "alloy-eip7928", "alloy-genesis", "alloy-primitives", "alloy-rpc-types-eth", "derive_more", + "evm2", + "evm2-inspectors", "morph-chainspec", "morph-payload-types", "morph-primitives", @@ -5147,20 +5358,21 @@ 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", ] [[package]] name = "morph-node" -version = "1.5.0" +version = "2.0.0" dependencies = [ "alloy-consensus", + "alloy-eip7928", "alloy-eips", "alloy-genesis", "alloy-hardforks", @@ -5172,7 +5384,6 @@ dependencies = [ "alloy-signer", "alloy-signer-local", "clap", - "dashmap", "eyre", "futures", "jsonrpsee", @@ -5191,6 +5402,7 @@ dependencies = [ "parking_lot", "reth-chain-state", "reth-chainspec", + "reth-consensus", "reth-db", "reth-e2e-test-utils", "reth-engine-local", @@ -5228,17 +5440,19 @@ dependencies = [ [[package]] name = "morph-payload-builder" -version = "1.5.0" +version = "2.0.0" dependencies = [ "alloy-consensus", "alloy-eips", "alloy-primitives", "alloy-rlp", + "evm2", "metrics", "morph-chainspec", "morph-evm", "morph-payload-types", "morph-primitives", + "morph-txpool", "reth-basic-payload-builder", "reth-chainspec", "reth-evm", @@ -5249,18 +5463,18 @@ dependencies = [ "reth-payload-primitives", "reth-payload-util", "reth-primitives-traits", - "reth-revm", "reth-storage-api", + "reth-tasks", "reth-transaction-pool", + "reth-trie-common", "reth-trie-parallel", - "revm", - "thiserror 2.0.18", + "thiserror 2.0.21", "tracing", ] [[package]] name = "morph-payload-types" -version = "1.5.0" +version = "2.0.0" dependencies = [ "alloy-consensus", "alloy-eips", @@ -5280,7 +5494,7 @@ dependencies = [ [[package]] name = "morph-primitives" -version = "1.5.0" +version = "2.0.0" dependencies = [ "alloy-consensus", "alloy-eips", @@ -5300,7 +5514,7 @@ dependencies = [ [[package]] name = "morph-proofs" -version = "1.5.0" +version = "2.0.0" dependencies = [ "alloy-eips", "alloy-primitives", @@ -5319,21 +5533,20 @@ 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", ] [[package]] name = "morph-proofs-exex" -version = "1.5.0" +version = "2.0.0" dependencies = [ "alloy-consensus", "alloy-eips", @@ -5356,7 +5569,7 @@ dependencies = [ [[package]] name = "morph-reference-index" -version = "1.5.0" +version = "2.0.0" dependencies = [ "alloy-consensus", "alloy-primitives", @@ -5377,14 +5590,14 @@ dependencies = [ "reth-tasks", "serde", "tempfile", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "tracing", ] [[package]] name = "morph-reth" -version = "1.5.0" +version = "2.0.0" dependencies = [ "alloy-consensus", "alloy-primitives", @@ -5403,42 +5616,38 @@ dependencies = [ "reth-cli-util", "reth-ethereum-cli", "reth-node-builder", + "reth-node-core", "reth-provider", "reth-rpc-server-types", + "reth-stages-types", "reth-tasks", "tracing", ] [[package]] name = "morph-revm" -version = "1.5.0" +version = "2.0.0" dependencies = [ "alloy-consensus", "alloy-eips", - "alloy-evm", "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", - "revm", - "thiserror 2.0.18", + "reth-evm-ethereum", + "thiserror 2.0.21", "tracing", ] [[package]] name = "morph-rpc" -version = "1.5.0" +version = "2.0.0" dependencies = [ "alloy-consensus", "alloy-eips", - "alloy-evm", "alloy-network", "alloy-primitives", "alloy-rpc-types-debug", @@ -5446,7 +5655,9 @@ dependencies = [ "alloy-serde", "async-trait", "derive_more", + "evm2", "eyre", + "futures", "jsonrpsee", "metrics", "morph-chainspec", @@ -5455,6 +5666,7 @@ dependencies = [ "morph-proofs", "morph-reference-index", "morph-revm", + "reth-chain-state", "reth-chainspec", "reth-errors", "reth-evm", @@ -5463,7 +5675,6 @@ dependencies = [ "reth-node-builder", "reth-primitives-traits", "reth-provider", - "reth-revm", "reth-rpc", "reth-rpc-api", "reth-rpc-convert", @@ -5474,46 +5685,47 @@ dependencies = [ "reth-tasks", "reth-transaction-pool", "reth-trie-common", - "revm", "serde", "serde_json", "tempfile", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "tracing", ] [[package]] name = "morph-statetest" -version = "1.5.0" +version = "2.0.0" dependencies = [ - "alloy-evm", + "alloy-consensus", + "alloy-eips", "alloy-primitives", "alloy-rlp", + "alloy-signer-local", "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]] name = "morph-txpool" -version = "1.5.0" +version = "2.0.0" dependencies = [ "alloy-consensus", "alloy-eips", - "alloy-evm", "alloy-primitives", "c-kzg", + "dashmap", "derive_more", + "evm2", "futures", "morph-chainspec", "morph-evm", @@ -5525,7 +5737,6 @@ dependencies = [ "reth-evm-ethereum", "reth-primitives-traits", "reth-provider", - "reth-revm", "reth-storage-api", "reth-transaction-pool", "tokio", @@ -5535,12 +5746,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", @@ -5589,22 +5800,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", @@ -5622,7 +5824,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]] @@ -5640,7 +5842,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]] @@ -5649,7 +5851,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", @@ -5667,6 +5869,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" @@ -5708,7 +5921,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", ] @@ -5784,7 +5997,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]] @@ -5813,12 +6026,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" @@ -5826,103 +6033,24 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" [[package]] -name = "opentelemetry" -version = "0.32.0" +name = "p256" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0142c63252a9e054e68a4c61a5778f7b14f576274d593f8ce883d191a099682" +checksum = "d2c9239b2dbc807adbbe147e8cf72ea7450c3a0aabe62cb8e75ff4ec22e1f72a" dependencies = [ - "futures-core", - "futures-sink", - "js-sys", - "pin-project-lite", - "thiserror 2.0.18", - "tracing", + "ecdsa 0.17.0", + "elliptic-curve 0.14.3", + "primefield", + "primeorder", + "serdect 0.4.3", + "sha2 0.11.0", ] [[package]] -name = "opentelemetry-http" -version = "0.32.0" +name = "page_size" +version = "0.6.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" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b" -dependencies = [ - "ecdsa", - "elliptic-curve", - "primeorder", - "sha2 0.10.9", -] - -[[package]] -name = "page_size" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "30d5b2194ed13191c1999ae0704b7839fb18384fa22e49b57eeaa97d79ce40da" +checksum = "30d5b2194ed13191c1999ae0704b7839fb18384fa22e49b57eeaa97d79ce40da" dependencies = [ "libc", "winapi", @@ -5986,6 +6114,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" @@ -5993,7 +6127,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8ed6a7761f76e3b9f92dfb0a60a6a6477c61024b775147ff0973a02653abaf2" dependencies = [ "digest 0.10.7", - "hmac", + "hmac 0.12.1", ] [[package]] @@ -6113,8 +6247,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]] @@ -6140,13 +6284,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", ] @@ -6230,23 +6373,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", -] - -[[package]] -name = "pretty_assertions" -version = "1.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ae130e2f271fbc2ac3a40fb1d07180839cdbbe443c7a27e1e3c13c5cac0116d" -dependencies = [ - "diff", - "yansi", + "smallvec", ] [[package]] @@ -6259,13 +6394,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]] @@ -6346,7 +6499,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", @@ -6359,7 +6512,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", ] @@ -6372,7 +6525,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", @@ -6438,15 +6591,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" @@ -6463,19 +6607,25 @@ dependencies = [ ] [[package]] -name = "quick-error" -version = "1.2.3" +name = "quanta" +version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0" +checksum = "73be39b77b45d82a4d1a5793fe9a89a5c143ceaa6ad0d8417982566bb0f34e11" +dependencies = [ + "libc", + "portable-atomic", + "raw-cpuid", + "wasip1", + "wasip2", + "web-sys", + "windows-sys 0.61.2", +] [[package]] -name = "quick-protobuf" -version = "0.8.1" +name = "quick-error" +version = "1.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d6da84cc204722a989e01ba2f6e1e276e190f22263d0cb6ce8526fcdb0d2e1f" -dependencies = [ - "byteorder", -] +checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0" [[package]] name = "quinn" @@ -6491,7 +6641,7 @@ dependencies = [ "rustc-hash", "rustls", "socket2", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "tracing", "web-time", @@ -6514,7 +6664,7 @@ dependencies = [ "rustls", "rustls-pki-types", "slab", - "thiserror 2.0.18", + "thiserror 2.0.21", "tinyvec", "tracing", "web-time", @@ -6695,7 +6845,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", @@ -6703,7 +6853,7 @@ dependencies = [ "kasuari", "lru 0.16.4", "strum", - "thiserror 2.0.18", + "thiserror 2.0.21", "unicode-segmentation", "unicode-truncate", "unicode-width", @@ -6727,7 +6877,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", @@ -6746,7 +6896,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]] @@ -6781,7 +6931,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]] @@ -6790,7 +6940,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]] @@ -6903,8 +7053,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-eips", @@ -6913,13 +7063,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", @@ -6930,8 +7080,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-eips", @@ -6939,20 +7089,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", @@ -6961,13 +7109,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-chains", "alloy-consensus", "alloy-eips", - "alloy-evm", "alloy-genesis", "alloy-primitives", "alloy-trie", @@ -6981,8 +7128,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-genesis", "clap", @@ -6994,11 +7141,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-chains", "alloy-consensus", + "alloy-eip7928", "alloy-eips", "alloy-primitives", "alloy-rlp", @@ -7054,7 +7202,6 @@ dependencies = [ "reth-provider", "reth-prune", "reth-prune-types", - "reth-revm", "reth-stages", "reth-stages-types", "reth-static-file", @@ -7063,7 +7210,7 @@ dependencies = [ "reth-tasks", "reth-trie", "reth-trie-db", - "secp256k1 0.30.0", + "secp256k1 0.33.1", "serde", "serde_json", "socket2", @@ -7073,13 +7220,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "reth-tasks", "tokio", @@ -7088,28 +7235,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-eips", "alloy-primitives", - "cfg-if", "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.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", @@ -7128,9 +7273,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", @@ -7139,8 +7283,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "eyre", "humantime-serde", @@ -7156,8 +7300,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-eip7928", @@ -7165,13 +7309,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-eips", @@ -7183,8 +7327,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-eips", @@ -7199,17 +7343,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-primitives", "derive_more", @@ -7218,29 +7362,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", + "alloy-eips", "alloy-primitives", "arbitrary", "arrayvec", @@ -7263,8 +7407,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-genesis", @@ -7287,14 +7431,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-eips", "alloy-primitives", @@ -7308,8 +7452,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-primitives", "alloy-rlp", @@ -7317,15 +7461,15 @@ 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.18", + "thiserror 2.0.21", "tokio", "tokio-stream", "tracing", @@ -7333,8 +7477,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-primitives", "alloy-rlp", @@ -7343,22 +7487,24 @@ 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", - "thiserror 2.0.18", + "secp256k1 0.33.1", + "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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-primitives", "dashmap", @@ -7367,13 +7513,13 @@ 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.18", + "thiserror 2.0.21", "tokio", "tokio-stream", "tracing", @@ -7381,8 +7527,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-eips", @@ -7397,17 +7543,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", @@ -7416,11 +7563,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-eips", + "alloy-genesis", "alloy-network", "alloy-primitives", "alloy-provider", @@ -7433,15 +7581,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", @@ -7454,6 +7604,7 @@ dependencies = [ "reth-payload-primitives", "reth-primitives-traits", "reth-provider", + "reth-prune-types", "reth-rpc-api", "reth-rpc-builder", "reth-rpc-eth-api", @@ -7462,7 +7613,9 @@ dependencies = [ "reth-tasks", "reth-tokio-util", "reth-tracing", - "revm", + "reth-transaction-pool", + "reth-trie", + "reth-trie-db", "serde_json", "tempfile", "tokio", @@ -7473,25 +7626,25 @@ 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.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", + "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.18", + "thiserror 2.0.21", "tokio", "tokio-stream", "tokio-util", @@ -7500,8 +7653,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-primitives", @@ -7523,8 +7676,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-eips", @@ -7544,40 +7697,42 @@ 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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" 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", "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", @@ -7586,7 +7741,6 @@ dependencies = [ "reth-provider", "reth-prune", "reth-prune-types", - "reth-revm", "reth-stages", "reth-stages-api", "reth-static-file", @@ -7597,21 +7751,18 @@ 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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-primitives", - "alloy-rlp", "alloy-rpc-types-engine", "eyre", "futures", @@ -7625,7 +7776,6 @@ dependencies = [ "reth-fs-util", "reth-payload-primitives", "reth-primitives-traits", - "reth-revm", "reth-storage-api", "serde", "serde_json", @@ -7636,8 +7786,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-eips", @@ -7649,13 +7799,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-primitives", "bytes", @@ -7670,8 +7820,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-primitives", @@ -7694,19 +7844,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" 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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-chains", "alloy-primitives", @@ -7724,7 +7874,7 @@ dependencies = [ "reth-primitives-traits", "serde", "snap", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "tokio-stream", "tokio-util", @@ -7733,8 +7883,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-chains", "alloy-consensus", @@ -7751,13 +7901,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "clap", "eyre", @@ -7779,8 +7929,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-eips", @@ -7795,8 +7945,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-eips", "alloy-primitives", @@ -7806,13 +7956,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-eip2124", "alloy-hardforks", @@ -7824,8 +7974,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-eips", @@ -7845,21 +7995,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-eips", - "alloy-primitives", "alloy-rpc-types-eth", "reth-codecs", "reth-primitives-traits", @@ -7868,8 +8016,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "rayon", "reth-db-api", @@ -7878,19 +8026,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" 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", @@ -7899,19 +8049,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", + "alloy-eip7928", "alloy-eips", - "alloy-evm", "alloy-primitives", "alloy-rpc-types-engine", + "evm2", + "rayon", "reth-chainspec", "reth-ethereum-forks", "reth-ethereum-primitives", @@ -7919,63 +8071,62 @@ 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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" 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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ - "alloy-evm", "alloy-primitives", "alloy-rlp", + "evm2", "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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" 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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-eips", @@ -7999,12 +8150,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", @@ -8012,8 +8161,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-eips", "eyre", @@ -8038,14 +8187,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-eips", "alloy-primitives", @@ -8058,44 +8207,47 @@ 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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" 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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-primitives", "alloy-rlp", "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-revm", "reth-rpc-api", - "reth-tracing", + "reth-tasks", "reth-trie", - "revm", "serde", "serde_json", + "similar", + "tokio", + "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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "bytes", "futures", @@ -8104,7 +8256,7 @@ dependencies = [ "jsonrpsee", "pin-project", "serde_json", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "tokio-stream", "tokio-util", @@ -8114,10 +8266,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ - "bitflags 2.11.1", + "bitflags 2.13.2", "byteorder", "crossbeam-queue", "dashmap", @@ -8125,14 +8277,23 @@ dependencies = [ "parking_lot", "reth-mdbx-sys", "smallvec", - "thiserror 2.0.18", + "thiserror 2.0.21", "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.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "bindgen", "cc", @@ -8140,8 +8301,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "futures", "libc", @@ -8154,8 +8315,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-primitives", "ipnet", @@ -8163,22 +8324,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" 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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-eips", @@ -8194,7 +8355,6 @@ dependencies = [ "metrics", "parking_lot", "pin-project", - "rand 0.8.6", "rand 0.9.4", "rayon", "reth-chainspec", @@ -8210,8 +8370,10 @@ dependencies = [ "reth-evm", "reth-evm-ethereum", "reth-fs-util", + "reth-lru", "reth-metrics", "reth-net-banlist", + "reth-net-nat", "reth-network-api", "reth-network-p2p", "reth-network-peers", @@ -8222,12 +8384,11 @@ dependencies = [ "reth-tokio-util", "reth-transaction-pool", "rustc-hash", - "schnellru", - "secp256k1 0.30.0", + "secp256k1 0.33.1", "serde", "smallvec", "socket2", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "tokio-stream", "tokio-util", @@ -8236,8 +8397,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-primitives", @@ -8254,15 +8415,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-eip7928", @@ -8285,23 +8446,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.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.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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-eip2124", "humantime-serde", @@ -8314,8 +8475,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "anyhow", "bincode 1.3.3", @@ -8324,15 +8485,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-rpc-types-engine", "eyre", @@ -8355,13 +8517,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-eips", + "alloy-network", "alloy-primitives", - "alloy-provider", "alloy-rpc-types", "alloy-rpc-types-engine", "aquamarine", @@ -8404,7 +8566,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", @@ -8414,7 +8578,7 @@ dependencies = [ "reth-tokio-util", "reth-tracing", "reth-transaction-pool", - "secp256k1 0.30.0", + "secp256k1 0.33.1", "serde_json", "tokio", "tokio-stream", @@ -8423,8 +8587,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-eips", @@ -8465,36 +8629,40 @@ dependencies = [ "reth-tracing", "reth-tracing-otlp", "reth-transaction-pool", - "secp256k1 0.30.0", + "secp256k1 0.33.1", "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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" 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", @@ -8502,13 +8670,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", @@ -8516,19 +8684,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-primitives", @@ -8541,7 +8713,7 @@ dependencies = [ "reth-transaction-pool", "serde", "serde_json", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "tokio-stream", "tokio-tungstenite", @@ -8551,8 +8723,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-eips", @@ -8575,8 +8747,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "bytes", "eyre", @@ -8589,6 +8761,7 @@ dependencies = [ "metrics-exporter-prometheus", "metrics-process", "metrics-util", + "parking_lot", "pprof_util", "procfs", "reqwest", @@ -8599,13 +8772,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "reth-chainspec", "reth-db-api", @@ -8616,8 +8790,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-primitives", @@ -8640,8 +8814,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "pin-project", "reth-payload-primitives", @@ -8652,8 +8826,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-eips", @@ -8669,14 +8843,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-primitives", @@ -8685,8 +8859,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-rpc-types-engine", @@ -8695,11 +8869,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", @@ -8711,25 +8885,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-eip7928", @@ -8737,6 +8909,7 @@ dependencies = [ "alloy-genesis", "alloy-primitives", "alloy-rpc-types-engine", + "evm2", "eyre", "itertools 0.14.0", "libc", @@ -8765,10 +8938,8 @@ dependencies = [ "reth-storage-errors", "reth-storage-overlay", "reth-tasks", - "reth-tokio-util", "reth-trie", "reth-trie-db", - "revm", "rocksdb", "smallvec", "strum", @@ -8778,8 +8949,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-primitives", @@ -8797,16 +8968,15 @@ dependencies = [ "reth-static-file-types", "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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-primitives", "arbitrary", @@ -8815,35 +8985,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-dyn-abi", "alloy-eip7928", "alloy-eips", - "alloy-evm", "alloy-genesis", "alloy-network", "alloy-primitives", @@ -8864,6 +9018,8 @@ dependencies = [ "async-trait", "derive_more", "dyn-clone", + "evm2", + "evm2-inspectors", "futures", "itertools 0.14.0", "jsonrpsee", @@ -8884,10 +9040,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", @@ -8898,12 +9052,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", @@ -8912,8 +9064,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-eips", "alloy-genesis", @@ -8942,8 +9094,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-network", "alloy-provider", @@ -8975,7 +9127,7 @@ dependencies = [ "reth-tokio-util", "reth-transaction-pool", "serde", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "tokio-util", "tower", @@ -8985,28 +9137,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" 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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-eips", "alloy-primitives", @@ -9029,21 +9181,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-dyn-abi", "alloy-eip7928", "alloy-eips", - "alloy-evm", "alloy-json-rpc", "alloy-network", "alloy-primitives", @@ -9054,6 +9205,8 @@ dependencies = [ "async-trait", "auto_impl", "dyn-clone", + "evm2", + "evm2-inspectors", "futures", "jsonrpsee", "jsonrpsee-types", @@ -9062,11 +9215,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", @@ -9074,8 +9226,6 @@ dependencies = [ "reth-tasks", "reth-transaction-pool", "reth-trie-common", - "revm", - "revm-inspectors", "serde_json", "tokio", "tracing", @@ -9083,14 +9233,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-chains", "alloy-consensus", "alloy-eip7928", "alloy-eips", - "alloy-evm", "alloy-network", "alloy-primitives", "alloy-rpc-client", @@ -9099,6 +9248,8 @@ dependencies = [ "alloy-sol-types", "alloy-transport", "derive_more", + "evm2", + "evm2-inspectors", "futures", "itertools 0.14.0", "jsonrpsee-core", @@ -9112,20 +9263,17 @@ dependencies = [ "reth-ethereum-primitives", "reth-evm", "reth-execution-types", + "reth-lru", "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", - "schnellru", + "reth-trie-common", "serde", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "tokio-stream", "tracing", @@ -9134,13 +9282,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-rpc-types-engine", "http", + "http-body-util", "jsonrpsee-http-client", "pin-project", + "tokio", "tower", "tower-http", "tracing", @@ -9148,10 +9298,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ - "alloy-eips", "alloy-primitives", "alloy-rpc-types-engine", "jsonrpsee-core", @@ -9164,9 +9313,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", @@ -9174,15 +9322,47 @@ dependencies = [ "alloy-rpc-types-eth", "alloy-signer", "reth-primitives-traits", - "thiserror 2.0.18", + "thiserror 2.0.21", +] + +[[package]] +name = "reth-snap-sync" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" +dependencies = [ + "alloy-eip7928", + "alloy-eips", + "alloy-primitives", + "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.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", + "alloy-eip7928", "alloy-primitives", "alloy-rlp", "eyre", @@ -9213,7 +9393,6 @@ dependencies = [ "reth-provider", "reth-prune", "reth-prune-types", - "reth-revm", "reth-stages-api", "reth-static-file-types", "reth-storage-api", @@ -9223,15 +9402,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-eips", "alloy-primitives", @@ -9251,29 +9430,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" 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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-primitives", "parking_lot", @@ -9292,8 +9472,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-primitives", "clap", @@ -9307,8 +9487,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-eip7928", @@ -9316,6 +9496,7 @@ dependencies = [ "alloy-primitives", "alloy-rpc-types-engine", "auto_impl", + "reth-chain-state", "reth-chainspec", "reth-db-api", "reth-db-models", @@ -9325,16 +9506,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-eips", "alloy-primitives", @@ -9344,17 +9524,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-eips", "alloy-primitives", + "evm2", "metrics", "parking_lot", "rayon", @@ -9377,8 +9557,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "crossbeam-utils", "dashmap", @@ -9389,7 +9569,7 @@ dependencies = [ "pin-project", "rayon", "reth-metrics", - "thiserror 2.0.18", + "thiserror 2.0.21", "thread-priority", "tokio", "tracing", @@ -9398,24 +9578,23 @@ 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.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.5.2" -source = "git+https://github.com/morph-l2/reth?tag=v2.5.2-morph.1#b3b64033e42d459b236542b845513bf56c6ba760" +version = "2.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "tokio", "tokio-stream", @@ -9424,12 +9603,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "clap", "eyre", - "reth-tracing-otlp", "rolling-file", "tracing", "tracing-appender", @@ -9442,26 +9620,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" 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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-eips", @@ -9469,7 +9639,7 @@ dependencies = [ "alloy-rlp", "aquamarine", "auto_impl", - "bitflags 2.11.1", + "bitflags 2.13.2", "futures-util", "imbl", "metrics", @@ -9485,17 +9655,16 @@ dependencies = [ "reth-evm-ethereum", "reth-execution-types", "reth-fs-util", + "reth-lru", "reth-metrics", "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", @@ -9503,8 +9672,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-eips", @@ -9512,6 +9681,7 @@ dependencies = [ "alloy-rlp", "alloy-trie", "auto_impl", + "crossbeam-channel", "itertools 0.14.0", "metrics", "parking_lot", @@ -9520,17 +9690,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-consensus", "alloy-primitives", @@ -9542,6 +9712,7 @@ dependencies = [ "arrayvec", "bytes", "derive_more", + "evm2", "hash-db", "itertools 0.14.0", "nybbles", @@ -9549,15 +9720,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-primitives", "reth-db-api", @@ -9572,32 +9743,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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" 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.11.0" +source = "git+https://github.com/paradigmxyz/reth?tag=v2.11.0#b9abbcc1b982755baa9021e6874e2e58936ca65f" dependencies = [ "alloy-primitives", "alloy-trie", @@ -9606,264 +9773,39 @@ dependencies = [ "rayon", "reth-execution-errors", "reth-metrics", - "reth-primitives-traits", - "reth-trie-common", - "serde", - "serde_json", - "slotmap", - "smallvec", - "strum", - "tracing", -] - -[[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", + "reth-primitives-traits", + "reth-trie-common", + "smallvec", + "strum", + "tracing", ] [[package]] -name = "revm-state" -version = "42.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2c4ae66db3abfcb565854dbfc95513bfa440b3dc390ddf8e50b0363d12a6fa79" +name = "reth-zstd-compressors" +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]] @@ -9979,9 +9921,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", @@ -9992,12 +9934,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", @@ -10052,11 +9995,11 @@ 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", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -10103,7 +10046,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", @@ -10124,7 +10067,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", @@ -10136,7 +10079,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs 1.0.11", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -10232,17 +10175,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" @@ -10261,11 +10193,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", ] @@ -10293,6 +10240,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" @@ -10311,14 +10269,23 @@ 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", - "core-foundation 0.10.1", + "bitflags 2.13.2", + "core-foundation", "core-foundation-sys", "libc", "security-framework-sys", @@ -10380,6 +10347,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" @@ -10406,7 +10384,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", @@ -10474,7 +10451,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", ] @@ -10531,6 +10518,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" @@ -10597,6 +10595,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" @@ -10619,15 +10627,21 @@ 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" 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", ] @@ -10649,25 +10663,22 @@ 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" +version = "1.16.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" dependencies = [ "arbitrary", "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" @@ -10681,7 +10692,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]] @@ -10707,9 +10718,25 @@ 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]] +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" @@ -10842,12 +10869,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.11.1", - "core-foundation 0.9.4", + "bitflags 2.13.2", + "core-foundation", "system-configuration-sys", ] @@ -10894,7 +10921,7 @@ dependencies = [ "getrandom 0.4.2", "once_cell", "rustix", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -10914,11 +10941,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]] @@ -10934,13 +10961,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]] @@ -10949,7 +10976,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", @@ -11140,6 +11167,7 @@ dependencies = [ "futures-core", "futures-io", "futures-sink", + "futures-util", "pin-project-lite", "slab", "tokio", @@ -11205,54 +11233,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" @@ -11261,16 +11241,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]] @@ -11280,28 +11255,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]] @@ -11336,7 +11304,7 @@ checksum = "050686193eb999b4bb3bc2acfa891a13da00f79734704c4b8b4ef1a10b368a3c" dependencies = [ "crossbeam-channel", "symlink", - "thiserror 2.0.18", + "thiserror 2.0.21", "time", "tracing-subscriber", ] @@ -11417,22 +11385,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" @@ -11515,6 +11467,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" @@ -11536,7 +11497,7 @@ dependencies = [ "rustls", "rustls-pki-types", "sha1", - "thiserror 2.0.18", + "thiserror 2.0.21", ] [[package]] @@ -11587,12 +11548,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" @@ -11630,12 +11585,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]] @@ -11664,9 +11619,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", @@ -11806,6 +11761,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" @@ -11920,7 +11881,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", @@ -12034,7 +11995,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]] @@ -12043,6 +12004,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" @@ -12513,6 +12499,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" @@ -12563,7 +12552,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", @@ -12593,6 +12582,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" @@ -12612,7 +12613,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", @@ -12637,12 +12638,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" @@ -12709,18 +12704,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", @@ -12772,7 +12767,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]] @@ -12784,6 +12788,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 773ed379..0bb4f93d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,7 @@ [workspace.package] -version = "1.5.0" +version = "2.0.0" edition = "2024" -rust-version = "1.95" +rust-version = "1.96" license = "MIT OR Apache-2.0" publish = false @@ -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" @@ -118,150 +118,126 @@ 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", default-features = false } -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 = { 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.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-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-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-ethereum-cli = { 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 } +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" } +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-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.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.11.0" } +reth-trie-parallel = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } -reth-revm = { git = "https://github.com/morph-l2/reth", tag = "v2.5.2-morph.1", default-features = false, features = [ - "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.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.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-consensus = { 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-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" -alloy-sol-types = { version = "1.6.1", default-features = false } -alloy-transport = "2.3.0" +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" } +alloy-serde = "2.5.0" +alloy-signer = "2.5.0" +alloy-signer-local = "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" 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 +# tag; a drifted rev compiles a second, incompatible copy of these crates. +# +# 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://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" } +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/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 087ff49c..97af478a 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..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 @@ -31,7 +31,9 @@ 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 reth-tasks.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/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 a4e687de..0a3377dd 100644 --- a/bin/morph-statetest/Cargo.toml +++ b/bin/morph-statetest/Cargo.toml @@ -7,9 +7,11 @@ license.workspace = true publish.workspace = true [dependencies] -alloy-evm.workspace = true -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 @@ -17,8 +19,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/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 cb1e8b2d..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 = result_logs(&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 = result_logs(&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,27 +199,18 @@ where } } -/// A token-fee transaction's deduction and refund Transfers are part of the result's logs, -/// including when the main frame reverted or halted. -fn result_logs( - exec_result: &Result, E>, -) -> Vec { - exec_result - .as_ref() - .map(|result| result.logs().to_vec()) - .unwrap_or_default() +/// 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 @@ -262,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 { @@ -284,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(), } } @@ -304,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..1a07230e 100644 --- a/bin/morph-statetest/src/schema.rs +++ b/bin/morph-statetest/src/schema.rs @@ -1,23 +1,23 @@ +use alloy_eips::{eip2930::AccessList, eip7702::SignedAuthorization}; +use alloy_primitives::{Address, B256, Bytes, TxKind, U256}; +use alloy_signer_local::PrivateKeySigner; +use evm2::{ + bytecode::Bytecode, + 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::{MorphAuthorization, 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 +26,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 +202,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, - }); - } - - if block.prevrandao.is_none() { - block.prevrandao = Some(B256::ZERO); + .current_random + .map(|random| U256::from_be_bytes(random.0)) + .unwrap_or_default(), + slot_num: self.env.slot_number.unwrap_or_default(), + ..Default::default() } - - 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 +274,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 +319,7 @@ impl MorphTransactionParts { .map(|auth_list| { auth_list .into_iter() - .map(|auth| { - revm::context::either::Either::::Left(auth.into()) - }) + .map(|auth| MorphAuthorization::Signed(auth.0)) .collect() }) .unwrap_or_default(); @@ -257,16 +335,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,35 +350,40 @@ 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() { - // 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); - } 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 +404,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 +562,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 +630,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)); @@ -632,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/bin/morph-statetest/src/trace.rs b/bin/morph-statetest/src/trace.rs new file mode 100644 index 00000000..559afba6 --- /dev/null +++ b/bin/morph-statetest/src/trace.rs @@ -0,0 +1,342 @@ +//! EIP-3155 execution tracer for debugging fixtures. +//! +//! Streams one JSON struct log per executed opcode, in the line format of `geth --json`. + +use alloy_primitives::U256; +use evm2::{ + EvmTypesHost, Inspector, + interpreter::{InstrStop, Interpreter, Message, MessageResult, opcode::OpCode}, +}; +use serde::Serialize; +use std::io::Write; + +/// Per-opcode state captured in `step`, emitted once its gas cost and stop outcome are known. +#[derive(Debug)] +struct PendingStep { + pc: usize, + op: u8, + gas: u64, + stack: Vec, + depth: u16, + mem_size: usize, + 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 { + 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 and any fault/revert marker. + /// + /// 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 = 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}"); + } + } +} + +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>) { + 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( + &mut self, + interp: &mut Interpreter<'_, '_, T>, + _message: &mut Message, + ) -> Option> { + self.flush_pending(interp, None); + None + } + + fn create( + &mut self, + interp: &mut Interpreter<'_, '_, T>, + _message: &mut Message, + ) -> Option> { + 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()); + } +} diff --git a/crates/chainspec/Cargo.toml b/crates/chainspec/Cargo.toml index e31034b8..00a7827e 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/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/hardfork.rs b/crates/chainspec/src/hardfork.rs index 830104b4..9e1e4f09 100644 --- a/crates/chainspec/src/hardfork.rs +++ b/crates/chainspec/src/hardfork.rs @@ -33,8 +33,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!( @@ -208,9 +208,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) @@ -222,10 +222,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] @@ -254,53 +254,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/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 936f3c7a..7cccb30d 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; @@ -26,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. @@ -75,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() @@ -155,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)?, + )?), }) } @@ -211,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. @@ -232,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 @@ -248,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. @@ -311,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") } } @@ -426,12 +502,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) @@ -922,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/consensus/Cargo.toml b/crates/consensus/Cargo.toml index 265da655..96146443 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, features = ["std"] } 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/consensus/src/validation.rs b/crates/consensus/src/validation.rs index 3f101eea..a1889ee0 100644 --- a/crates/consensus/src/validation.rs +++ b/crates/consensus/src/validation.rs @@ -41,7 +41,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, MorphChainSpec, MorphHardforks}; use morph_primitives::{ @@ -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, @@ -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(()) } @@ -2459,7 +2601,7 @@ mod tests { U256::ZERO, )); - let result = alloy_evm::block::BlockExecutionResult { + let result = BlockExecutionResult { receipts: vec![receipt], requests: Default::default(), gas_used: 21000, @@ -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/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..211be35a 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(), } } @@ -456,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); @@ -524,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); @@ -591,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); @@ -624,42 +638,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 +732,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 +744,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 +798,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, @@ -854,13 +929,18 @@ impl RealMorphL2EngineApi { &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)?; + 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 @@ -869,17 +949,27 @@ 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; + + 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); @@ -891,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) } @@ -1036,6 +1188,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 +1208,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 +1513,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 +1524,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 +1533,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 +1669,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/Cargo.toml b/crates/evm/Cargo.toml index 312b43d8..79cef8b4 100644 --- a/crates/evm/Cargo.toml +++ b/crates/evm/Cargo.toml @@ -19,19 +19,22 @@ morph-payload-types = { workspace = true, optional = 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"] } +evm2-inspectors = { workspace = true, optional = true } + alloy-consensus.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] @@ -43,11 +46,21 @@ rayon.workspace = true default = [] serde-bincode-compat = [ "morph-primitives/serde-bincode-compat", + "reth-execution-types/serde-bincode-compat", +] +# 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:evm2-inspectors", + "dep:reth-rpc-eth-api", + "morph-primitives/reth-codec", ] -# 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-revm/rpc", "morph-primitives/reth-codec"] 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 9b66a3f9..d5133a4d 100644 --- a/crates/evm/src/block/mod.rs +++ b/crates/evm/src/block/mod.rs @@ -2,54 +2,142 @@ //! //! 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; +mod simulate; -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::{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 alloy_primitives::{Address, 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 { .. } + | HandlerError::IntrinsicGasGreaterThanCap { .. } + ) + } + + fn is_gas_limit_too_low(&self) -> bool { + matches!( + self.0, + HandlerError::IntrinsicGasTooLow { .. } | HandlerError::GasLimitBelowFloor { .. } + ) + } + + /// 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: AnyError::new(error), + } + .into() + } + HandlerError::Database(_) + | HandlerError::Fatal(_) + | HandlerError::WrongTransactionType { .. } => InternalBlockExecutionError::EVM { + hash, + error: AnyError::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 handler_error = match error { + BlockExecutionError::Validation(BlockValidationError::InvalidTx { error, .. }) => { + error.as_any().downcast_ref::()? + } + BlockExecutionError::Validation(BlockValidationError::Other(error)) => { + error.downcast_ref::()? + } + _ => return None, + }; + handler_error.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, + 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 { + fn into_result(self) -> TxResultWithState { self.result } } @@ -74,11 +162,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`: Build receipt from the cached fee info, 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 @@ -90,25 +179,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, } } @@ -117,10 +212,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); @@ -133,54 +226,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. /// @@ -197,132 +340,550 @@ 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 (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())); + } - // Execute the transaction - let result = self - .evm - .transact(tx_env) - .map_err(|err| BlockExecutionError::evm(err, *consensus_tx.tx_hash()))?; + 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())?, + }; - // Read caches from the EVM immediately after execution, before the next tx resets them. - let l1_fee = self.evm.cached_l1_data_fee(); + 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()))?; - Ok(MorphTxResult { - result, - recovered: Recovered::new_unchecked(consensus_tx, signer), - l1_fee, - }) + Ok(MorphTxResult { result, input }) } - fn commit_transaction(&mut self, output: Self::Result) -> GasOutput { - let MorphTxResult { - result: ResultAndState { result, state }, - recovered, - l1_fee, - } = output; + fn commit_transaction( + &mut self, + output: Self::TransactionResultWithState, + ) -> Result { + let MorphTxResult { result, input } = output; + let TxResultWithState { + result, + pending_state, + .. + } = result; - // 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(); + 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, }; 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 receipts(&self) -> &[Self::Receipt] { + &self.receipts } - fn finish( + 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; + 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, + ) -> 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)), + } + } + + fn legacy_tx(tx_seq: u64, gas_limit: u64) -> MorphTxEnvelope { + MorphTxEnvelope::Legacy(Signed::new_unhashed( + TxLegacy { + chain_id: Some(1337), + nonce: tx_seq, + 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)) + ); + + 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] + 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()); + } + + #[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), + ); + + // 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()); + 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/block/receipt.rs b/crates/evm/src/block/receipt.rs index 79219afe..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,35 +25,31 @@ //! | 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, U256}; -use morph_primitives::{MorphReceipt, MorphTransactionReceipt, MorphTxEnvelope, MorphTxType}; -use revm::context::result::ExecutionResult; +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) #[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, } @@ -68,13 +63,13 @@ pub(crate) struct MorphReceiptBuilderCtx<'a, E: Evm> { /// /// # Token Fee Calculation Formula /// ```text -/// token_fee = eth_fee * token_scale / fee_rate (rounded up) +/// token_fee = eth_fee * fee_rate / token_scale /// ``` /// /// # Fields /// - `version`: The version of the Morph transaction format (0 = legacy, 1 = with reference/memo) /// - `fee_token_id`: ID of the ERC20 token registered in L2TokenRegistry -/// - `fee_rate`: Price ratio from L2TokenRegistry (token price relative to ETH) +/// - `fee_rate`: Exchange rate from L2TokenRegistry (token per ETH) /// - `token_scale`: Decimal scale factor for the token (e.g., 10^18) /// - `fee_limit`: Maximum tokens the user agreed to pay /// - `reference`: 32-byte key for transaction indexing by external systems @@ -114,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`]. @@ -141,32 +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, } = ctx; + let l1_fee = result.ext.l1_data_fee; - // For a token-fee MorphTx `result` already holds the logs in go-ethereum's order: - // [deduct Transfer] + [main tx logs, on success] + [refund Transfer] - // The handler leaves both fee transfers' logs in the journal and the main frame - // reverts only back to its own checkpoint, so they survive a failed main frame, - // as they do in go-ethereum, whose `StateDB.logs` sit outside the snapshot/revert - // mechanism. revm returns the journal's logs for successes, reverts and halts alike. - let is_success = result.is_success(); - let logs = result.into_logs(); - + // The EVM reports logs in chronological order, matching go-ethereum: + // [deduct Transfer] + [main tx logs] + [refund Transfer] + // 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)) } @@ -187,7 +177,7 @@ impl MorphReceiptBuilder for DefaultMorphReceiptBuilder { // MorphTx transactions should always have MorphTx-specific fields. // If fields are missing, it indicates one of the following: // 1. The fee token is not registered in L2TokenRegistry - // 2. The token registry lookup failed (logged by commit_transaction) + // 2. TokenFeeInfo::fetch returned None (token inactive or query failed) // 3. A bug in get_morph_tx_fields logic // // We log a warning and fallback to L1-fee-only receipt to avoid @@ -207,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." ); @@ -221,130 +210,47 @@ 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) - } - - 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()), - } - } + use alloy_consensus::TxReceipt; + use alloy_primitives::{Address, Log}; + use evm2::{TxResultExt, interpreter::InstrStop}; + use morph_revm::MorphTxResultExt; - 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, }; @@ -358,14 +264,12 @@ 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, }; @@ -378,15 +282,13 @@ 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, }; @@ -399,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 { @@ -412,11 +313,10 @@ 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), }; @@ -442,15 +342,13 @@ 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, }; @@ -475,13 +373,11 @@ 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, }; @@ -495,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)], @@ -503,11 +398,10 @@ 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, }; @@ -515,67 +409,21 @@ mod tests { 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() - } - - /// A reverted or halted `ExecutionResult` still carries the logs emitted before the - /// main frame failed, which is where the handler leaves a token-fee transaction's - /// deduction and refund Transfers (go-ethereum keeps them in `StateDB.logs`, outside - /// the snapshot/revert mechanism). The receipt must keep them, in order. + /// A reverted token-fee transaction still reports the fee transfers the EVM kept. #[test] - fn test_reverted_receipt_keeps_fee_logs() { + fn test_build_receipt_keeps_logs_of_a_failed_transaction() { let builder = DefaultMorphReceiptBuilder; - let tx = create_morph_tx(); + let log = Log::new(Address::repeat_byte(0x01), vec![], Bytes::new()).unwrap(); - let deduct_log = make_fee_log(0xAA); - let refund_log = make_fee_log(0xBB); - - let ctx = MorphReceiptBuilderCtx:: { - tx: &tx, - result: ExecutionResult::Revert { - gas: result_gas(20_000), - logs: vec![deduct_log.clone(), refund_log.clone()], - output: alloy_primitives::Bytes::new(), - }, - cumulative_gas_used: 20_000, - l1_fee: U256::ZERO, - morph_tx_fields: None, - }; - - let receipt = builder.build_receipt(ctx); - - assert!( - !TxReceipt::status(&receipt), - "reverted tx must have status=false" - ); - assert_eq!(TxReceipt::logs(&receipt), &[deduct_log, refund_log]); - } - - /// On success the result's logs, `[deduct] + [main] + [refund]`, reach the receipt - /// unchanged. - #[test] - fn test_successful_receipt_keeps_log_order() { - let builder = DefaultMorphReceiptBuilder; - let tx = create_morph_tx(); - - let logs = vec![make_fee_log(0xAA), make_fee_log(0xCC), make_fee_log(0xBB)]; - - let ctx = MorphReceiptBuilderCtx:: { - tx: &tx, - result: make_success_with_logs(21_000, logs.clone()), - 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, }; let receipt = builder.build_receipt(ctx); - assert!(TxReceipt::status(&receipt)); - assert_eq!(TxReceipt::logs(&receipt), logs.as_slice()); + assert!(!TxReceipt::status(&receipt)); + assert_eq!(TxReceipt::logs(&receipt).len(), 2); } } 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 5eaf28fd..ba989534 100644 --- a/crates/evm/src/config.rs +++ b/crates/evm/src/config.rs @@ -1,16 +1,16 @@ -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; -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 { @@ -18,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 } @@ -33,45 +36,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 +76,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 +122,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 +134,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 +212,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 +223,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 +237,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 +249,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 +274,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/context.rs b/crates/evm/src/context.rs index de01f683..ba508472 100644 --- a/crates/evm/src/context.rs +++ b/crates/evm/src/context.rs @@ -1,5 +1,17 @@ +#[cfg(feature = "rpc")] +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 +31,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/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 32a67f87..01c74c16 100644 --- a/crates/evm/src/evm.rs +++ b/crates/evm/src/evm.rs @@ -1,270 +1,474 @@ -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, Log, U256}; +use core::any::TypeId; +use evm2::{ + ExecutedTx, Inspector, InspectorConfig, TxResult, TxResultWithState, + evm::{AccountInfo, Cache, DynDatabase, NonStaticAny, PendingState}, + interpreter::{Interpreter, Message, MessageResult}, + 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; +#[cfg(feature = "rpc")] +use evm2_inspectors::transfer::TransferInspector; +/// 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) +/// 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() } -} -/// Morph EVM implementation. -/// -/// 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 -/// `morph_revm::MorphEvm` type. -#[expect(missing_debug_implementations)] -pub struct MorphEvm { - inner: morph_revm::MorphEvm, - /// Precompiles wrapped as PrecompilesMap for reth compatibility - precompiles_map: PrecompilesMap, - inspect: bool, -} + fn initialize_interp(&mut self, interp: &mut Interpreter<'_, '_, MorphEvmTypes>) { + self.0.initialize_interp(interp); + } -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()); + fn step(&mut self, interp: &mut Interpreter<'_, '_, MorphEvmTypes>) { + self.0.step(interp); + } - Self { - inner, - precompiles_map, - inspect: false, - } + fn step_end(&mut self, interp: &mut Interpreter<'_, '_, MorphEvmTypes>) { + self.0.step_end(interp); } -} -impl MorphEvm { - /// Provides a reference to the EVM context. - pub const fn ctx(&self) -> &MorphContext { - &self.inner.inner.ctx + fn log(&mut self, log: &Log, host: &mut morph_revm::MorphEvm<'_>) { + self.0.log(log, host); } - /// Provides a mutable reference to the EVM context. - pub fn ctx_mut(&mut self) -> &mut MorphContext { - &mut self.inner.inner.ctx + fn call( + &mut self, + interp: &mut Interpreter<'_, '_, MorphEvmTypes>, + message: &mut Message, + ) -> Option> { + self.0.call(interp, message) } - /// 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, - } + fn call_end( + &mut self, + interp: &mut Interpreter<'_, '_, MorphEvmTypes>, + message: &Message, + result: &mut MessageResult, + ) { + self.0.call_end(interp, message, result); } - /// 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() + fn create( + &mut self, + interp: &mut Interpreter<'_, '_, MorphEvmTypes>, + message: &mut Message, + ) -> Option> { + self.0.create(interp, message) } - /// 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() + 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); } } -impl Deref for MorphEvm +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 - DB: Database, - I: Inspector>, + I: Inspector + 'static, { - type Target = MorphContext; + 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())) +} + +/// 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. 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>, + unwrap_inspector: Option>, +} + +impl<'a> MorphEvm<'a> { + /// Creates a Morph EVM over `database`. + pub fn new(database: impl DynDatabase + 'a, env: MorphEvmEnv) -> Self { + Self { + inner: morph_revm::morph_evm(database, env), + unwrap_inspector: None, + } + } +} + +impl<'a> Deref for MorphEvm<'a> { + type Target = morph_revm::MorphEvm<'a>; #[inline] fn deref(&self) -> &Self::Target { - self.ctx() + &self.inner } } -impl DerefMut for MorphEvm -where - DB: Database, - I: Inspector>, -{ +/// 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 { - self.ctx_mut() + &mut self.inner } } -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; +impl<'a> Evm for MorphEvm<'a> { + type EvmTypes = MorphEvmTypes; + type Transaction = MorphTxEnv; - fn block(&self) -> &Self::BlockEnv { - &self.block + fn transact( + &mut self, + transaction: &Recovered, + ) -> Result, BlockExecutionError> { + Evm::transact(&mut self.inner, transaction) } - fn cfg_env(&self) -> &CfgEnv { - &self.inner.inner.ctx.cfg + fn transact_commit( + &mut self, + transaction: &Recovered, + ) -> Result, BlockExecutionError> { + Evm::transact_commit(&mut self.inner, transaction) } - fn chain_id(&self) -> u64 { - self.cfg.chain_id + fn transact_result( + &mut self, + transaction: &Recovered, + ) -> Result, BlockExecutionError> { + Evm::transact_result(&mut self.inner, transaction) } - fn transact_raw( + fn transact_with_inspector( &mut self, - tx: Self::Tx, - ) -> Result, Self::Error> { - if self.inspect { - self.inner.inspect_tx(tx) + transaction: &Recovered, + inspector: I, + ) -> Result<(I, TxResultWithState), BlockExecutionError> + where + 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, + FeeFrameFilter::new(inspector), + )?; + Ok((filter.into_inner(), result)) + } + + fn set_inspector(&mut self, inspector: I) + 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)), + ); + 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 { - self.inner.transact(tx) + None } } - 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_inspector(&mut self) -> Option + '_>> { + match self.unwrap_inspector.take() { + Some(unwrap) => unwrap(&mut self.inner), + None => Evm::take_inspector(&mut self.inner), + } } - fn finish(self) -> (Self::DB, EvmEnv) { - let Context { - block: block_env, - cfg: cfg_env, - journaled_state, - .. - } = self.inner.inner.ctx; + fn state_db_mut(&mut self) -> &mut dyn DynDatabase { + Evm::state_db_mut(&mut self.inner) + } + + fn commit_state(&mut self, state: &PendingState) { + Evm::commit_state(&mut self.inner, state); + } - (journaled_state.database, EvmEnv { block_env, cfg_env }) + fn take_state_cache(&mut self) -> Cache { + Evm::take_state_cache(&mut self.inner) } - fn set_inspector_enabled(&mut self, enabled: bool) { - self.inspect = enabled; + fn precompile_ids(&self) -> Vec<(Address, PrecompileId)> { + Evm::precompile_ids(&self.inner) } - fn components(&self) -> (&Self::DB, &Self::Inspector, &Self::Precompiles) { - ( - &self.inner.inner.ctx.journaled_state.database, - &self.inner.inner.inspector, - &self.precompiles_map, - ) + fn has_precompile(&self, address: &Address) -> bool { + Evm::has_precompile(&self.inner, address) } - 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 account_info( + &mut self, + address: &Address, + ) -> Result, BlockExecutionError> { + Evm::account_info(&mut self.inner, address) + } + + fn move_precompiles( + &mut self, + moves: impl IntoIterator, + ) -> Result<(), MovePrecompileError> { + Evm::move_precompiles(&mut self.inner, moves) + } + + 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), + &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); + 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() }, + Address::ZERO, ); - let mut evm = MorphEvm::new( - db, - EvmEnv { - block_env: MorphBlockEnv { - inner: BlockEnv { - basefee: 1, - ..Default::default() - }, - }, + let result = Evm::transact(&mut evm, &tx).unwrap(); + + 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 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); + 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() - }) - .unwrap(); + }, + 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 + ); - assert!(result.result.is_success()); + 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::>>() + ); + } + + /// `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/evm/src/lib.rs b/crates/evm/src/lib.rs index fc0d1f82..3e008f72 100644 --- a/crates/evm/src/lib.rs +++ b/crates/evm/src/lib.rs @@ -77,22 +77,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, MorphInvalidTransaction}; /// 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 ccdad592..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 @@ -51,6 +52,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 @@ -61,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..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. @@ -267,13 +269,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/components/pool.rs b/crates/node/src/components/pool.rs index ae4d9199..7d3e9f10 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,22 @@ 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, while preserving an explicit `--txpool.gas-limit`. + 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); + 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(); @@ -54,7 +71,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/src/test_utils.rs b/crates/node/src/test_utils.rs index 8874e847..77d3a130 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, } } @@ -271,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() @@ -282,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. @@ -316,6 +369,30 @@ impl TestNodeBuilder { 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 +422,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,7 +439,10 @@ impl TestNodeBuilder { let desired_gas_limit = self.desired_gas_limit; let debug_tip = self.debug_tip; let trusted_peer = self.trusted_peer; - reth_e2e_test_utils::E2ETestSetupBuilder::::new( + 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), morph_payload_attributes, @@ -364,9 +450,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 +477,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 +491,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 6e9b37e8..eab534df 100644 --- a/crates/node/src/validator.rs +++ b/crates/node/src/validator.rs @@ -3,17 +3,19 @@ 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, }; -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, ReceiptRootBloom}; use reth_engine_tree::tree::payload_validator::TreeCtx; use reth_engine_tree::tree::{ BasicEngineValidator, CacheWaitDurations, EngineApiTreeState, EngineValidator, @@ -25,8 +27,8 @@ use reth_engine_tree::tree::{ StateRootJobOutcome, StateRootStrategy, }, }; -use reth_errors::{ConsensusError, ProviderResult}; -use reth_evm::{ConfigureEvm, revm::context::Block as _}; +use reth_errors::{ConsensusError, ProviderError, ProviderResult}; +use reth_evm::{ConfigureEvm, EvmEnv as _}; use reth_node_api::{ AddOnsContext, FullNodeComponents, InvalidPayloadAttributesError, NewPayloadError, NodeTypes, PayloadAttributes, PayloadTypes, PayloadValidator, @@ -36,18 +38,22 @@ 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, SealedHeader}; use reth_provider::{ - BlockExecutionOutput, BlockNumReader, BlockReader, ChainSpecProvider, DatabaseProviderFactory, - PruneCheckpointReader, StageCheckpointReader, StateProviderFactory, StateReader, - StateRootProvider, StorageSettingsCache, TryIntoHistoricalStateProvider, + BlockExecutionOutput, BlockExecutionResult, 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, }; -use std::{collections::VecDeque, sync::Arc}; +use std::{ + collections::{HashMap, VecDeque}, + sync::Arc, +}; /// Builder for Morph engine validator (payload validation). /// @@ -126,14 +132,22 @@ where let post_execution_validator = validator.clone(); let provider = ctx.node.provider().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())); + > = Arc::new(MorphStateRootStrategy::new( + chain_spec, + 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( provider.clone(), - Arc::new(ctx.node.consensus().clone()), + consensus, ctx.node.evm_config().clone(), validator, tree_config, @@ -151,7 +165,7 @@ where Ok(MorphTreeEngineValidator::new( validator, provider, - chain_spec, + engine_consensus, post_execution_validator, )) } @@ -218,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 @@ -234,27 +398,37 @@ where { inner: BasicEngineValidator, provider: P, - chain_spec: 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, + engine_consensus: Arc, post_execution_validator: MorphEngineValidator, ) -> Self { Self { inner, provider, - chain_spec, + 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 @@ -262,22 +436,25 @@ where Evm: ConfigureEvm, P: BlockReader
, { + fn lookup_sealed_header( + &self, + hash: B256, + ) -> ProviderResult>> { + if let Some(header) = self.tree_headers.lock().get(&hash).cloned() { + return Ok(Some(header)); + } + self.provider.sealed_header_by_hash(hash) + } + fn validate_next_l1_msg_index( &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)?, + None => self.lookup_sealed_header(parent_hash)?, }; let Some(parent) = parent else { // The upstream validator reports the missing parent with the @@ -285,36 +462,10 @@ where return Ok(()); }; - let mut expected = parent.next_l1_msg_index; - 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") - })?; - expected = queue_index.checked_add(1).ok_or_else(|| { - ConsensusError::other(MorphConsensusError::InvalidNextL1MessageIndex { - expected: u64::MAX, - actual: block.header().next_l1_msg_index, - }) - })?; - } - - // 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(), - ); - } - Ok(()) + self.engine_consensus + .inner() + .validate_l1_msg_index_against_parent(block, parent.header()) + .map_err(Into::into) } fn validate_next_l1_msg_index_for_block( @@ -327,14 +478,39 @@ where .map_err(|kind| InsertBlockError::new(block.clone(), kind).into()) } - fn validate_withdraw_trie_root( + /// 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(); + consensus + .validate_header_structural(sealed_header) + .map_err(ProviderError::other)?; + if let Some(parent) = self.lookup_sealed_header(block.parent_hash())? { + consensus + .validate_header_against_parent_structural(sealed_header, &parent) + .map_err(ProviderError::other)?; + consensus + .validate_l1_msg_index_against_parent(block.sealed_block(), parent.header()) + .map_err(ProviderError::other)?; + } + consensus + .validate_block_pre_execution_without_da_limit(block.sealed_block()) + .map_err(ProviderError::other)?; + Ok(()) + } + + 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(), || { + if let Err(err) = + MorphEngineValidator::validate_withdraw_trie_root_expectation(expectation, || { output.executed_block.hashed_state() }) { @@ -345,6 +521,13 @@ where .into()); } + self.record_tree_header( + output + .executed_block + .recovered_block() + .sealed_header() + .clone(), + ); Ok(output) } } @@ -368,38 +551,64 @@ where fn convert_payload_to_block( &self, - payload: MorphExecutionData, + mut payload: MorphExecutionData, ) -> Result, NewPayloadError> { + let block_hash = payload.block.hash(); + // 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.is_zero()) + { + self.post_execution_validator + .take_withdraw_trie_root_expectation(block_hash); + 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)?; + if payload.is_safe { + self.engine_consensus.mark_safe(block_hash); + } + + let output = self.inner.validate_payload(payload, ctx)?; + let expectation = MorphEngineValidator::expectation_from_root(expected_withdraw_trie_root); + self.verify_withdraw_trie_root(expectation, output) } 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)?; @@ -407,17 +616,27 @@ 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( &self, block: BuiltPayloadExecutedBlock, ) -> ProviderResult> { - self.inner.on_inserted_executed_block(block) + self.validate_pre_inserted_block(block.recovered_block.as_ref())?; + 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); } @@ -447,21 +666,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

@@ -474,8 +701,9 @@ where P::Provider: BlockNumReader + PruneCheckpointReader + StageCheckpointReader + + ChangeSetReader + + StorageChangeSetReader + StorageSettingsCache - + TryIntoHistoricalStateProvider + 'static, Evm: ConfigureEvm + 'static, DefaultStateRootStrategy: StateRootStrategy, @@ -484,14 +712,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, )) @@ -509,24 +741,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 { @@ -539,7 +765,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( @@ -553,11 +779,16 @@ where /// /// 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_root_order: Arc>>, + expected_withdraw_trie_roots: Arc>>, +} + +impl Default for MorphEngineValidator { + fn default() -> Self { + Self::new() + } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -571,7 +802,20 @@ 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 { + 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( @@ -579,40 +823,16 @@ impl MorphEngineValidator { block_hash: B256, expectation: WithdrawTrieRootExpectation, ) { - let is_new_entry = self - .expected_withdraw_trie_roots - .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); - - while self.expected_withdraw_trie_roots.len() > Self::MAX_EXPECTED_WITHDRAW_TRIE_ROOTS { - let Some(evicted_hash) = order.pop_front() else { - break; - }; - self.expected_withdraw_trie_roots.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 removed = self - .expected_withdraw_trie_roots - .remove(&block_hash) - .map(|(_, expected)| expected); - - if removed.is_some() { - self.expected_withdraw_trie_root_order - .lock() - .retain(|hash| *hash != block_hash); - } - - removed + self.expected_withdraw_trie_roots.lock().remove(&block_hash) } fn clear_withdraw_trie_root_expectation_on_error( @@ -644,19 +864,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(()); }; @@ -676,6 +887,23 @@ impl MorphEngineValidator { } Ok(()) } + + #[cfg(test)] + 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 { @@ -688,13 +916,16 @@ 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 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) } @@ -770,10 +1001,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); @@ -782,23 +1017,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] @@ -1058,6 +1285,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() { @@ -1173,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/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..a951611b 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,694 @@ 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(()) +} + +/// `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 d67d5590..b74c0628 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,287 @@ 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(()) +} + +/// 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 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 mut node = nodes.pop().expect("one node requested"); + + let base_payload = build_block_no_submit(&mut node, vec![]).await?; + + 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(); + + // 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"), + ); + + // 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"), + ); + + // 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:?}" + ); + + // 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!( + b1_status.is_valid(), + "connecting parent block 1 must succeed: {b1_status:?}" + ); + + // 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/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/proof_history.rs b/crates/node/tests/it/proof_history.rs index f7041c58..72c80205 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}; @@ -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; @@ -474,11 +475,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 +783,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 +804,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); @@ -1486,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/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 2e49b44a..40c5766d 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`). @@ -1310,3 +1310,1817 @@ 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(()) +} + +/// `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(()) +} + +/// `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)) +} + +/// 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 eth_simulate_v1_morph_l1_fee_and_token_semantics() -> 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 + 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)) + .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.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(); + + 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); + + 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) + }) + }; + + // ------------------------------------------------------------------------- + // 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 }, + }, + "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}"); + } + + 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 + ); + + // 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!( + override_blocks[0]["calls"][0]["status"].as_str(), + Some("0x1"), + "baseFeePerGas override must not reject zero-fee MorphTx under validation:false: {override_blocks}" + ); + } + + // ------------------------------------------------------------------------- + // 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 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", (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" + ); + } + + // ------------------------------------------------------------------------- + // 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); + } + + // ------------------------------------------------------------------------- + // 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_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 eth_call_and_call_many_respect_rpc_gas_cap_under_block_gas_limit_override() +-> eyre::Result<()> { + reth_tracing::init_test_tracing(); + + // 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().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 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", + }); + + // (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}]" + ); + 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!( + eth_gas_seen > 49_000_000, + "expected gas cap ~{DEFAULT_RPC_GAS_CAP} under max block gas override, got {eth_gas_seen}" + ); + + // (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}" + ); + } + + // (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 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("out of gas"), + "expected OutOfGas error, got: {err_str}" + ); + + 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)), + } + }); + + ( + 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?; + Ok((nodes.pop().unwrap(), wallet)) +} + +/// `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(); + + 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) }), + ); + 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); + + // 1. Without `blockOverrides.gasLimit`, the 30M header ceiling rejects a 35M contract. + client + .request::( + "eth_estimateGas", + ( + serde_json::json!({ "from": zero_eth_slot_sender, "to": contract_35m }), + "latest", + state_overrides.clone(), + ), + ) + .await + .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), + }); + 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 pending_est_u64 = u64::try_from(pending_est)?; + assert!( + 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 acd3e31d..28eda327 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,39 +271,184 @@ 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_max_fee_below_base_fee_accepted_for_queuing() -> eyre::Result<()> { +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 node = nodes.pop().unwrap(); + 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(()) +} + +/// 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, + tx_seq: 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: tx_seq, 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 pools low-fee txs for future execution when baseFee drops, - // so they are accepted into the queued set, not rejected outright. + 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(); + + 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(()) } @@ -325,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 9b614d4a..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,25 +23,24 @@ 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 reth-primitives-traits.workspace = true -reth-revm = { workspace = true, features = ["std"] } 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 @@ -51,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 fea02de9..f0baf720 100644 --- a/crates/payload/builder/src/builder.rs +++ b/crates/payload/builder/src/builder.rs @@ -2,25 +2,31 @@ use crate::metrics::MorphPayloadBuilderMetrics; use crate::{MorphBuilderConfig, MorphPayloadBuilderError, config::PayloadBuildingBreaker}; -use alloy_consensus::{BlockHeader, Transaction, Typed2718}; -use alloy_eips::eip2718::Encodable2718; -use alloy_primitives::{B256, Bytes, U256}; -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_consensus::{BlockHeader, Transaction, Typed2718, transaction::TxHashRef}; +use alloy_eips::{BlockId, eip2718::Encodable2718}; +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, }; 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 _, InvalidTxError, NextBlockEnvAttributes, OnStateHook, + database::StateProviderDatabase, }; use reth_execution_cache::{CachedStateMetrics, CachedStateMetricsSource, CachedStateProvider}; use reth_execution_types::BlockExecutionOutput; @@ -28,17 +34,88 @@ 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::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(_) + ) +} + +/// 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( + 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(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)) } @@ -194,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(), }; @@ -208,27 +293,34 @@ 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( cached_reads.as_db_mut(state), state_provider.as_ref(), + &self.client, + &self.pool, ctx, best, state_root_handle, @@ -293,11 +385,14 @@ 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. 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, } @@ -349,11 +444,16 @@ 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; + 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()`. @@ -369,21 +469,68 @@ 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(), + }, + ) + })?; + // 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!( + "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(); @@ -431,9 +578,9 @@ impl MorphPayloadBuilderCtx { // Execute the transaction and record EVM execution time. let apply_started = Instant::now(); - // `BlockBuilder::execute_transaction` returns alloy-evm's `GasOutput`; - // 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 { @@ -483,24 +630,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 @@ -514,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; @@ -528,22 +665,61 @@ 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, info: &mut ExecutionInfo, 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 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(())); } @@ -582,6 +758,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) { @@ -630,6 +826,24 @@ impl MorphPayloadBuilderCtx { "skipping invalid transaction and its descendants" ); best_txs.mark_invalid(tx.signer(), tx.nonce()); + // 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", + 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; } @@ -659,6 +873,7 @@ impl MorphPayloadBuilderCtx { self.metrics .commit_tx_apply_duration_seconds .record(apply_started.elapsed()); + info.executed_senders.insert(tx.signer()); // Update execution info info.cumulative_gas_used += gas_used; @@ -699,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, @@ -713,6 +930,7 @@ impl ExecutionInfo { total_fees: U256::ZERO, next_l1_message_index, transaction_count: 0, + executed_senders: HashSet::new(), max_da_block_size, } } @@ -742,16 +960,20 @@ impl ExecutionInfo { } /// Builds the payload on top of the state. -fn build_payload_inner<'a, DB, BestTxs>( +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, mut state_root_handle: Option, ) -> Result, PayloadBuilderError> where - DB: Database, + DB: Database + 'a, BestTxs: PayloadTransactions> + 'a, + Client: StateProviderFactory, + Pool: TransactionPool>, { let build_started = Instant::now(); let attributes = ctx.attributes(); @@ -764,11 +986,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 +1007,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 +1015,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 +1030,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); @@ -838,6 +1057,8 @@ where &mut info, &mut executed_txs, best_txs, + client, + pool, &breaker, )? .is_some() @@ -880,31 +1101,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 `state_root_handle` is provided, drop the state hook to signal FinishedStateUpdates - // to the background sparse trie task (via `StateRootUpdateHook`'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 +1130,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)? }; @@ -973,7 +1191,7 @@ where let executed = has_transactions.then(|| { let execution_output = BlockExecutionOutput { result: execution_result, - state: db.take_bundle(), + state: execution_state, }; BuiltPayloadExecutedBlock { recovered_block: Arc::new(block), @@ -1201,6 +1419,7 @@ mod tests { cancel: Default::default(), best_payload, builder_config: MorphBuilderConfig::default(), + can_evict_from_pool: true, metrics: MorphPayloadBuilderMetrics::default(), } } @@ -1238,65 +1457,927 @@ mod tests { // read_withdraw_trie_root tests (requires mock DB) // ========================================================================= - struct MockDb { - storage_value: U256, + 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) } - impl revm::Database for MockDb { - type Error = std::convert::Infallible; + #[test] + fn test_read_withdraw_trie_root_zero() { + let mut state = state_with_withdraw_trie_root(U256::ZERO); + let root = read_withdraw_trie_root(&mut state).unwrap(); + assert_eq!(root, B256::ZERO); + } - fn basic( - &mut self, - _address: alloy_primitives::Address, - ) -> Result, Self::Error> { - Ok(None) + #[test] + fn test_read_withdraw_trie_root_nonzero() { + let expected = B256::from([0xAB; 32]); + 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 state = state_with_withdraw_trie_root(U256::MAX); + 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 code_by_hash( + 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, - _code_hash: B256, - ) -> Result { - Ok(revm::bytecode::Bytecode::default()) + 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 storage( + fn execute_transaction_with_result_closure( &mut self, - _address: alloy_primitives::Address, - _index: U256, - ) -> Result { - Ok(self.storage_value) + _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 block_hash(&mut self, _number: u64) -> Result { - Ok(B256::ZERO) + 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(), + can_evict_from_pool: true, + metrics: MorphPayloadBuilderMetrics::default(), } } + // ========================================================================= + // M-H09: Pre-execution queue_index validation & overflow protection tests + // ========================================================================= + #[test] - fn test_read_withdraw_trie_root_zero() { - let mut db = MockDb { - storage_value: U256::ZERO, + 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 root = read_withdraw_trie_root(&mut db).unwrap(); - assert_eq!(root, B256::ZERO); + 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_read_withdraw_trie_root_nonzero() { - let expected = B256::from([0xAB; 32]); - let mut db = MockDb { - storage_value: expected.into(), + 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 root = read_withdraw_trie_root(&mut db).unwrap(); - assert_eq!(root, expected); + 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_read_withdraw_trie_root_max_value() { - let mut db = MockDb { - storage_value: U256::MAX, + 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 root = read_withdraw_trie_root(&mut db).unwrap(); - assert_eq!(root, B256::from(U256::MAX)); + 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, + || true, + |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, 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)) + }; + + 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, + || true, + |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); + } + + #[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/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/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 7ebc2836..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 @@ -799,7 +833,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::*; @@ -840,7 +874,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()), )); @@ -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!( @@ -1377,7 +1413,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/Cargo.toml b/crates/proofs/Cargo.toml index 5ab9dc01..2f0b961c 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, features = ["std"] } +reth-evm = { workspace = true, features = ["std", "witness"] } reth-execution-errors.workspace = true reth-metrics.workspace = true reth-primitives-traits.workspace = true reth-provider.workspace = true -reth-revm = { workspace = true, features = ["std", "witness"] } reth-tasks.workspace = true reth-trie = { workspace = true, features = ["serde"] } reth-trie-common = { workspace = true, features = ["serde"] } diff --git a/crates/proofs/src/api.rs b/crates/proofs/src/api.rs index f988ec98..01b99e07 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 7c1608a5..8f7a7c8b 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, }, }, }; @@ -558,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, @@ -576,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; } @@ -603,50 +603,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 +721,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 +736,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 +1053,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 +1091,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 { @@ -1215,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 { @@ -1534,6 +1456,7 @@ mod tests { }; use reth_trie::{ BranchNodeCompact, HashedPostStateSorted, HashedStorage, Nibbles, StoredNibbles, + hashed_cursor::HashedCursor, updates::{StorageTrieUpdates, TrieUpdatesSorted}, }; use tempfile::TempDir; @@ -1541,7 +1464,7 @@ mod tests { use super::*; use crate::db::{ StorageTrieKey, - models::{AccountTrieHistory, StorageTrieHistory}, + models::{AccountTrieHistory, MaybeDeleted, StorageTrieHistory}, }; const B0: u64 = 0; @@ -3699,301 +3622,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" - ); - } - } - - /// Wiped-storage-with-new-slots case 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"); - - // 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"); - - 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 + 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); - // 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 live_slot = B256::from([0xB1; 32]); + let live_value_old = U256::from(333u64); + let live_value_new = U256::from(999u64); - 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") @@ -4001,10 +3692,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] @@ -4841,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/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 f02aeb16..0b2f627b 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 630d4802..0ad0b8a2 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/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/reader.rs b/crates/reference-index/src/reader.rs index b5093a2b..52099185 100644 --- a/crates/reference-index/src/reader.rs +++ b/crates/reference-index/src/reader.rs @@ -112,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 cfc83d8a..44684d78 100644 --- a/crates/reference-index/src/runtime.rs +++ b/crates/reference-index/src/runtime.rs @@ -266,9 +266,8 @@ 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 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.handle.set_phase(ReferenceIndexPhase::Live); @@ -287,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)?; @@ -295,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)?; @@ -527,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 + }; } } @@ -867,4 +914,148 @@ mod tests { assert_eq!(handle.db().unwrap().indexed_to().unwrap(), None); assert_eq!(handle.db().unwrap().indexed_block_hash(0).unwrap(), None); } + + #[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 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()); + + // 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!( + 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); + + // Next turn reconciles away A4 and indexes B4..=B5 cleanly. + runtime.synchronize_once(false).unwrap(); + assert_eq!(handle.phase(), ReferenceIndexPhase::Live); + assert_eq!(db.indexed_to().unwrap(), Some(5)); + assert_eq!( + db.indexed_block_hash(4).unwrap(), + base.canonical_hash(4).unwrap() + ); + assert_eq!( + db.indexed_block_hash(5).unwrap(), + base.canonical_hash(5).unwrap() + ); + assert_ne!(db.indexed_block_hash(4).unwrap(), Some(old_block4_hash)); + } + + #[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) + } + } + + #[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/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 735efc44..82710f5a 100644 --- a/crates/revm/Cargo.toml +++ b/crates/revm/Cargo.toml @@ -15,27 +15,18 @@ morph-primitives.workspace = true morph-chainspec.workspace = true reth-evm.workspace = true -reth-ethereum-primitives = { workspace = true, features = ["serde"] } -reth-storage-api = { workspace = true, optional = true } -reth-rpc-eth-types = { workspace = true, optional = true } +reth-evm-ethereum.workspace = true -revm.workspace = true +evm2 = { workspace = true, features = ["std"] } +evm2-macros.workspace = true -alloy-evm.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 29874fcd..c42be2fe 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>; +} -/// The Morph EVM context type. +/// An evm2 EVM configured with the Morph type family. +pub type MorphEvm<'a> = evm2::Evm<'a, MorphEvmTypes>; + +/// 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,254 +147,190 @@ 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.host().tx_env().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, +/// 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), + ) +} - #[inline] - #[expect(clippy::type_complexity)] - fn new_inner( - inner: Evm< - MorphContext, - I, - EthInstructions>, - MorphPrecompiles, - EthFrame, - >, - ) -> Self { +/// 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 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, + in_fee_frame: bool, +} + +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, + 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)) + /// Returns the wrapped inspector. + pub fn into_inner(self) -> I { + self.inner } - /// 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 const fn inner(&self) -> &I { + &self.inner } - /// Consumes self and returns the inner Inspector. - pub fn into_inspector(self) -> I { - self.inner.into_inspector() + /// Returns a mutable reference to the wrapped inspector. + pub const fn inner_mut(&mut self) -> &mut I { + &mut 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. +impl> Inspector for FeeFrameFilter { #[inline] - pub fn cached_token_fee_info(&self) -> Option { - self.cached_token_fee_info + fn inspector_config(&self) -> evm2::InspectorConfig { + if self.in_fee_frame { + evm2::InspectorConfig::without_steps() + } else { + self.inner.inspector_config() + } } - /// 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 initialize_interp(&mut self, interp: &mut Interpreter<'_, '_, MorphEvmTypes>) { + if !self.in_fee_frame { + self.inner.initialize_interp(interp); + } } -} -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 step(&mut self, interp: &mut Interpreter<'_, '_, MorphEvmTypes>) { + if !self.in_fee_frame { + self.inner.step(interp); + } } - fn all_mut( - &mut self, - ) -> ( - &mut Self::Context, - &mut Self::Instructions, - &mut Self::Precompiles, - &mut FrameStack, - ) { - self.inner.all_mut() + fn step_end(&mut self, interp: &mut Interpreter<'_, '_, MorphEvmTypes>) { + if !self.in_fee_frame { + self.inner.step_end(interp); + } } - fn frame_stack(&mut self) -> &mut FrameStack { - &mut self.inner.frame_stack + fn log(&mut self, log: &Log, host: &mut MorphEvm<'_>) { + if !self.in_fee_frame { + self.inner.log(log, host); + } } - fn frame_init( + fn call( &mut self, - frame_input: ::FrameInit, - ) -> Result< - ItemOrResult<&mut Self::Frame, ::FrameResult>, - ContextError, - > { - self.inner.frame_init(frame_input) + 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 frame_run(&mut self) -> Result, ContextError> { - self.inner.frame_run() + fn call_end( + &mut self, + interp: &mut Interpreter<'_, '_, MorphEvmTypes>, + message: &Message, + result: &mut MessageResult, + ) { + 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_return_result( + fn create( &mut self, - result: ::FrameResult, - ) -> Result::FrameResult>, ContextError> { - self.inner.frame_return_result(result) + interp: &mut Interpreter<'_, '_, MorphEvmTypes>, + message: &mut Message, + ) -> Option> { + if self.in_fee_frame { + return None; + } + self.inner.create(interp, message) } -} -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, + fn create_end( + &mut self, + 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); + } } } @@ -322,7 +343,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); @@ -332,13 +353,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)" ); } @@ -347,7 +368,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); @@ -366,12 +387,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] @@ -382,21 +403,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" ); } @@ -417,23 +438,78 @@ 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 + ); + } + } + + #[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/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 4a701649..8cfe89b9 100644 --- a/crates/revm/src/handler.rs +++ b/crates/revm/src/handler.rs @@ -1,27 +1,46 @@ -//! Morph EVM Handler implementation. - -use alloy_primitives::{Address, Bytes, U256}; -use morph_primitives::transaction::morph_transaction::MORPH_TX_VERSION_2; -use revm::{ - 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::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::{DbResult, 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, @@ -29,1034 +48,926 @@ 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>; + +/// 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() } } -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), - } +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), + ); } - - #[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)) + 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 { + /// Fee token identifier in `L2TokenRegistry`, used to reload the live `(token_address, + /// balance_slot)` routing target during post-execution reimbursement (`[MR-03]`). + token_id: u16, + /// 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)); - } + /// 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 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, - )?; +/// 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, + l1_data_fee: U256, + token_fee: Option, +} - let regular_gas_refund = evm - .ctx_ref() - .cfg() - .gas_params() - .tx_eip7702_auth_refund_regular() - .saturating_mul(refunded_accounts); +/// 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 chain_id = host.version().chain_id; + *host.tx_env_mut() = TxEnvExt { + origin: caller, + gas_price, + chain_id: U256::from(chain_id), + ..TxEnvExt::default() + }; - Ok(Some(regular_gas_refund)) + 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, + l1_data_fee: U256::ZERO, + token_fee: None, + }); } - #[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; + 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)?; - let (_, tx, _, journal, _, _) = evm.ctx().all_mut(); + 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)? + }; + warm_transaction_accounts(host, tx, caller)?; + + Ok(PreparedMorphTx { + caller, + gas_price, + intrinsic, + floor_gas, + sender_nonce: charged.sender_nonce, + l1_data_fee: charged.l1_data_fee, + token_fee: charged.token_fee, + }) +} - if tx.is_l1_msg() { - let mut caller = journal.load_account_with_code_mut(tx.caller())?.data; +/// 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, + 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, frame, &mut tx_gas, execution_gas_limit, reservoir)?; - // CREATE nonce is bumped later in make_create_frame - if tx.kind().is_call() { - caller.bump_nonce(); - } - 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); + } - // 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); + 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, 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); } - - // Standard ETH-based fee handling - self.validate_and_deduct_eth_fee(evm) + 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(); + output.ext = MorphTxResultExt { + l1_data_fee, + token_fee_info: token_fee.map(|fee| fee.info), + }; + Ok(output) +} - // L1 message gas is prepaid on L1, no reimbursement needed. - if tx.is_l1_msg() { - return 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, + }, + ) +} - // 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(()); - } +/// 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 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(()); + match tx.tx_type { + LEGACY_TX_TYPE | EIP2930_TX_TYPE => validate_gas_price(version, max_fee, basefee)?, + EIP1559_TX_TYPE | MORPH_TX_TYPE_ID => { + validate_priority_fee(version, max_fee, priority_fee)?; + validate_gas_price(version, effective_gas_price, basefee)?; } - 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(()); + 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); + } } + _ => {} + } - let beneficiary = block.beneficiary(); + 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)?; - let basefee = block.basefee() as u128; - let effective_gas_price = tx.effective_gas_price(basefee); + if tx.is_morph_tx() { + validate_morph_tx_authorization_list(host, tx)?; + } - let gas_used = exec_result.gas().used(); + Ok(()) +} - let execution_fee = U256::from(effective_gas_price).saturating_mul(U256::from(gas_used)); +/// 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(()); + } - // reward beneficiary - journal - .load_account_mut(beneficiary)? - .incr_balance(execution_fee.saturating_add(l1_data_fee)); + // 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()); + } - Ok(()) + if tx.authorization_list.is_empty() { + return Ok(()); } - #[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(()); - } + if !host.spec_id().enables(SpecId::PRAGUE) { + return Err(MorphInvalidTransaction::Eip7702NotSupported.into()); + } + if tx.kind.is_create() { + return Err(MorphInvalidTransaction::AuthorizationListCreate.into()); + } - // 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(), - )?; - } + Ok(()) +} - // 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)?; - } +/// 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, + ) +} - 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()), - }); +/// 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)?; - // 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); + if eip3607 && !sender.is_empty_code_hash() { + let code = sender.load_code()?; + if !code.is_empty() && !code.is_eip7702() { + return Err(HandlerError::RejectCallerWithCode); } - - // 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) } - - 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)) + if nonce_check && sender.nonce() != tx_nonce { + return Err(HandlerError::InvalidNonce { + expected: sender.nonce(), + got: tx_nonce, + }); } + 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), - } - } +/// 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) } -// 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()); - } +/// 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(()) +} - Ok(()) +/// 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) +} - /// 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)?; +/// The fee a transaction was charged during [`prepare`]. +struct ChargedFee { + l1_data_fee: U256, + token_fee: Option, + sender_nonce: u64, +} - let rlp_bytes = evm - .ctx_ref() - .tx() - .rlp_bytes - .as_ref() - .map(|b| b.as_ref()) - .unwrap_or_default(); +/// Whether the transaction is an RPC simulation of an unsigned call that carries no encoding. +/// +/// Upstream `eth_simulateV1` executes each call in an empty `WithEncoded` envelope and treats +/// that as carrying no L1 cost on an L2 (`simulate::execute_transactions`). Morph's post-Curie +/// formula still charges a commit fee for zero bytes, so such calls are priced at zero L1 fee +/// here. `MorphBlockExecutor` gives `validation: true` simulations a placeholder-signature +/// encoding, so only `validation: false` simulations reach the handler unencoded. +/// +/// EIP-3607 is never disabled during consensus execution, where every transaction carries its +/// signed encoding, so a missing encoding there is still priced by the formula instead of +/// silently becoming free. +#[inline] +fn is_unencoded_rpc_simulation(host: &MorphEvm<'_>, tx: &MorphTxEnv) -> bool { + !host.feature(EvmFeatures::EIP3607) + && tx.rlp_bytes.as_ref().is_none_or(|bytes| bytes.is_empty()) +} - let l1_data_fee = l1_block_info.calculate_tx_l1_cost(rlp_bytes, hardfork); - evm.cached_l1_data_fee = l1_data_fee; +/// 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) +} - let (block, tx, cfg, journal, _, _) = evm.ctx().all_mut(); +/// 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( + |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(); + Ok(l1_block_info.calculate_tx_l1_cost(rlp_bytes, hardfork)) +} - let mut caller = journal.load_account_with_code_mut(tx.caller())?.data; +/// 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 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 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, + }) +} - pre_execution::validate_account_nonce_and_code( - &caller.account().info, - tx.nonce(), - cfg.is_eip3607_disabled(), - cfg.is_nonce_check_disabled(), - )?; +/// 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, + gas_price: U256, + token_id: u16, +) -> HandlerResult { + // Token ID 0 means ETH — routed through deduct_eth_fee instead. + if token_id == 0 { + return Err(MorphInvalidTransaction::TokenIdZeroNotSupported.into()); + } - let new_balance_after_l2_fee = - calculate_caller_fee_with_l1_cost(*caller.balance(), tx, block, cfg, l1_data_fee)?; + // Validate account nonce and code (EIP-3607) BEFORE any state mutations. + validate_sender(host, caller, tx.nonce)?; - caller.set_balance(new_balance_after_l2_fee); + let fee_charge = host.feature(EvmFeatures::FEE_CHARGE); - // CREATE nonce is bumped later in make_create_frame - if tx.kind().is_call() { - caller.bump_nonce(); + // 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| storage_slot_untracked_with_account(state, &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, + }); } - /// 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), - ); - - if reimburse_eth.is_zero() { - return Ok(()); - } + let token_fee_info = load_token_fee_info(host, token_registry_entry, caller)?; - // 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(), - } - })?; + let beneficiary = host.block().beneficiary; + let fee_limit_from_tx = tx.fee_limit.unwrap_or_default(); - // 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) - }; + // Get RLP-encoded transaction bytes for L1 fee calculation + let l1_data_fee = l1_data_fee(host, tx)?; - // 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(()); - } + // 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(gas_price); - // 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:711). - 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 { - // The refund's Transfer logs stay in the journal, after the main frame's, which is - // where go-ethereum's `StateDB.logs` records them too. - transfer_erc20_with_evm( - evm, - beneficiary, - caller, - token_fee_info.token_address, - token_amount_required, - None, - ) - .map(|_| ()) - }; + // Total fee in ETH + let total_eth_fee = l2_gas_fee.saturating_add(l1_data_fee); - 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" - ); - } + // 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); - Ok(()) - } + let fee_limit = token_fee_info.effective_fee_limit(fee_limit_from_tx); - /// 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()); + // 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()); + } - { - 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 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, + caller, + beneficiary, + token_fee_info.token_address, + token_amount_required, + Some(token_fee_info.balance), + )?; + } - 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()); - } - } - } + // 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()); + + let sender_nonce = bump_sender_nonce(host, caller)?; + + Ok(ChargedFee { + l1_data_fee, + token_fee: Some(AppliedTokenFee { + token_id, + info: token_fee_info, + rounding_credit, + refund_counter, + }), + sender_nonce, + }) +} - 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(()); +/// 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); + } +} - let hardfork = *evm.ctx_ref().cfg().spec(); - - let token_fee_info = load_token_fee_info(evm, token_registry_entry, caller_addr)?; - - 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); - - // 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); - - // 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)); - - // Total fee in ETH - let total_eth_fee = l2_gas_fee.saturating_add(l1_data_fee); - - // 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); +/// Reimburse unused gas fees in ERC20 tokens. +/// +/// 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, + gas_price: U256, + unused_gas: u64, + fee: AppliedTokenFee, +) -> HandlerResult<()> { + let beneficiary = host.block().beneficiary; + let hardfork = host.config_spec_id(); + let AppliedTokenFee { + token_id, + info, + rounding_credit, + .. + } = fee; + + let reimburse_eth = gas_price.saturating_mul(U256::from(unused_gas)); + if reimburse_eth.is_zero() { + return Ok(()); + } - let fee_limit = token_fee_info.effective_fee_limit(fee_limit_from_tx); + // 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) + }; - // 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()); - } + // 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(()); + } - 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), - )?; - } + // 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| storage_slot_untracked_with_account(state, &address, &slot), + token_id, + )? + else { + return Ok(()); + }; - 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. - // - // Fee deduction ran real EVM frames, so their state writes must survive while the - // frames' 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). Those are the only two things done here. - // - // `mark_cold` below only has to *drop* the warmth these frames 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. - // - // `mark_cold` leaves each slot's transaction id alone, and revm-state re-baselines - // the EIP-2200 `original_value` only when that id changes (bluealloy/revm#3746), so - // the main frame still prices its SSTOREs against the value committed before this - // transaction, as go-ethereum's `GetCommittedState` does. Re-baselining the slot - // the deduction just cleared would turn the main frame's restoring SSTORE into a - // create and drop the `SubRefund` that cancels the deduction's `+4800`: measured on - // `main_restores_cleared_slot`, 23_291 gas becomes 38_391. Nothing here depends on - // the journal's own id either, so batched execution (`ExecuteEvm::transact_many`) - // prices the same as one `transact` per transaction. - // - // The deduction's Transfer logs and undo history stay in the journal. The main - // frame's checkpoint is taken after this point, so a revert or halt there truncates - // only its own logs, and `post_execution::output` returns - // `[deduction] + [main frame, on success] + [refund]` for every outcome: the order - // go-ethereum's `StateDB.logs` produces, since those logs sit outside its - // snapshot/revert mechanism. The undo history lets `catch_error` still roll the - // deduction back. - let journal = evm.ctx_mut().journal_mut(); - journal.transient_storage.clear(); - for account in journal.state.values_mut() { - account.mark_cold(); - account - .storage - .values_mut() - .for_each(|slot| slot.mark_cold()); - } - } + // 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) = live_balance_slot { + transfer_erc20_with_slot( + host, + beneficiary, + caller, + live_token_address, + token_amount_required, + balance_slot, + ) + } else { + transfer_erc20_with_evm( + host, + beneficiary, + caller, + live_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 = %live_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<'_>, 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.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(&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<'_>, token: Address, account: Address, -) -> Result> -where - DB: alloy_evm::Database, -{ +) -> HandlerResult { let result = evm_call( - evm, + host, 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<'_>, 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| storage_slot_untracked_with_account(state, &address, &slot), + entry.token_address(), + caller, + slot, + )? + } + None => evm_call_balance_of(host, entry.token_address(), caller)?, }; Ok(entry.into_fee_info(caller, balance)) } @@ -1066,32 +977,25 @@ 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<'_>, 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, token_address, from)?, }; // Geth checks affordability before executing the token contract. @@ -1104,17 +1008,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, 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()); } @@ -1123,7 +1021,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(), @@ -1132,7 +1030,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, token_address, from)?; // Verify sender balance decreased by exactly the transfer amount. // Matches go-ethereum's transferAltTokenByEVM which always checks this, @@ -1147,14 +1045,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); @@ -1168,67 +1066,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) @@ -1237,188 +1122,163 @@ 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::token_fee::{ + L2_TOKEN_REGISTRY_ADDRESS, compute_mapping_slot, + tests::{UnreadableTokenDb, is_token_read_failure}, + }; use crate::{ - MorphBlockEnv, - token_fee::{L2_TOKEN_REGISTRY_ADDRESS, compute_mapping_slot}, + MorphAuthorization, MorphBlockEnv, MorphEvmEnv, evm::morph_evm, evm::morph_evm_env, }; - use alloy_primitives::{B256, Bytes, TxKind, address, keccak256}; - use morph_chainspec::hardfork::MorphHardfork; - use morph_primitives::MORPH_TX_TYPE_ID; - use revm::{ - ExecuteEvm, - context::{BlockEnv, TxEnv}, - context_interface::{cfg::gas_params::GasId, result::InvalidTransaction}, - database::{CacheDB, EmptyDB}, - inspector::NoOpInspector, - state::{AccountInfo, Bytecode}, + use alloy_consensus::transaction::Recovered; + use alloy_eips::eip7702::{ + Authorization, RecoveredAuthority, RecoveredAuthorization, SignedAuthorization, }; + use alloy_primitives::{Log, TxKind, address, b256}; + use evm2::{ + Inspector, + 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:?}" + /// 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) { + 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); + set_tx_env(&mut evm, caller); + reimburse_token_fee( + &mut evm, 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 { + token_id: 1, + 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); + 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); + inner.insert_account_storage( + &crate::token_fee::L2_TOKEN_REGISTRY_ADDRESS, + &base, + &U256::from_be_bytes(REFUND_PROBE_TOKEN.into_word().0), ); + 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] @@ -1426,28 +1286,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( + set_tx_env(&mut evm, from); + let error = transfer_erc20_with_evm( &mut evm, 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 { @@ -1472,34 +1332,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) } } @@ -1510,25 +1370,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(); + 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(); + set_tx_env(&mut evm, caller); load_token_fee_info(&mut evm, entry, caller) .unwrap() .balance @@ -1540,13 +1392,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() }, @@ -1563,125 +1415,163 @@ 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, - ) { + /// 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)); } fn insert_test_fee_token_config( - db: &mut CacheDB, + db: &mut InMemoryDB, token_id: u16, token: Address, is_active: bool, 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); 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()); + set_tx_env(&mut evm, caller); + deduct_token_fee( + &mut evm, + &token_fee_simulation_tx(token_id), + caller, + U256::ZERO, + 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, + 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() }; - 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), + + assert!(matches!( + validate_env(&evm, &tx).unwrap_err(), + HandlerError::FeeCapLessThanBaseFee { .. } + )); + } + + #[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() }; - - let err = - as Handler>::validate_env(&MorphEvmHandler::default(), &mut evm) - .unwrap_err(); - + 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!( - err, - EVMError::Transaction(MorphInvalidTransaction::EthInvalidTransaction( - InvalidTransaction::GasPriceLessThanBasefee - )) + validate_env(&evm, &inverted_tip_tx).unwrap_err(), + HandlerError::PriorityFeeGreaterThanMaxFee )); } @@ -1689,13 +1579,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() -> MorphAuthorization { + let signed: SignedAuthorization = Authorization { chain_id: U256::from(1), address: Address::with_last_byte(0x42), nonce: 0, @@ -1704,7 +1589,8 @@ mod tests { U256::from(1), U256::from(2), true, - )) + )); + MorphAuthorization::Signed(signed) } fn recovered_authorization( @@ -1712,8 +1598,8 @@ mod tests { delegate: Address, chain_id: u64, auth_nonce: u64, - ) -> Either { - Either::Right(RecoveredAuthorization::new_unchecked( + ) -> MorphAuthorization { + MorphAuthorization::Recovered(RecoveredAuthorization::new_unchecked( Authorization { chain_id: U256::from(chain_id), address: delegate, @@ -1726,557 +1612,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![MorphAuthorization::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] @@ -2285,39 +2025,18 @@ 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( + 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()); + set_tx_env(&mut evm, from); + + let err = transfer_erc20_with_evm( + &mut evm, 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 err = transfer_erc20_with_evm( - &mut evm, - from, - to, + to, token, U256::from(4), Some(original_balance), @@ -2325,17 +2044,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] @@ -2343,45 +2058,23 @@ 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( - 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, 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, from, to, token, 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] @@ -2393,36 +2086,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 evm = MorphEvm::new( - MorphContext::new(db, MorphHardfork::default()), - NoOpInspector, - ); - evm.block = MorphBlockEnv { - inner: BlockEnv::default(), - }; + 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()); - // 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] @@ -2430,111 +2110,68 @@ 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()); + set_tx_env(&mut evm, account); 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_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; @@ -2543,28 +2180,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" ); @@ -2577,14 +2202,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 { @@ -2592,17 +2211,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; @@ -2669,92 +2286,58 @@ mod tests { U256::from_be_bytes(account.into_word().0) } - fn fee_refund_evm(payer_token_balance: U256) -> MorphEvm, NoOpInspector> { - fee_refund_evm_with_token_code(fee_refund_slotless_erc20_code(), payer_token_balance) - } - - fn fee_refund_evm_with_token_code( - code: Bytes, - payer_token_balance: U256, - ) -> MorphEvm, NoOpInspector> { - 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" @@ -2771,178 +2354,14 @@ mod tests { ); ( - gas_used, - gas_refunded, - fee_refund_present_value(&evm, FEE_REFUND_CALLER), - ) - } - - /// `fee_refund_slotless_erc20_code` whose `transfer` also emits - /// `Transfer(msg.sender, to, amount)`, so fee frames leave logs behind. - fn fee_refund_logging_erc20_code() -> Bytes { - let mut code = vec![ - 0x36, // CALLDATASIZE - 0x60, 0x44, // PUSH1 68 - 0x14, // EQ - 0x60, 0x13, // PUSH1 19 (transfer JUMPDEST) - 0x57, // JUMPI - // balanceOf(address) - 0x60, 0x04, // PUSH1 4 - 0x35, // CALLDATALOAD - 0x54, // SLOAD - 0x60, 0x00, // PUSH1 0 - 0x52, // MSTORE - 0x60, 0x20, // PUSH1 32 - 0x60, 0x00, // PUSH1 0 - 0xf3, // RETURN - // transfer(address,uint256) - 0x5b, // JUMPDEST (pc 19) - 0x60, 0x24, // PUSH1 36 - 0x35, // CALLDATALOAD -> amount - 0x80, // DUP1 -> amount amount - 0x33, // CALLER -> caller amount amount - 0x54, // SLOAD -> bal_from amount amount - 0x03, // SUB -> bal_from-amount amount - 0x33, // CALLER -> caller new_from amount - 0x55, // SSTORE -> amount - 0x60, 0x04, // PUSH1 4 - 0x35, // CALLDATALOAD -> to amount - 0x80, // DUP1 -> to to amount - 0x54, // SLOAD -> bal_to to amount - 0x82, // DUP3 -> amount bal_to to amount - 0x01, // ADD -> new_to to amount - 0x90, // SWAP1 -> to new_to amount - 0x55, // SSTORE -> amount - 0x60, 0x00, // PUSH1 0 - 0x52, // MSTORE -> memory[0..32] = amount - 0x60, 0x04, // PUSH1 4 - 0x35, // CALLDATALOAD -> to - 0x33, // CALLER -> caller to - 0x7f, // PUSH32 Transfer topic - ]; - code.extend_from_slice(keccak256("Transfer(address,address,uint256)").as_slice()); - code.extend_from_slice(&[ - 0x60, 0x20, // PUSH1 32 - 0x60, 0x00, // PUSH1 0 - 0xa3, // LOG3 -> Transfer(caller, to, amount) - 0x60, 0x01, // PUSH1 1 - 0x60, 0x00, // PUSH1 0 - 0x52, // MSTORE - 0x60, 0x20, // PUSH1 32 - 0x60, 0x00, // PUSH1 0 - 0xf3, // RETURN - ]); - Bytes::from(code) - } - - fn fee_log_tx(nonce: u64, to: Address, data: Bytes) -> MorphTxEnv { - 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(to), - data, - nonce, - ..Default::default() - }, - fee_token_id: Some(FEE_REFUND_TOKEN_ID), - ..Default::default() - } - } - - /// Asserts `log` is the logging token's `Transfer(from, to, ..)`. - fn assert_fee_transfer(log: &alloy_primitives::Log, from: Address, to: Address) { - assert_eq!(log.address, FEE_REFUND_TOKEN); - assert_eq!( - log.topics(), - &[ - keccak256("Transfer(address,address,uint256)"), - from.into_word(), - to.into_word() - ] - ); - } - - /// go-ethereum keeps the fee Transfers in `StateDB.logs`, outside the snapshot the main - /// frame reverts, so they reach the receipt even when the transaction fails. revm returns - /// the journal's logs for every outcome, and the main frame's checkpoint is taken after the - /// deduction, so the same two logs come back on a revert, deduction first. - #[test] - fn fee_transfer_logs_survive_a_reverting_main_frame() { - const REVERTER: Address = address!("5000000000000000000000000000000000000005"); - let mut evm = fee_refund_evm_with_token_code( - fee_refund_logging_erc20_code(), - U256::from(10).pow(U256::from(18)), - ); - let code = Bytes::from_static(&[0x60, 0x00, 0x60, 0x00, 0xfd]); // REVERT(0, 0) - evm.ctx_mut().db_mut().insert_account_info( - REVERTER, - AccountInfo { - code_hash: keccak256(code.as_ref()), - code: Some(Bytecode::new_raw(code)), - ..Default::default() - }, - ); - - let result = evm - .transact_one(fee_log_tx(0, REVERTER, Bytes::new())) - .expect("a reverting main frame is still a valid transaction"); - assert!( - matches!(result, ExecutionResult::Revert { .. }), - "{result:?}" - ); - let logs = result.into_logs(); - assert_eq!(logs.len(), 2, "deduction and refund Transfers: {logs:?}"); - assert_fee_transfer(&logs[0], FEE_REFUND_CALLER, FEE_REFUND_BENEFICIARY); - assert_fee_transfer(&logs[1], FEE_REFUND_BENEFICIARY, FEE_REFUND_CALLER); - } - - /// Batched execution (`transact_many`, no `finalize` between transactions) must price and - /// log exactly like one `transact` per transaction. The second transaction pays in the - /// token and then moves it in its main frame, touching the balance slot the deduction just - /// wrote: were the slot's EIP-2200 original value re-baselined between the two, that - /// SSTORE would be charged as a reset (2900) instead of a dirty write (100). - #[test] - fn batched_transactions_match_individual_execution() { - let balance = U256::from(10).pow(U256::from(18)); - let txs = [ - fee_log_tx(0, FEE_REFUND_TARGET, Bytes::new()), - fee_log_tx( - 1, + result.tx_gas_used(), + result.refunded, + storage_of( + &mut evm, FEE_REFUND_TOKEN, - build_transfer_calldata(FEE_REFUND_TARGET, U256::from(1)), + fee_refund_balance_slot(FEE_REFUND_CALLER), ), - ]; - - let mut individual = - fee_refund_evm_with_token_code(fee_refund_logging_erc20_code(), balance); - let individual_results: Vec<_> = txs - .iter() - .map(|tx| { - revm::ExecuteCommitEvm::transact_commit(&mut individual, tx.clone()) - .expect("token-fee MorphTx must execute") - }) - .collect(); - - let mut batched = fee_refund_evm_with_token_code(fee_refund_logging_erc20_code(), balance); - let batched_results = batched - .transact_many(txs.into_iter()) - .expect("token-fee MorphTx must execute"); - - for (individual, batched) in individual_results.iter().zip(&batched_results) { - assert!(individual.is_success(), "{individual:?}"); - assert_eq!(individual.tx_gas_used(), batched.tx_gas_used()); - assert_eq!(individual.logs(), batched.logs()); - } - - // The second transaction's logs: deduction, the main frame's own transfer, refund. - let logs = individual_results[1].logs(); - assert_eq!(logs.len(), 3, "{logs:?}"); - assert_fee_transfer(&logs[0], FEE_REFUND_CALLER, FEE_REFUND_BENEFICIARY); - assert_fee_transfer(&logs[1], FEE_REFUND_CALLER, FEE_REFUND_TARGET); - assert_fee_transfer(&logs[2], FEE_REFUND_BENEFICIARY, FEE_REFUND_CALLER); + ) } #[test] @@ -2958,59 +2377,98 @@ mod tests { #[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)), - ..Default::default() - }, - ); + 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); + 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 + /// 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 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() - }, - ); + 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: (), + }; + prepare(&mut request).unwrap(); + 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); } } + /// 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 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)), + 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, FEE_REFUND_CALLER, @@ -3020,47 +2478,42 @@ mod tests { Some(U256::ZERO), ) .unwrap(); - assert!(evm.ctx_ref().journal().state.is_empty()); + 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 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( + 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, - AccountInfo { - balance: U256::from(FEE_REFUND_GAS_LIMIT as u128 * FEE_REFUND_GAS_PRICE), - ..Default::default() - }, + (FEE_REFUND_GAS_LIMIT as u128 * FEE_REFUND_GAS_PRICE) as u64, ); 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() + tx_type: if fee_token_id.is_some() { + MORPH_TX_TYPE_ID + } else { + 0 }, fee_token_id, - ..Default::default() + ..fee_refund_tx() }; - let result = evm.transact_one(tx).expect("probe must execute"); - assert!(result.is_success(), "expected success, got {result:?}"); - result.output().cloned().unwrap_or_default() + 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) @@ -3085,7 +2538,7 @@ mod tests { 0x5f, // PUSH0 (offset) 0xf3, // RETURN ]); - Bytes::from(code) + code } /// Same ERC20, except `balanceOf` returns its result through the identity @@ -3120,71 +2573,138 @@ mod tests { Bytes::from(code) } - /// 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. + /// 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 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) + 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. + /// 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 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 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, + ]); - // 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 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, + ]), ); - } - /// 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), + let env = test_env( + MorphHardfork::Celadon, + MorphBlockEnv { + basefee: U256::ZERO, + gas_limit: U256::from(30_000_000), ..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), + }, + ); + + 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] + 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. 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. + /// 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. @@ -3205,6 +2725,706 @@ mod tests { ); } } + + /// `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 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 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() + }, + ); + 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 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 { .. }) + )); + } + + /// `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]) + } + + #[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 { + 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 = transact(&mut evm, tx, caller).unwrap(); + + 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" + ); + } + + /// An L1 message prepaid on L1 must run even if its gas limit does not cover intrinsic gas. + #[test] + 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); + } + + #[test] + 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() + }; + + 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()); + } + + /// `; STOP`, for an opcode that takes no arguments. + fn opcode_probe(opcode: u8) -> Bytes { + Bytes::from(vec![opcode, 0x00]) + } + + /// 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 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 + ] { + assert_eq!( + 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") + ); + } + + /// 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. @@ -3215,17 +3435,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::{ - ExecuteEvm, - 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"); @@ -3242,13 +3458,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 { @@ -3260,6 +3473,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 // ------------------------------------------------------------------------- @@ -3267,14 +3489,18 @@ 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) { + // 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); 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)); @@ -3290,21 +3516,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 @@ -3312,15 +3533,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() } @@ -3330,15 +3547,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(), ) } @@ -3352,18 +3570,21 @@ 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 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, 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 // 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}" ); @@ -3377,41 +3598,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]; @@ -3469,57 +3655,56 @@ 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()); + 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); - 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 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() }; - 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, + CALLER, + U256::from(1), + gas_left, + AppliedTokenFee { + token_id: FEE_TOKEN_ID, + 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) } @@ -3569,22 +3754,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.ctx.journal_mut().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!( @@ -3593,4 +3772,713 @@ 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 { + token_id: FEE_TOKEN_ID, + 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); + } + + /// 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()); + } + + #[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(); + // 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, + &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. + 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( + &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 + ); + } + + /// 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/l1block.rs b/crates/revm/src/l1block.rs index 99481bd7..3074c61e 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 5e420dda..ac64fed2 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, TokenRegistryEntry, compute_mapping_slot, + L2_TOKEN_REGISTRY_ADDRESS, TokenFeeInfo, TokenRegistryEntry, compute_mapping_slot, compute_mapping_slot_for_address, encode_balance_of_calldata, }; -pub use tx::{MorphTxEnv, MorphTxExt}; +pub use tx::{MorphAuthorization, MorphTxEnv, MorphTxExt, encode_simulated_tx_for_l1_fee}; diff --git a/crates/revm/src/precompiles.rs b/crates/revm/src/precompiles.rs index ba170f2a..d002f9a4 100644 --- a/crates/revm/src/precompiles.rs +++ b/crates/revm/src/precompiles.rs @@ -9,14 +9,14 @@ //! Berlin (base) //! └── Bernoulli/Curie = Berlin with ripemd160/blake2f replaced by disabled stubs //! └── Morph203/Viridian = Bernoulli with ripemd160/blake2f re-enabled (working) -//! └── Emerald/Jade = Morph203 + Osaka precompiles +//! └── Emerald = Morph203 + Osaka precompiles //! ``` //! //! | Hardfork | Base | Changes | Notes | //! |------------------|-----------|----------------------------------------------------------|-------------------------------| //! | Bernoulli/Curie | Berlin | ripemd160/blake2f as disabled stubs; modexp 32B limit | - | //! | Morph203/Viridian| Bernoulli | blake2f/ripemd160 re-enabled; BN256 pairing 4-pair limit | - | -//! | Emerald/Jade | Morph203 | BLS12-381, P256verify; modexp EIP-7823/7883 upgrade | NO KZG (0x0a) | +//! | Emerald | Morph203 | BLS12-381, P256verify; modexp EIP-7823/7883 upgrade | NO KZG (0x0a) | //! //! ## Why Disabled Stubs? //! @@ -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 `PrecompileHalt` status 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. @@ -196,26 +179,23 @@ fn modexp_len_exceeds_32(data: &[u8], offset: usize) -> bool { /// Without this limit, morph-reth would accept arbitrarily large modexp inputs /// that go-ethereum rejects, causing a consensus split. /// -/// Ref: go-ethereum `bigModExp.Run` in `core/vm/contracts.go` -fn modexp_with_32byte_limit(input: &[u8], gas_limit: u64, reservoir: u64) -> PrecompileResult { +/// Ref: +fn modexp_with_32byte_limit( + evm: &mut MorphEvm<'_>, + message: &Message, + gas: &mut GasTracker, +) -> PrecompileResult { + 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) || 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. @@ -226,23 +206,18 @@ fn modexp_with_32byte_limit(input: &[u8], gas_limit: u64, reservoir: u64) -> Pre /// accounting differs (the underlying computation is the same, but block gas /// limits and metering become inconsistent). /// -/// Ref: go-ethereum `bn256PairingIstanbul.Run` in `core/vm/contracts.go` +/// 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 = evm.message_input(message); 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. @@ -251,31 +226,31 @@ fn bn256_pairing_with_4pair_limit( /// All 9 Berlin addresses are present (so they get warmed via EIP-2929), but 0x03/0x09 /// consume all forwarded gas and return failure when called. /// -/// Matches: go-ethereum `PrecompiledContractsBernoulli` in `core/vm/contracts.go` -pub fn bernoulli() -> &'static Precompiles { - static INSTANCE: OnceLock = OnceLock::new(); +/// Matches: +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, )]); @@ -328,39 +303,28 @@ pub fn morph203() -> &'static Precompiles { /// - Adds P256verify (0x100) from RIP-7212 /// - Does **NOT** include KZG Point Evaluation (0x0a) — go-ethereum omits it /// -/// Ref: go-ethereum `PrecompiledContractsEmerald` in `core/vm/contracts.go` -pub fn emerald() -> &'static Precompiles { - static INSTANCE: OnceLock = OnceLock::new(); +/// Ref: +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 43b17022..6a8e2360 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::{MorphEvm, MorphEvmEnv, morph_evm}, +}; /// L2 Token Registry contract address on Morph L2. /// Reference: @@ -55,36 +51,94 @@ pub struct TokenFeeInfo { } /// Fee-token registry metadata without any caller-specific balance state. -#[derive(Clone, Copy, Debug)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct TokenRegistryEntry { - token_address: Address, - is_active: bool, - decimals: u8, - price_ratio: U256, - scale: U256, - balance_slot: Option, + /// 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 fn load(db: &mut DB, token_id: u16) -> Result, DB::Error> { - read_registry_entry(db, token_id) + 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 fn load_with( + read: impl FnMut(Address, U256) -> Result, + token_id: u16, + ) -> Result, E> { + 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(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)); } @@ -94,13 +148,43 @@ 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 fn load_for_caller( self, db: &mut DB, caller: Address, env: &MorphEvmEnv, - ) -> Result> { + ) -> Result { let balance = read_token_balance_with_fallback( db, self.token_address, @@ -111,20 +195,26 @@ 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 }; 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, @@ -151,17 +241,20 @@ 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, caller: Address, env: &MorphEvmEnv, - ) -> Result, EVMError> { - let entry = match TokenRegistryEntry::load(db, token_id)? { - Some(e) => e, + ) -> Result, HandlerError> { + let entry = match TokenRegistryEntry::load(db, token_id).map_err(database_error::)? { + Some(e) => e.ensure_usable(token_id)?, None => return Ok(None), }; @@ -174,7 +267,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. @@ -183,7 +276,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, @@ -196,6 +289,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. @@ -261,10 +371,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()); @@ -276,13 +386,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 { @@ -290,16 +400,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, @@ -340,13 +450,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. @@ -359,40 +475,49 @@ 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; + // 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 chain_id = evm.version().chain_id; + *evm.tx_env_mut() = TxEnvExt { + origin: account, + chain_id: U256::from(chain_id), + ..TxEnvExt::default() + }; crate::handler::evm_call_balance_of(&mut evm, 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. @@ -411,10 +536,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. @@ -429,52 +558,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 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 block_hash(&mut self, number: u64) -> Result { - Ok(self.inner.block_hash(number).unwrap()) + 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; @@ -494,20 +647,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 } @@ -519,19 +666,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(); @@ -544,13 +690,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(); @@ -562,12 +705,144 @@ pub(crate) mod tests { inner: call_mode_token_state(token, 10_000_000), token, }; + let error = TokenFeeInfo::load_for_caller(&mut unreadable, 1, caller, &env).unwrap_err(); + 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!( - TokenFeeInfo::load_for_caller(&mut unreadable, 1, caller, &env).unwrap_err(), - EVMError::Database(TokenReadFailure) + 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/revm/src/tx.rs b/crates/revm/src/tx.rs index f5541be0..246efa4c 100644 --- a/crates/revm/src/tx.rs +++ b/crates/revm/src/tx.rs @@ -1,41 +1,169 @@ //! 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, Signed, 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::{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}, }; -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}; + +/// 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; + +/// 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 { + /// 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(), + } + } -/// Re-export Either for authorization list -use alloy_consensus::transaction::Either; + 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. /// -/// 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 +176,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 +207,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 +218,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 +272,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 +297,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 +328,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 +361,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(), + MorphAuthorization::Signed(signed) => signed.clone(), // Recovered authorizations no longer carry their original // signature, so reuse the fee-sizing placeholder. - Either::Right(recovered) => { + MorphAuthorization::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( + MorphAuthorization::Recovered(RecoveredAuthorization::new_unchecked( auth.inner().clone(), - authority, + LazyAuthorization::Signed(auth).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 } } -/// MorphTx fields extracted from the typed envelope. -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,47 +591,43 @@ 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] 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() - } -} - -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 + self.is_morph_tx() && self.reference.is_some() } } #[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 +637,87 @@ 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 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!(tx.is_morph_tx()); + assert!(!morph_eth_fee.uses_token_fee()); + assert!(morph_eth_fee.has_reference()); - let regular_tx = TxEnv::default(); - assert!(!regular_tx.is_morph_tx()); + 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 test_deref() { + fn typed_2718_reports_the_type_byte() { let tx = MorphTxEnv { - inner: TxEnv { - gas_limit: 21000, - ..Default::default() - }, + tx_type: MORPH_TX_TYPE_ID, ..Default::default() }; - assert_eq!(tx.gas_limit, 21000); - assert_eq!(tx.inner.gas_limit, 21000); + assert_eq!(tx.ty(), MORPH_TX_TYPE_ID); } #[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); + fn effective_gas_price_uses_the_transaction_fee_model() { + let legacy = MorphTxEnv { + gas_price: 10, + ..Default::default() + }; + assert_eq!(legacy.effective_gas_price_at(1), 10); + + 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 +732,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 +750,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 +772,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 +797,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 +824,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 +834,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 +845,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 +874,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 +895,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![MorphAuthorization::Signed(sample_signed_authorization())], ..Default::default() }; @@ -871,25 +917,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![MorphAuthorization::Signed(signed_authorization.clone())], ..Default::default() }; @@ -907,21 +944,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 +964,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 +972,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: MorphAuthorization) -> 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 +997,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()), + MorphAuthorization::Signed(signed_authorization.clone()), ); let encoded = tx.encode_for_l1_fee(53077); @@ -987,10 +1015,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 +1023,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, + MorphAuthorization::Signed(sample_signed_authorization()), + ); let encoded = tx.encode_for_l1_fee(53077); let decoded = MorphTxEnvelope::decode_2718(&mut encoded.as_ref()).unwrap(); @@ -1010,10 +1038,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 +1048,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), + MorphAuthorization::Recovered(recovered), + ); let encoded = tx.encode_for_l1_fee(53077); let decoded = MorphTxEnvelope::decode_2718(&mut encoded.as_ref()).unwrap(); @@ -1073,16 +1101,184 @@ 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] { + MorphAuthorization::Recovered(recovered) => { let (authorization, _authority) = recovered.clone().into_parts(); assert_eq!(&authorization, signed_authorization.inner()); } 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 4f880141..2b4d6fe8 100644 --- a/crates/rpc/Cargo.toml +++ b/crates/rpc/Cargo.toml @@ -14,11 +14,12 @@ 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 # Reth +reth-chain-state.workspace = true reth-chainspec.workspace = true reth-node-api.workspace = true reth-node-builder.workspace = true @@ -31,9 +32,8 @@ reth-rpc-eth-types.workspace = true reth-rpc-server-types.workspace = true reth-metrics.workspace = true metrics.workspace = true -reth-evm = { workspace = true, features = ["std"] } +reth-evm = { workspace = true, features = ["std", "witness"] } reth-provider.workspace = true -reth-revm = { workspace = true, features = ["std", "witness"] } reth-storage-api.workspace = true reth-tasks.workspace = true reth-errors.workspace = true @@ -42,7 +42,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 @@ -55,10 +54,11 @@ jsonrpsee.workspace = true async-trait.workspace = true # Serialization +futures.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/rpc/src/error.rs b/crates/rpc/src/error.rs index 63cac662..08fcfe97 100644 --- a/crates/rpc/src/error.rs +++ b/crates/rpc/src/error.rs @@ -1,10 +1,10 @@ //! Error types for Morph RPC use alloy_primitives::B256; -use morph_evm::MorphEvmConfig; +use alloy_rpc_types_eth::error::EthRpcErrorCode; +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 +90,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; } @@ -100,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::<()>) @@ -172,8 +176,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 +196,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()) } } @@ -257,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/call.rs b/crates/rpc/src/eth/call.rs index b1141e31..135ba936 100644 --- a/crates/rpc/src/eth/call.rs +++ b/crates/rpc/src/eth/call.rs @@ -1,26 +1,72 @@ -//! 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 a token-denominated limit -//! (MorphTx `fee_token_id > 0`, see `token_gas_allowance`). `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, except -//! that fee-token callers are left uncapped for the handler. - -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; +//! - [`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, Bytes, TxKind, U256, U512}; +use alloy_rpc_types_eth::{BlockId, simulate::SimulatePayload, state::EvmOverrides}; +use evm2::{ + EvmFeatures, TxResult, + evm::{CacheDB, Db}, + interpreter::InstrStop, + registry::HandlerError, +}; use morph_chainspec::{MorphChainSpec, MorphHardforks}; -use morph_revm::{L1BlockInfo, MorphTxExt, TokenFeeInfo}; -use reth_evm::{EvmEnvFor, TxEnvFor}; +use morph_revm::{ + L1BlockInfo, MorphEvmEnv, MorphTxEnv, MorphTxExt, TokenFeeInfo, TokenRegistryEntry, +}; +use reth_chainspec::MIN_TRANSACTION_GAS; +use reth_errors::ProviderError; +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, + RpcTypes, + helpers::{ + 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}, + error::api::{FromEvmHalt, FromRevert}, + simulate::EthSimulateError, }; -use reth_rpc_eth_types::EthApiError; -use revm::{Database, context::Transaction as RevmTransaction}; +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 std::borrow::Cow; +use tracing::trace; impl EthCall for MorphEthApi where @@ -28,8 +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, + 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()); + } + 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)?; + } + self.eth_api() + .simulate_v1(payload, block) + .await + .map_err(Into::into) + } } impl EstimateCall for MorphEthApi @@ -38,8 +105,223 @@ where N::Provider: ChainSpecProvider, Rpc: reth_rpc_convert::RpcConvert, + Rpc::Network: RpcTypes, 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, + ); + + // 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(); + + 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); + 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 @@ -72,54 +354,32 @@ 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. - if evm_env.cfg_env.disable_block_gas_limit { - 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, - }); - } - - // 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( + // `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) + { + return call_gas_allowance( &mut db, - tx_env.caller(), - tx_env.value(), - l1_fee, - fee_token_id, - tx_env.fee_limit, - tx_env.gas_price(), + tx_env.inner(), + tx_env.signer(), + self.call_gas_limit(), ); } - // allowance = (balance − value − l1_fee) / gas_price, done at wei - // precision so the remainder is not lost across the two - // subtractions. - let balance = db - .basic(tx_env.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); - } - Ok(gas_allowance_from_balance( - available - l1_fee, - tx_env.gas_price(), - )) + // eth_estimateGas path. + let l1_fee = self.estimate_l1_fee(&mut db, evm_env, tx_env)?; + estimate_gas_allowance( + &mut db, + evm_env, + tx_env.inner(), + tx_env.signer(), + l1_fee, + self.call_gas_limit(), + ) } } @@ -145,74 +405,224 @@ 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); - 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, - caller: alloy_primitives::Address, - value: U256, - l1_fee: U256, - fee_token_id: u16, - fee_limit: Option, - gas_price: u128, - ) -> Result - where - DB: revm::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)?; +/// 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())) +} - // ETH only needs to cover `value`; gas + L1 fee are paid in tokens. - let eth_balance = db - .basic(caller) +/// 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) + } +} + +/// 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(|acc| acc.balance) + .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)) +} - token_gas_allowance( - eth_balance, - value, - &token_fee_info, +/// 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_limit, - gas_price, - self.eth_api().gas_cap(), - ) + 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. +#[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, + 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 in EVM-call mode: as the no-`fee_limit` fallback (instead of `u64::MAX`) -/// and as the clamp on a user-supplied `fee_limit`. 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, @@ -220,7 +630,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() @@ -233,53 +642,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_token_fee_info`). On the estimateGas path - // `disable_fee_charge=true` 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)) } @@ -304,23 +698,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::*; @@ -411,30 +788,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, @@ -442,101 +847,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, @@ -545,78 +865,299 @@ 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. + + // `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), + ); + 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:?}" + ); + } + + #[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(_))); + } + + #[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!( - token_amount_to_eth(U256::from(4u64), &info), - Some(U256::from(1u64)) + call_gas_allowance(&mut db, &standard_tx, caller, 0).unwrap(), + 100 ); - // Exact multiple: 10 tokens → 3 wei (floor and ceil agree). assert_eq!( - token_amount_to_eth(U256::from(10u64), &info), - Some(U256::from(3u64)) + 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 + )); } } diff --git a/crates/rpc/src/eth/mod.rs b/crates/rpc/src/eth/mod.rs index 01ff9e00..efc0f983 100644 --- a/crates/rpc/src/eth/mod.rs +++ b/crates/rpc/src/eth/mod.rs @@ -3,19 +3,19 @@ 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, 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::{ - EthApiTypes, RpcNodeCore, RpcNodeCoreExt, + EthApiTypes, FromEthApiError, RpcNodeCore, RpcNodeCoreExt, helpers::{ EthApiSpec, EthBlocks, EthFees, EthState, EthSubscriptions, EthTransactions, LoadBlock, LoadFee, LoadPendingBlock, LoadState, LoadTransaction, SpawnBlocking, Trace, @@ -23,7 +23,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 +79,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 +88,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 +157,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 @@ -258,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 @@ -351,6 +377,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 @@ -397,13 +495,15 @@ where { fn apply_pre_execution_changes( &self, - _block: &RecoveredBlock<::Block>, - _db: &mut StateCacheDb, - ) -> Result<(), Self::Error> { + _block: &reth_primitives_traits::RecoveredBlock< + reth_provider::ProviderBlock, + >, + _db: &mut reth_rpc_eth_types::StateCacheDb, + ) -> Result { // Morph has no Ethereum-style (EIP-4788) pre-block system calls to replay. The // upstream default would only run the Morph executor's pre-execution step, // which just pre-warms the L1 gas oracle account. - Ok(()) + Ok(Default::default()) } } 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 d3d0339a..02a5726a 100644 --- a/crates/rpc/src/eth/transaction.rs +++ b/crates/rpc/src/eth/transaction.rs @@ -1,15 +1,20 @@ //! 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 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_primitives::{MorphTxEnvelope, TxMorph, transaction::morph_transaction::MAX_MEMO_LENGTH}; +use morph_revm::{MorphAuthorization, MorphEvmEnv, MorphTxEnv}; use reth_evm::EvmEnv; /// Converts a [`MorphTransactionRequest`] into a simulated transaction envelope. @@ -53,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. @@ -99,21 +136,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,31 +162,100 @@ 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)?; + // 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); + if !is_morph_tx && tx_type == TxType::Eip7702 && kind.is_create() { + return Err(EthTxEnvError::AuthorizationListInvalidFields.into()); + } + 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::new(inner_tx_env); + let mut tx_env = MorphTxEnv { + tx_type: tx_type.into(), + gas_limit: inner.gas.unwrap_or_default(), + gas_price, + gas_priority_fee, + 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(MorphAuthorization::Signed) + .collect(), + ..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; - 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 +265,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)) } } @@ -291,12 +391,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 { @@ -322,27 +423,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 @@ -370,7 +464,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 +498,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 +520,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 +570,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 +646,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 +723,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 @@ -646,6 +743,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(); @@ -663,16 +807,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 +842,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" ); @@ -737,7 +881,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" ); @@ -1061,15 +1205,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 { @@ -1097,10 +1244,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 @@ -1122,11 +1269,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 { @@ -1155,7 +1305,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] @@ -1192,7 +1342,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()), @@ -1560,4 +1710,208 @@ 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()); + } + + #[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/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/morph/handler.rs b/crates/rpc/src/morph/handler.rs index acef6045..67bb9949 100644 --- a/crates/rpc/src/morph/handler.rs +++ b/crates/rpc/src/morph/handler.rs @@ -11,7 +11,8 @@ use morph_reference_index::{ ReferenceTransactionResult, }; use reth_storage_api::{BlockNumReader, HeaderProvider}; -use std::time::{Duration, Instant}; +use std::time::Duration; +use tokio::time::Instant; use tracing; const TARGET: &str = "morph::reference_index_rpc"; @@ -25,11 +26,119 @@ 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 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 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!( + phase, + ReferenceIndexPhase::Deferred + | ReferenceIndexPhase::PreJade + | ReferenceIndexPhase::Repairing + ) { + return true; + } + + if let Some(indexed_to) = indexed_to + && canonical_tip_number.saturating_sub(indexed_to) > MAX_STEADY_STATE_LAG + { + return true; + } + + 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, + /// The index cursor has not reached the canonical tip yet. + Behind { + tip_number: u64, + indexed_to: Option, + }, +} + +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()?; + 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()?; + 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. + 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), + } +} + // ── Context ────────────────────────────────────────────────────────────────── /// `morph_` namespace context. All dependencies are required; no `Option<>`. @@ -111,10 +220,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 +237,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> { @@ -147,94 +253,34 @@ where // 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`. + // 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); 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) + 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()); - } - // 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. + match attempt { + QueryAttempt::Ready(results) => return Ok(results), + 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)); } - 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)); - } - } - Err(other) => return Err(to_rpc_error(other)), } } @@ -243,7 +289,7 @@ where wait.mark_timed_out(); return Err(to_rpc_error(ReferenceIndexError::IndexBehind)); }; - std::thread::sleep(delay); + tokio::time::sleep(delay).await; } } } @@ -562,6 +608,7 @@ mod tests { block: CanonicalBlock { number: 0, hash, + parent_hash: B256::ZERO, timestamp: block_timestamp, transactions: Vec::new(), }, @@ -580,8 +627,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 +649,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 +671,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 +700,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,13 +731,16 @@ 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 // the runtime will not catch up while indexing is intentionally paused. @@ -697,6 +750,7 @@ mod tests { block: CanonicalBlock { number: 0, hash, + parent_hash: B256::ZERO, timestamp: 100, transactions: Vec::new(), }, @@ -717,6 +771,7 @@ mod tests { let error = handler .get_transaction_hashes_by_reference(args()) + .await .unwrap_err(); assert_eq!(error.message(), "reference index is behind"); @@ -738,7 +793,121 @@ mod tests { } #[test] - fn live_lag_wait_eventually_returns_behind() { + fn should_fail_fast_classifies_phases_and_steady_state_lag() { + assert!(should_fail_fast( + ReferenceIndexPhase::Deferred, + Some(10), + 10 + )); + assert!(should_fail_fast(ReferenceIndexPhase::PreJade, None, 10)); + assert!(should_fail_fast( + 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( + ReferenceIndexPhase::Backfill, + Some(10), + 12 + )); + assert!(!should_fail_fast(ReferenceIndexPhase::Backfill, None, 1)); + + // Lag > MAX_STEADY_STATE_LAG (2) fails fast. + assert!(should_fail_fast( + ReferenceIndexPhase::Backfill, + Some(10), + 13 + )); + } + + #[tokio::test] + 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 (_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: 3, + }], + BTreeMap::from([(head_hash, header(3, 103))]), + ); + let handler = MorphRpcHandler::new(MorphRpc::new(handle, provider)); + + let started = Instant::now(); + let error = handler + .get_transaction_hashes_by_reference(args()) + .await + .unwrap_err(); + + assert_eq!(error.message(), "reference index is behind"); + assert!( + started.elapsed() < Duration::from_millis(100), + "a lag beyond steady state must not burn the wait budget: {:?}", + started.elapsed() + ); + } + + #[tokio::test] + 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 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(), + }); + 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: mid_hash, + parent_hash: indexed_hash, + timestamp: 101, + transactions: Vec::new(), + }); + chain.push(CanonicalBlock { + number: 2, + hash: head_hash, + parent_hash: mid_hash, + timestamp: 102, + transactions: Vec::new(), + }); + + let provider = TestProvider::new( + [ChainInfo { + best_hash: head_hash, + best_number: 2, + }], + BTreeMap::from([(head_hash, header(2, 102))]), + ); + 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)); + + let result = handler.get_transaction_hashes_by_reference(args()).await; + catch_up.join().unwrap(); + + assert!( + result.is_ok(), + "a lag of two is steady state and must be waited out: {result:?}" + ); + } + + #[tokio::test] + 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); @@ -753,19 +922,21 @@ mod tests { let error = handler .get_transaction_hashes_by_reference(args()) + .await .unwrap_err(); assert_eq!(error.message(), "reference index is behind"); } - #[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); let chain = GrowingTestChain::new(CanonicalBlock { number: 0, hash: indexed_hash, + parent_hash: B256::ZERO, timestamp: 100, transactions: Vec::new(), }); @@ -775,6 +946,7 @@ mod tests { chain.push(CanonicalBlock { number: 1, hash: head_hash, + parent_hash: indexed_hash, timestamp: 101, transactions: Vec::new(), }); @@ -794,20 +966,24 @@ 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(); catch_up.join().unwrap(); assert!(results.is_empty()); } - #[test] - fn live_lag_wait_covers_a_200ms_catch_up() { + #[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); let chain = GrowingTestChain::new(CanonicalBlock { number: 0, hash: indexed_hash, + parent_hash: B256::ZERO, timestamp: 100, transactions: Vec::new(), }); @@ -817,6 +993,7 @@ mod tests { chain.push(CanonicalBlock { number: 1, hash: head_hash, + parent_hash: indexed_hash, timestamp: 101, transactions: Vec::new(), }); @@ -834,7 +1011,7 @@ mod tests { }); let handler = MorphRpcHandler::new(MorphRpc::new(handle, provider)); - let result = handler.get_transaction_hashes_by_reference(args()); + let result = handler.get_transaction_hashes_by_reference(args()).await; catch_up.join().unwrap(); assert!( @@ -843,14 +1020,15 @@ mod tests { ); } - #[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); let chain = GrowingTestChain::new(CanonicalBlock { number: 0, hash: indexed_hash, + parent_hash: B256::ZERO, timestamp: 100, transactions: Vec::new(), }); @@ -860,6 +1038,7 @@ mod tests { chain.push(CanonicalBlock { number: 1, hash: head_hash, + parent_hash: indexed_hash, timestamp: 101, transactions: Vec::new(), }); @@ -888,6 +1067,7 @@ mod tests { let error = handler .get_transaction_hashes_by_reference(args()) + .await .unwrap_err(); transition.join().unwrap(); @@ -896,8 +1076,8 @@ mod tests { assert_eq!(*outcomes.lock().unwrap(), [false]); } - #[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 +1105,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..6c30a2e8 100644 --- a/crates/rpc/src/morph/rpc.rs +++ b/crates/rpc/src/morph/rpc.rs @@ -41,9 +41,11 @@ 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 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, args: ReferenceQueryArgs, ) -> RpcResult>; 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/Cargo.toml b/crates/txpool/Cargo.toml index 1d7ad71b..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 @@ -23,18 +23,19 @@ reth-chainspec.workspace = true reth-evm = { workspace = true, features = ["std"] } reth-primitives-traits.workspace = true reth-provider.workspace = true -reth-revm = { workspace = true, features = ["std"] } 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 c-kzg = "2.1.5" +dashmap.workspace = true derive_more.workspace = true futures.workspace = true parking_lot.workspace = true @@ -43,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/error.rs b/crates/txpool/src/error.rs index 3889bbb9..83e97bc4 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. @@ -66,6 +72,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 { @@ -86,6 +102,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, @@ -110,6 +129,9 @@ impl fmt::Display for MorphTxError { Self::InvalidFormat { reason } => { write!(f, "invalid MorphTx format: {reason}") } + Self::ForkNotActive { reason } => { + write!(f, "{reason}") + } } } } @@ -119,16 +141,21 @@ 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 - configuration issue, not penalizable - Self::InvalidPriceRatio { .. } | Self::TokenBalanceQueryFailed { .. } => false, + // Invalid price ratio, scale, or balanceOf failure - state/config issue, not penalizable + Self::InvalidPriceRatio { .. } + | Self::InvalidTokenScale { .. } + | Self::TokenBalanceQueryFailed { .. } => false, // Insufficient balance or fee limit - normal validation failure Self::InsufficientTokenBalance { .. } | Self::InsufficientEthForValue { .. } => false, } @@ -146,12 +173,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)), } } @@ -224,6 +247,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"), @@ -231,14 +257,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!( @@ -248,6 +279,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 { @@ -271,6 +310,8 @@ 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::TokenBalanceQueryFailed { token_id: 1 }.is_bad_transaction()); } #[test] @@ -281,6 +322,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 ac0e2948..34fe7e1f 100644 --- a/crates/txpool/src/lib.rs +++ b/crates/txpool/src/lib.rs @@ -39,6 +39,8 @@ mod error; pub use error::{MorphTxError, MorphTxValidationError}; +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 6ae73871..5802ab15 100644 --- a/crates/txpool/src/maintain.rs +++ b/crates/txpool/src/maintain.rs @@ -15,8 +15,8 @@ //! 1. Listening to canonical state changes (new blocks) //! 2. Re-validating every pooled transaction, including those parked behind a nonce gap, //! against the sender's current account balances -//! 3. Removing the first transaction with an L1 fee or token shortfall that reth cannot -//! handle, letting the pool park its descendants +//! 3. Removing every transaction with a block-gas-limit, L1 fee, or token-fee violation +//! that reth cannot handle, letting the pool park surviving descendants //! //! # Relationship with reth's own maintenance task //! @@ -25,8 +25,9 @@ //! guarantee between them. Everything reth's task already understands (ETH balance, nonces, //! base fee, mined transactions) stays its responsibility. This task also checks the //! sender's **ERC20 token** balance and the **L1 data fees** missing from reth's cost. -//! An ordinary transaction that cannot cover L1 fees is -//! removed so its descendants are parked instead of remaining unchecked in pending. +//! Every transaction of a sender at or above the on-chain nonce is revalidated in one pass, +//! matching go-ethereum's full-list filter; removing offending transactions lets reth park +//! any surviving descendants. //! //! Because the ordering is not guaranteed, this task must tolerate seeing a pool snapshot //! that still contains transactions the new block already executed. It does so by reading @@ -40,19 +41,22 @@ //! and `demoteUnexecutables` (tx_pool.go), but implemented as a separate //! maintenance task since we cannot modify reth's internal pool logic. -use crate::{MorphPooledTransaction, MorphTxValidationError, MorphValidationState}; +use crate::{ + MorphPooledTransaction, MorphTxValidationError, MorphValidationState, + morph_tx_validation::validate_morph_tx_with, + state_cache::{StateCache, TokenFeeValidator}, +}; use alloy_consensus::Transaction; use alloy_consensus::Typed2718; use alloy_primitives::{Address, B256, TxHash}; use futures::{FutureExt, StreamExt}; -use morph_chainspec::hardfork::{MorphHardfork, MorphHardforks}; -use morph_revm::{L1BlockInfo, MorphBlockEnv, MorphEvmEnv}; +use morph_chainspec::hardfork::MorphHardforks; +use morph_revm::{L1BlockInfo, MorphEvmEnv}; use reth_chainspec::ChainSpecProvider; -use reth_evm::{ConfigureEvm, EvmFactory, EvmFactoryFor}; +use reth_evm::{ConfigureEvm, Database, EvmEnvFor, database::StateProviderDatabase}; use reth_primitives_traits::{AlloyBlockHeader, HeaderTy, NodePrimitives, SealedHeader}; use reth_provider::CanonStateSubscriptions; -use reth_revm::database::StateProviderDatabase; -use reth_storage_api::{BlockReaderIdExt, StateProviderFactory}; +use reth_storage_api::{BlockReaderIdExt, StateProvider as _, StateProviderFactory}; use reth_transaction_pool::{PoolTransaction, TransactionPool}; use std::collections::{HashMap, HashSet}; @@ -80,7 +84,7 @@ impl FeeStateSource for ProviderFeeState>, Evm: ConfigureEvm, - EvmFactoryFor: EvmFactory, + EvmEnvFor: Into, { fn state_for( &self, @@ -100,124 +104,135 @@ fn exceeds_block_gas_limit(tx_gas_limit: u64, block_gas_limit: u64) -> bool { /// Determines which transactions to remove while revalidating all senders' fee affordability. /// -/// Returns the hashes to remove from the pool. Only the first offending transaction of a -/// sender is returned: the pool parks the rest of that sender's transactions on its own when -/// the returned hash is removed (see [`maintain_morph_pool`]). -fn collect_removable_transactions( +/// Scans every transaction of each sender at or above the sender's on-chain nonce and returns +/// every offending hash in one pass, matching go-ethereum's full-sender filter (`txList.FilterF`). +/// Continuing past ETH-parked or invalid predecessors prevents an earlier parked transaction from +/// shielding invalid higher-nonce transactions that reth would otherwise promote unvalidated once +/// the predecessor is replaced or funded. Surviving descendants of removed transactions are parked +/// automatically by reth's `remove_transactions` (see [`maintain_morph_pool`]). +fn collect_removable_transactions( db: &mut DB, l1_block_info: &L1BlockInfo, evm_env: &MorphEvmEnv, block_gas_limit: u64, pool_txs: Vec<&MorphPooledTransaction>, ) -> Vec { - let hardfork = *evm_env.cfg_env.spec(); - // These caches live for exactly this provider/environment snapshot. Cache successful - // reads only; a later block must re-read changed registry parameters and balances. - let mut token_entries = HashMap::new(); - let mut token_balances = HashMap::new(); - // Group by sender and process in nonce order so removing a transaction parks its descendants. + let hardfork = evm_env.spec; + + // Group by sender and process in nonce order for deterministic removal ordering. let mut txs_by_sender: HashMap> = HashMap::new(); for tx in pool_txs { txs_by_sender.entry(tx.sender()).or_default().push(tx); } - let mut to_remove: Vec = Vec::new(); - - for (sender, mut sender_txs) in txs_by_sender { - sender_txs.sort_by_key(|tx| tx.transaction().nonce()); - - // Read one account per sender. Affordability is per transaction, matching - // admission and geth; cumulative ETH parking remains owned by reth. - let account = match db.basic(sender) { - Ok(account) => account.unwrap_or_default(), + // Read each sender's on-chain account once before constructing the reusable `TokenFeeValidator` + // over `&mut *db`. If a sender's account cannot be read due to a transient DB error, skip + // that sender instead of evicting their transactions. + let mut sender_accounts: HashMap = + HashMap::with_capacity(txs_by_sender.len()); + for sender in txs_by_sender.keys() { + match db.get_account(sender) { + Ok(account) => { + sender_accounts.insert(*sender, account.unwrap_or_default()); + } Err(err) => { tracing::warn!( target: "morph::txpool::maintain", ?sender, ?err, - "Failed to get account info; skipping sender" + "Failed to get account info; leaving sender's transactions in the pool" ); - continue; } + } + } + + // Cache registry entries, storage reads, and call-mode `balanceOf` results across all + // transactions in this round only; a later block builds a fresh cache. + let cache = StateCache::default(); + let mut token_validator = TokenFeeValidator::new(&cache, db, evm_env.clone()); + + let mut to_remove: Vec = Vec::new(); + + for (sender, mut sender_txs) in txs_by_sender { + let Some(account) = sender_accounts.get(&sender) else { + continue; }; + sender_txs.sort_by_key(|tx| Transaction::nonce(*tx)); for tx in sender_txs { - // Access the consensus tx by reference (via Deref chain) instead of - // cloning. Use the pool tx's cached EIP-2718 encoding for L1 fee. let consensus_tx = tx.transaction(); - // Already executed by the new block. reth's own maintenance task removes these - // when it applies the same canonical update; both tasks subscribe to the - // canonical stream independently, so this one can still observe them here. - // Judging them is pointless, and removing one here would park the sender's next - // transaction until reth's own update re-promotes it. - if consensus_tx.nonce() < account.nonce { + // Standard maintenance removes mined transactions concurrently; skip any the + // new block already executed rather than judging them against post-block balances. + if tx.nonce() < account.nonce { continue; } - // A nonce gap does not stop the walk. Every check below is per transaction - // against the sender's current balances, which is what admission applies and - // what go-ethereum's `promoteExecutables` applies to its whole queue (`FilterF`) - // before `Ready` promotes anything. Nothing here accumulates the costs of the - // missing predecessors, so a transaction parked behind a gap can be judged on its - // own. Left unchecked, reth would promote it unvalidated the moment the gap is - // filled: `AllTransactions::insert_tx` only recomputes the ETH cost bits, which - // for a token-fee MorphTx cover its value alone. + // A nonce gap or earlier invalid/ETH-parked transaction does not stop the walk. + // Every check below is per transaction against the sender's current balances, + // which is what admission applies and what go-ethereum's `promoteExecutables` + // applies to its whole queue (`FilterF`) before `Ready` promotes anything. + // Nothing here accumulates the costs of missing predecessors, so every transaction + // can be judged on its own. Stopping early would leave invalid higher-nonce + // transactions in the pool for reth to promote unvalidated the moment a + // predecessor is replaced or funded: `AllTransactions::insert_tx` only recomputes + // the ETH cost bits, which for a token-fee MorphTx cover its value alone. // Reth only sets its block-gas-limit flag at insertion, so a later // limit reduction needs the same explicit removal for both tx types. if exceeds_block_gas_limit(consensus_tx.gas_limit(), block_gas_limit) { to_remove.push(*tx.hash()); - break; + continue; } - // Reth knows this ETH cost (only value for token-fee MorphTx) and can - // park the transaction until a balance update makes it affordable again. - if *tx.cost() > account.balance { - break; + let uses_token_fee = consensus_tx.fee_token_id().is_some_and(|id| id > 0); + + // For ETH-paying transactions (ordinary txs and `fee_token_id == 0` MorphTxs), + // reth knows `tx.cost()` (`gas_limit * max_fee_per_gas + value`) and parks the + // transaction until a balance update makes it affordable again. Do not remove it + // here, but keep scanning higher nonces so an ETH-parked predecessor cannot shield + // invalid descendants. + // + // For token-fee MorphTxs (`fee_token_id > 0`), `tx.cost()` is `value` alone: even + // when reth parks the transaction for an ETH `value` shortfall, we must still + // validate its token usability and token-fee affordability below so an invalid or + // unaffordable token transaction is not left parked and later promoted unvalidated + // when ETH arrives. + if *tx.cost() > account.balance && !uses_token_fee { + continue; } let l1_data_fee = l1_block_info.calculate_tx_l1_cost(tx.encoded_2718(), hardfork); if consensus_tx.ty() != morph_primitives::MORPH_TX_TYPE_ID { if tx.cost().saturating_add(l1_data_fee) > account.balance { to_remove.push(*tx.hash()); - break; } continue; } - // Validate each transaction against the same chain balance used at admission. + // Validate each MorphTx against the same chain balance used at admission. + // When a token-fee MorphTx is parked purely due to an ETH `value` shortfall + // (`tx.value() > account.balance`), raise `eth_balance` to `tx.value()` so + // `validate_morph_tx_with` does not treat that ETH shortfall as a removal reason + // (standard maintenance owns ETH `value` parking) while still enforcing hardfork, + // format, token usability, and token balance checks. + let eth_balance = if uses_token_fee { + account.balance.max(consensus_tx.value()) + } else { + account.balance + }; let input = crate::MorphTxValidationInput { consensus_tx, sender, - eth_balance: account.balance, + eth_balance, l1_data_fee, hardfork, evm_env, }; - match crate::morph_tx_validation::validate_morph_tx_with_token_info( - &input, - |token_id| { - use morph_revm::TokenRegistryEntry; - let entry = match token_entries.entry(token_id) { - std::collections::hash_map::Entry::Occupied(entry) => *entry.get(), - std::collections::hash_map::Entry::Vacant(entry) => { - *entry.insert(TokenRegistryEntry::load(db, token_id)?) - } - }; - let Some(entry) = entry else { - return Ok(None); - }; - let info = match token_balances.entry((sender, token_id)) { - std::collections::hash_map::Entry::Occupied(info) => *info.get(), - std::collections::hash_map::Entry::Vacant(info) => { - *info.insert(entry.load_for_caller(db, sender, evm_env)?) - } - }; - Ok(Some(info)) - }, - ) { + match validate_morph_tx_with(&input, |token_id, caller| { + token_validator.resolve_token_fee_info(token_id, caller) + }) { Ok(_) => {} Err(MorphTxValidationError::State(err)) => { tracing::warn!( @@ -225,9 +240,8 @@ fn collect_removable_transactions( tx_hash = ?tx.hash(), ?sender, ?err, - "Could not read token state; leaving sender's MorphTx in the pool" + "Could not read token state; leaving MorphTx in the pool" ); - break; } Err(MorphTxValidationError::Invalid(err)) => { tracing::debug!( @@ -238,9 +252,8 @@ fn collect_removable_transactions( "Removing MorphTx: validation failed" ); to_remove.push(*tx.hash()); - break; } - }; + } } } @@ -305,7 +318,8 @@ where .into_iter() .flat_map(|sender| pool.get_transactions_by_sender(sender)) .collect(); - let mut db = StateProviderDatabase::new(state.provider); + let evm_state_provider = (&state.provider).into_evm_state_provider(); + let mut db = StateProviderDatabase::new(&evm_state_provider); let still_removable: HashSet = collect_removable_transactions( &mut db, &state.head.l1_block_info, @@ -329,11 +343,11 @@ where /// - Re-validates MorphTx (0x7F) transactions in the pool /// - Removes transactions that no longer have sufficient token balance /// - Re-validates L1 fee affordability for every sender, including ordinary-only senders -/// - Removes ordinary transactions whose L1 fees make them individually unaffordable, -/// parking their descendants -/// - Judges each transaction on its own, including those parked behind a nonce gap +/// - Removes every transaction whose block gas limit, L1 fee, or token-fee validation fails, +/// letting the pool park surviving descendants +/// - Judges each transaction on its own across each sender's full nonce sequence at or above +/// the on-chain nonce, including transactions parked behind a nonce gap or ETH shortfall /// - Re-checks every removal at the canonical head right before applying it -/// pub async fn maintain_morph_pool(pool: Pool, client: Client, evm_config: Evm) where Pool: TransactionPool + Clone, @@ -343,8 +357,8 @@ where + CanonStateSubscriptions + Clone + 'static, - Evm: ConfigureEvm::Primitives>, - EvmFactoryFor: EvmFactory, + Evm: ConfigureEvm::Primitives>, + EvmEnvFor: Into, { let chain_events = client.canonical_state_stream(); @@ -390,8 +404,8 @@ async fn maintain_morph_pool_with( "Processing new block for pool fee validation" ); - // Every transaction type is revalidated (ordinary ones for their L1 fee), and a - // sender's full nonce order decides which offender is removed first. + // Every transaction type is revalidated (ordinary ones for their L1 fee), scanning each + // sender's full nonce sequence at or above the on-chain nonce. let all_txs = pool.all_transactions(); let pool_txs: Vec<&MorphPooledTransaction> = all_txs .pending @@ -411,7 +425,8 @@ async fn maintain_morph_pool_with( continue; } }; - let mut db = StateProviderDatabase::new(state.provider); + let evm_state_provider = (&state.provider).into_evm_state_provider(); + let mut db = StateProviderDatabase::new(&evm_state_provider); let l1_block_info = state.head.l1_block_info; let evm_env = &state.head.evm_env; @@ -455,1138 +470,450 @@ async fn maintain_morph_pool_with( #[cfg(test)] mod tests { use super::*; - use alloy_primitives::U256; - - #[test] - fn gas_limit_check_rejects_transactions_above_block_limit() { - assert!(exceeds_block_gas_limit(30_000_001, 30_000_000)); - assert!(!exceeds_block_gas_limit(30_000_000, 30_000_000)); - } - - // --------------------------------------------------------------------------------- - // Revalidation round tests - // - // These drive `collect_removable_transactions` against a hand-built state so the - // removal verdict can be asserted without a pool, and one pool-level test covers the - // descendant handling that only the pool can show. - // --------------------------------------------------------------------------------- - use crate::morph_tx_validation::tests::{ BALANCE_OF_RUNTIME, FAILING_BALANCE_OF, TokenRead, UnreadableTokenDb, - call_mode_registry_storage, call_mode_token_state, token_balance_key, + call_mode_registry_storage, call_mode_token_state, test_evm_env, token_balance_key, }; - use alloy_consensus::{Signed, transaction::Recovered}; + use alloy_consensus::{Signed, TxLegacy, transaction::Recovered}; use alloy_eips::eip2718::Encodable2718; - use alloy_primitives::{Signature, TxKind, address}; - use morph_primitives::{MorphTxEnvelope, TxMorph}; + use alloy_primitives::{Bytes, Sealable, Signature, TxKind, U256, address}; + use evm2::bytecode::Bytecode; + use evm2::evm::{AccountInfo, CacheDB, DynDatabase, EmptyDB, InMemoryDB}; + use morph_chainspec::{MORPH_MAINNET, MorphHardfork}; + use morph_evm::MorphEvmConfig; + use morph_primitives::{MorphHeader, MorphPrimitives, MorphTxEnvelope, TxMorph}; use morph_revm::L2_TOKEN_REGISTRY_ADDRESS; - use reth_revm::revm; - use reth_revm::revm::database::{CacheDB, EmptyDB}; - use reth_revm::revm::state::AccountInfo; + use reth_provider::test_utils::{ExtendedAccount, MockEthProvider}; + use reth_transaction_pool::{ + CoinbaseTipOrdering, Pool, blobstore::InMemoryBlobStore, + validate::EthTransactionValidatorBuilder, + }; + use std::sync::Arc; - const SIGNER: Address = address!("0000000000000000000000000000000000000001"); + const SIGNER: Address = address!("1000000000000000000000000000000000000001"); const FEE_TOKEN: Address = address!("5300000000000000000000000000000000000042"); + const SECOND_TOKEN: Address = address!("5300000000000000000000000000000000000043"); const TOKEN_ID: u16 = 1; - /// `gas_limit * max_fee_per_gas` of [`token_fee_tx`]; at a 1:1 price ratio this is also - /// the per-transaction token requirement at admission and revalidation. + const SECOND_TOKEN_ID: u16 = 2; const TX_TOKEN_BUDGET: u64 = 21_000 * 100; - /// State with [`TOKEN_ID`] registered as an active call-mode fee token at a 1:1 price - /// ratio, whose `balanceOf` reports `token_balance` for [`SIGNER`]. - fn test_state(account_nonce: u64, eth_balance: u64, token_balance: u64) -> CacheDB { - test_state_with_token_code( - account_nonce, - eth_balance, - token_balance, - BALANCE_OF_RUNTIME, - ) - } - - /// [`test_state`] with the fee token's `balanceOf` replaced by `code`. - fn test_state_with_token_code( - account_nonce: u64, - eth_balance: u64, - token_balance: u64, - code: &'static [u8], - ) -> CacheDB { - let mut db = - call_mode_token_state(TOKEN_ID, FEE_TOKEN, code, SIGNER, U256::from(token_balance)); - db.insert_account_info( - SIGNER, - AccountInfo { - nonce: account_nonce, - balance: U256::from(eth_balance), - ..Default::default() - }, - ); - db - } - - /// A token-fee MorphTx requiring [`TX_TOKEN_BUDGET`] tokens and no ETH. - fn token_fee_tx(tx_nonce: u64) -> MorphPooledTransaction { - token_fee_tx_with(tx_nonce, U256::ZERO, 21_000) - } - - fn token_fee_tx_with_value(tx_nonce: u64, value: U256) -> MorphPooledTransaction { - token_fee_tx_with(tx_nonce, value, 21_000) - } - - /// [`token_fee_tx`] with `gas_limit`, so its token requirement scales with it. - fn token_fee_tx_with_gas_limit(tx_nonce: u64, gas_limit: u64) -> MorphPooledTransaction { - token_fee_tx_with(tx_nonce, U256::ZERO, gas_limit) + fn l1_block_info_with_fee(l1_fee: u64) -> L1BlockInfo { + let scaled = U256::from(l1_fee) * U256::from(1_000_000_000); + L1BlockInfo { + l1_base_fee: U256::from(1), + l1_commit_scalar: scaled, + calldata_gas: scaled, + ..Default::default() + } } - fn token_fee_tx_with(tx_nonce: u64, 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: tx_nonce, + nonce, gas_limit, max_fee_per_gas: 100, max_priority_fee_per_gas: 10, to: TxKind::Call(address!("0000000000000000000000000000000000000002")), value, - fee_token_id: TOKEN_ID, + fee_token_id: token_id, fee_limit: U256::ZERO, ..Default::default() }; - let recovered = Recovered::new_unchecked( - MorphTxEnvelope::Morph(Signed::new_unhashed(tx, Signature::test_signature())), - SIGNER, - ); - let encoded_len = recovered.encode_2718_len(); - MorphPooledTransaction::new(recovered, encoded_len) - } - - /// The environment the revalidation round is evaluated in. - fn test_evm_env() -> MorphEvmEnv { - MorphEvmEnv::new( - reth_revm::revm::context::CfgEnv::new_with_spec(MorphHardfork::Emerald), - MorphBlockEnv::default(), - ) - } - - fn removable(db: &mut CacheDB, txs: Vec<&MorphPooledTransaction>) -> Vec { - collect_removable_transactions( - db, - &L1BlockInfo::default(), - &test_evm_env(), - 30_000_000, - txs, - ) + 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 { + let tx = TxLegacy { + chain_id: Some(2818), + nonce, + gas_limit, + gas_price, + to: TxKind::Call(address!("0000000000000000000000000000000000000002")), + value, + input: Bytes::new(), + }; + 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) } - #[test] - fn transactions_already_executed_by_the_block_are_skipped_not_taken_for_a_gap() { - // The new block executed nonce 0, but this task can still see it: reth's own maintenance - // removes it on the same notification, in no guaranteed order. Reading it as a nonce gap - // would end the walk before nonce 1, which the post-state can no longer pay for. - let mut db = test_state(1, 0, TX_TOKEN_BUDGET - 1); - let (tx0, tx1) = (token_fee_tx(0), token_fee_tx(1)); - - assert_eq!(removable(&mut db, vec![&tx0, &tx1]), vec![*tx1.hash()]); + fn register_call_mode_token( + db: &mut InMemoryDB, + token_id: u16, + token: Address, + token_balance: u64, + active: bool, + ) { + let mut entries = call_mode_registry_storage(token_id, token); + if !active { + let mut inactive = [0u8; 32]; + inactive[30] = 18; + inactive[31] = 0; + entries[2].1 = U256::from_be_bytes(inactive); + } + for (slot, value) in entries { + db.insert_account_storage(&L2_TOKEN_REGISTRY_ADDRESS, &slot, &value); + } + db.insert_account_info( + &token, + 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), + ); } #[test] - fn individually_affordable_token_transactions_are_retained() { - // Each transaction passes admission against the same account balance. - // Maintenance must not evict one merely because their maximum costs add up. - let mut db = test_state(0, 0, TX_TOKEN_BUDGET + TX_TOKEN_BUDGET / 2); - let (tx0, tx1) = (token_fee_tx(0), token_fee_tx(1)); - - assert!(removable(&mut db, vec![&tx0, &tx1]).is_empty()); + fn gas_limit_check_rejects_transactions_above_block_limit() { + assert!(exceeds_block_gas_limit(30_000_001, 30_000_000)); + assert!(!exceeds_block_gas_limit(30_000_000, 30_000_000)); } #[test] - fn an_ordinary_transaction_between_morph_txs_does_not_hide_the_successor() { - let mut db = test_state(0, 10_000_000, TX_TOKEN_BUDGET - 1); - let (first, middle, last) = (legacy_tx(0), legacy_tx(1), token_fee_tx(2)); - assert_eq!( - removable(&mut db, vec![&first, &middle, &last]), - vec![*last.hash()] + fn skips_mined_nonces_and_revalidates_ordinary_tx_l1_fee() { + let mut db = CacheDB::new(EmptyDB::default()); + db.insert_account_info( + &SIGNER, + AccountInfo { + nonce: 1, + balance: U256::from(2_100_000u64), // covers tx1 cost (2.1M) alone, NOT + 1M L1 fee + ..Default::default() + }, ); - } + let tx0_mined = legacy_tx(0, 21_000, 100, U256::ZERO); + let tx1_unpayable_l1 = legacy_tx(1, 21_000, 100, U256::ZERO); + let tx2_payable = legacy_tx(2, 21_000, 10, U256::ZERO); // 210k + 1M <= 2.1M - #[test] - fn ordinary_predecessors_do_not_cause_a_morph_tx_value_to_be_evicted() { - let mut db = test_state(0, TX_TOKEN_BUDGET + 6, 10 * TX_TOKEN_BUDGET); - let (first, last) = (legacy_tx(0), token_fee_tx_with_value(1, U256::from(7))); - assert!(removable(&mut db, vec![&first, &last]).is_empty()); - } + let to_remove = collect_removable_transactions( + &mut db, + &l1_block_info_with_fee(1_000_000), + &test_evm_env(MorphHardfork::Celadon), + 30_000_000, + vec![&tx0_mined, &tx1_unpayable_l1, &tx2_payable], + ); - #[test] - fn morph_eth_shortfalls_remain_owned_by_standard_maintenance() { - let mut db = test_state(0, 6, 10 * TX_TOKEN_BUDGET); - let tx = token_fee_tx_with_value(0, U256::from(7)); - assert!(removable(&mut db, vec![&tx]).is_empty()); + assert_eq!(to_remove, vec![*tx1_unpayable_l1.hash()]); } #[test] - fn block_gas_limit_decreases_remove_both_transaction_types() { - for tx in [legacy_tx(0), token_fee_tx(0)] { - let mut db = test_state(0, 10_000_000, 10 * TX_TOKEN_BUDGET); - assert_eq!( - collect_removable_transactions( - &mut db, - &L1BlockInfo::default(), - &test_evm_env(), - 20_000, - vec![&tx] - ), - vec![*tx.hash()] + fn eth_parked_and_transient_db_errors_do_not_shield_higher_nonces() { + for fail_on in [ + TokenRead::Registry, + TokenRead::TokenAccount, + TokenRead::TokenStorage, + ] { + let mut inner = call_mode_token_state( + TOKEN_ID, + FEE_TOKEN, + SIGNER, + U256::from(TX_TOKEN_BUDGET), + BALANCE_OF_RUNTIME, + ); + // Second token is inactive (only detectable if registry read works). + register_call_mode_token(&mut inner, SECOND_TOKEN_ID, SECOND_TOKEN, 0, false); + inner.insert_account_info( + &SIGNER, + AccountInfo { + nonce: 0, + balance: U256::from(2_100_000u64), + ..Default::default() + }, ); - } - } - - #[test] - fn unaffordable_ordinary_predecessors_remain_owned_by_standard_maintenance() { - let mut db = test_state(0, 0, 10 * TX_TOKEN_BUDGET); - let (first, last) = (legacy_tx(0), token_fee_tx(1)); - assert!(removable(&mut db, vec![&first, &last]).is_empty()); - } - - #[test] - fn a_payable_transaction_behind_a_nonce_gap_is_kept() { - // The gap only decides where the transaction sits; affordability is judged on its own. - let mut db = test_state(0, 0, TX_TOKEN_BUDGET); - let (tx0, gapped) = (token_fee_tx(0), token_fee_tx(10)); - - assert!(removable(&mut db, vec![&tx0, &gapped]).is_empty()); - } - - #[test] - fn an_unpayable_transaction_behind_a_nonce_gap_is_removed() { - // Nonce 0 needs one budget, nonce 10 needs two, and the sender holds one. Stopping at - // the gap would leave nonce 10 in place for reth to promote unvalidated once nonces - // 1 to 9 arrive. - let mut db = test_state(0, 0, TX_TOKEN_BUDGET); - let (tx0, gapped) = (token_fee_tx(0), token_fee_tx_with_gas_limit(10, 2 * 21_000)); - - assert_eq!( - removable(&mut db, vec![&tx0, &gapped]), - vec![*gapped.hash()] - ); - } - - #[test] - fn a_sender_holding_only_future_nonces_is_still_revalidated() { - // go-ethereum's `promoteExecutables` filters the whole queue per transaction before - // promoting anything; a sender that no longer holds tokens loses its parked MorphTx. - let mut db = test_state(0, 0, 0); - let gapped = token_fee_tx(5); - - assert_eq!(removable(&mut db, vec![&gapped]), vec![*gapped.hash()]); - } - #[derive(Debug)] - struct CountingDb { - inner: CacheDB, - reads: HashMap, - } + let mut db = UnreadableTokenDb { + inner, + token: FEE_TOKEN, + fail_on, + }; - impl revm::Database for CountingDb { - type Error = core::convert::Infallible; - fn basic(&mut self, address: Address) -> Result, Self::Error> { - self.inner.basic(address) - } - fn code_by_hash( - &mut self, - hash: alloy_primitives::B256, - ) -> Result { - self.inner.code_by_hash(hash) - } - fn storage(&mut self, address: Address, slot: U256) -> Result { - *self.reads.entry(address).or_default() += 1; - self.inner.storage(address, slot) - } - fn block_hash(&mut self, number: u64) -> Result { - self.inner.block_hash(number) - } - } + // Nonce 0 triggers transient DB error on FEE_TOKEN -> must NOT be removed. + let tx0_db_err = token_fee_tx(0, TOKEN_ID, U256::ZERO, 21_000); + // Nonce 1 is ETH-parked (cost > 2.1M) -> left to reth, must NOT shield nonce 2. + let tx1_eth_parked = legacy_tx(1, 21_000, 200, U256::ZERO); + // Nonce 2 fails L1 fee check (2.1M + 1M > 2.1M) -> must be removed! + let tx2_l1_shortfall = legacy_tx(2, 21_000, 100, U256::ZERO); + // Nonce 3 is affordable (210k + 1M <= 2.1M) -> stays. + let tx3_valid = legacy_tx(3, 21_000, 10, U256::ZERO); - #[test] - fn token_cache_is_shared_within_a_round_and_refreshed_next_round() { - let mut db = CountingDb { - inner: test_state(0, 0, TX_TOKEN_BUDGET), - reads: HashMap::new(), - }; - let txs: Vec<_> = (0..3).map(token_fee_tx).collect(); - assert!( - collect_removable_transactions( + let to_remove = collect_removable_transactions( &mut db, - &L1BlockInfo::default(), - &test_evm_env(), + &l1_block_info_with_fee(1_000_000), + &test_evm_env(MorphHardfork::Celadon), 30_000_000, - txs.iter().collect() - ) - .is_empty() - ); - // Three transactions share one registry entry (five words) and one `balanceOf` SLOAD. - assert_eq!(db.reads[&L2_TOKEN_REGISTRY_ADDRESS], 5); - assert_eq!(db.reads[&FEE_TOKEN], 1); + vec![&tx0_db_err, &tx1_eth_parked, &tx2_l1_shortfall, &tx3_valid], + ); - // The next round reads both again, so it sees the balance spent in between. - db.inner - .insert_account_storage(FEE_TOKEN, token_balance_key(SIGNER), U256::ZERO) - .unwrap(); - assert_eq!( - collect_removable_transactions( - &mut db, - &L1BlockInfo::default(), - &test_evm_env(), - 30_000_000, - txs.iter().collect() - ), - vec![*txs[0].hash()] - ); - assert_eq!(db.reads[&L2_TOKEN_REGISTRY_ADDRESS], 10); - assert_eq!(db.reads[&FEE_TOKEN], 2); + assert_eq!( + to_remove, + vec![*tx2_l1_shortfall.hash()], + "transient {fail_on:?} error or ETH-parked tx must not remove tx0 or shield tx2" + ); + } } #[test] - fn unreadable_token_state_does_not_remove_transactions() { - let tx = token_fee_tx(0); - - // Sanity check: the same transaction against readable state is kept as well, so the - // assertions below are about the read failure and not about affordability. - assert!( - removable(&mut test_state(0, 0, 10 * TX_TOKEN_BUDGET), vec![&tx]).is_empty(), - "transaction is affordable when the token balance can be read" - ); + fn failing_balance_of_removes_morph_tx_without_removing_valid_descendants() { + for (label, runtime) in FAILING_BALANCE_OF { + let mut db = call_mode_token_state( + TOKEN_ID, + FEE_TOKEN, + SIGNER, + U256::from(TX_TOKEN_BUDGET), + runtime, + ); + db.insert_account_info( + &SIGNER, + AccountInfo { + nonce: 0, + balance: U256::from(10_000_000u64), + ..Default::default() + }, + ); + let tx0_bad_token = token_fee_tx(0, TOKEN_ID, U256::ZERO, 21_000); + let tx1_valid_eth = legacy_tx(1, 21_000, 100, U256::ZERO); - for failing in [TokenRead::Storage, TokenRead::Code] { - let mut db = UnreadableTokenDb { - inner: test_state(0, 0, 10 * TX_TOKEN_BUDGET), - token: FEE_TOKEN, - failing, - }; let to_remove = collect_removable_transactions( &mut db, &L1BlockInfo::default(), - &test_evm_env(), + &test_evm_env(MorphHardfork::Celadon), 30_000_000, - vec![&tx], - ); - assert!( - to_remove.is_empty(), - "a {failing:?} read failure inside balanceOf is not an invalid transaction" + vec![&tx0_bad_token, &tx1_valid_eth], ); + assert_eq!(to_remove, vec![*tx0_bad_token.hash()], "case {label}"); } } #[test] - fn a_balance_query_without_a_balance_removes_the_transaction() { - let tx = token_fee_tx(0); - for code in FAILING_BALANCE_OF { - let mut db = test_state_with_token_code(0, 0, 10 * TX_TOKEN_BUDGET, code); - assert_eq!( - removable(&mut db, vec![&tx]), - vec![*tx.hash()], - "balanceOf code {code:02x?}" - ); - } - } - - // --------------------------------------------------------------------------------- - // Pool-level test: only the pool can show what happens to a removed transaction's - // descendants, so this one drives the maintenance loop against a real pool. - // --------------------------------------------------------------------------------- - - use alloy_consensus::TxLegacy; - use alloy_primitives::Sealable; - use morph_chainspec::{MORPH_MAINNET, MorphChainSpec}; - use morph_evm::MorphEvmConfig; - use morph_primitives::MorphPrimitives; - use reth_provider::test_utils::{ExtendedAccount, MockEthProvider}; - use reth_transaction_pool::{ - CoinbaseTipOrdering, Pool, blobstore::InMemoryBlobStore, - validate::EthTransactionValidatorBuilder, - }; - - type TestProvider = MockEthProvider; - - fn storage_key(slot: U256) -> alloy_primitives::B256 { - alloy_primitives::B256::from(slot.to_be_bytes::<32>()) - } - - /// The chain head the pool validates against: an empty Emerald-active block. - fn head_block() -> morph_primitives::Block { - morph_primitives::Block { - header: morph_primitives::MorphHeader::from(alloy_consensus::Header { + fn remove_transactions_parks_surviving_descendant_and_rechecks_canonical_head() { + type TestPool = Pool< + crate::MorphTransactionValidator< + MockEthProvider, + MorphPooledTransaction, + MorphEvmConfig, + >, + CoinbaseTipOrdering, + InMemoryBlobStore, + >; + + let head0 = MorphHeader { + inner: alloy_consensus::Header { number: 1, - timestamp: 1_767_765_600, + timestamp: 2_000_000_000, gas_limit: 30_000_000, - base_fee_per_gas: Some(10), + base_fee_per_gas: Some(1), ..Default::default() - }), - body: Default::default(), - } - } - - /// Mirrors [`test_state`] for [`MockEthProvider`], which the pool's validator needs. - fn mock_provider(eth_balance: u64, token_balance: u64) -> TestProvider { - let client = MockEthProvider::::new() - .with_chain_spec((**MORPH_MAINNET).clone()) - .with_genesis_block(); - - // MorphTx is only accepted from Emerald onwards, so the head must be past it. - let head = head_block(); - client.add_block(head.header.hash_slow(), head); - - client.add_account(SIGNER, ExtendedAccount::new(0, U256::from(eth_balance))); - client.add_account( - L2_TOKEN_REGISTRY_ADDRESS, - ExtendedAccount::new(0, U256::ZERO).extend_storage( - call_mode_registry_storage(TOKEN_ID, FEE_TOKEN) - .map(|(slot, value)| (storage_key(slot), value)), - ), - ); - set_token_balance(&client, token_balance); - client - } - - /// Deploys the call-mode fee token with `token_balance` recorded for [`SIGNER`]. - fn set_token_balance(client: &TestProvider, token_balance: u64) { - client.add_account( - FEE_TOKEN, - ExtendedAccount::new(0, U256::ZERO) - .with_bytecode(alloy_primitives::Bytes::from_static(BALANCE_OF_RUNTIME)) - .extend_storage([( - storage_key(token_balance_key(SIGNER)), - U256::from(token_balance), - )]), - ); - } - - /// A canonical commit of [`head_block`]. - fn commit_event() -> reth_provider::CanonStateNotification { - commit_event_of(head_block()) - } - - /// A canonical commit of `block`. - fn commit_event_of( - block: morph_primitives::Block, - ) -> reth_provider::CanonStateNotification { - reth_provider::CanonStateNotification::Commit { - new: std::sync::Arc::new(reth_provider::Chain::new( - [reth_primitives_traits::RecoveredBlock::new_unhashed( - block, - Vec::new(), - )], - Default::default(), - Default::default(), - )), - } - } - - /// A plain ETH-fee transaction, affordable on its own. - fn legacy_tx(tx_nonce: u64) -> MorphPooledTransaction { - legacy_tx_for_sender(tx_nonce, SIGNER) - } - - fn legacy_tx_for_sender(tx_nonce: u64, sender: Address) -> MorphPooledTransaction { - let tx = TxLegacy { - chain_id: Some(2818), - nonce: tx_nonce, - gas_limit: 21_000, - gas_price: 100, - to: TxKind::Call(address!("0000000000000000000000000000000000000002")), - value: U256::ZERO, + }, ..Default::default() }; - let recovered = Recovered::new_unchecked( - MorphTxEnvelope::Legacy(Signed::new_unhashed(tx, Signature::test_signature())), - sender, - ); - let encoded_len = recovered.encode_2718_len(); - MorphPooledTransaction::new(recovered, encoded_len) - } - - /// Runs the maintenance loop against the provider, as the node does. - fn provider_state(client: TestProvider) -> ProviderFeeState { - ProviderFeeState { - client, - evm_config: MorphEvmConfig::new_with_default_factory(MORPH_MAINNET.clone()), - } - } - - /// A [`FeeStateSource`] with a separate state per block, unlike [`MockEthProvider`], - /// whose state ignores the block hash. `head` is the canonical head. - struct BlockStates { - states: HashMap, - head: SealedHeader, - } - - impl FeeStateSource for BlockStates { - fn state_for( - &self, - header: &morph_primitives::MorphHeader, - ) -> Result { - let client = self - .states - .get(&header.hash_slow()) - .ok_or("no state for this block")?; - crate::validator::validation_state_for_header( - client, - &MorphEvmConfig::new_with_default_factory(MORPH_MAINNET.clone()), - header, - ) - } - - fn canonical_head( - &self, - ) -> Result>, BoxError> { - Ok(Some(self.head.clone())) - } - } - - /// The block after [`head_block`]. - fn next_block() -> morph_primitives::Block { - let mut block = head_block(); - block.header.inner.number = 2; - block.header.inner.timestamp += 1; - block - } - - /// Admits [`token_fee_tx`] 0 while [`SIGNER`] can pay, then runs maintenance on `events` - /// with the sender's tokens drained at [`head_block`] and `head_token_balance` at the - /// canonical head, [`next_block`]. Returns whether the transaction is still pooled. - /// - /// The events go through a tokio broadcast channel, like reth's canonical stream, and the - /// loop runs the way `spawn_critical_blocking_task` runs it: `Handle::block_on` on a - /// blocking thread, where tokio's cooperative budget applies. - fn survives_a_stale_round( - head_token_balance: u64, - events: Vec>, - ) -> bool { - let judged = mock_provider(0, TX_TOKEN_BUDGET); - let validator = crate::MorphTransactionValidator::new( - EthTransactionValidatorBuilder::new( - judged.clone(), - MorphEvmConfig::new_with_default_factory(MORPH_MAINNET.clone()), - ) - .disable_balance_check() - .with_custom_tx_type(morph_primitives::MORPH_TX_TYPE_ID) - .build::(InMemoryBlobStore::default()), - ); - let pool = Pool::new( - validator, - CoinbaseTipOrdering::default(), - InMemoryBlobStore::default(), - Default::default(), - ); - let hash = futures::executor::block_on(pool.add_transaction( - reth_transaction_pool::TransactionOrigin::Local, - token_fee_tx(0), - )) - .unwrap() - .hash; - set_token_balance(&judged, 0); - let head = next_block().header; - let source = BlockStates { - states: HashMap::from([ - (head_block().header.hash_slow(), judged), - (head.hash_slow(), mock_provider(0, head_token_balance)), - ]), - head: SealedHeader::seal_slow(head), + let head1 = MorphHeader { + inner: alloy_consensus::Header { + number: 2, + timestamp: 2_000_000_002, + gas_limit: 30_000_000, + base_fee_per_gas: Some(1), + ..Default::default() + }, + ..Default::default() }; - let (sender, receiver) = tokio::sync::broadcast::channel(events.len()); - for event in events { - sender.send(event).unwrap(); - } - drop(sender); - let events = tokio_stream::wrappers::BroadcastStream::new(receiver) - .map(|event| event.expect("the channel holds every event")); - let runtime = tokio::runtime::Runtime::new().unwrap(); - let handle = runtime.handle().clone(); - let loop_pool = pool.clone(); - let task = runtime.spawn_blocking(move || { - handle.block_on(maintain_morph_pool_with(loop_pool, source, events)) - }); - runtime.block_on(task).unwrap(); - pool.get(&hash).is_some() - } - - #[test] - fn removals_judged_at_an_older_block_are_rechecked_at_the_canonical_head() { - for backlog in [false, true] { - // Without a backlog, the head moved on before its notification arrived. With one, - // 128 notifications exhaust tokio's cooperative budget within a single poll, so the - // loop cannot see the head's notification behind them before it removes anything. - let events = || { - let mut events: Vec<_> = std::iter::repeat_with(commit_event) - .take(if backlog { 128 } else { 1 }) - .collect(); - if backlog { - events.push(commit_event_of(next_block())); - } - events - }; - assert!( - survives_a_stale_round(TX_TOKEN_BUDGET, events()), - "backlog={backlog}: payable at the canonical head, so it must stay" + let make_provider = |token_balance: u64, header: &MorphHeader| { + let p = MockEthProvider::::new() + .with_chain_spec((**MORPH_MAINNET).clone()) + .with_genesis_block(); + p.add_block( + header.hash_slow(), + morph_primitives::Block::new(header.clone(), Default::default()), ); - assert!( - !survives_a_stale_round(0, events()), - "backlog={backlog}: still unpayable at the canonical head, so it must go" - ); - } - } - - #[test] - fn unchanged_head_does_not_evict_newly_admitted_transactions() { - let client = mock_provider(6_300_000, 10_000_000); - client.add_account( - morph_revm::L1_GAS_PRICE_ORACLE_ADDRESS, - ExtendedAccount::new(0, U256::ZERO).extend_storage([ - (storage_key(U256::from(1)), U256::from(1)), - ( - storage_key(U256::from(7)), - U256::from(2_000_000_000_000_000u64), - ), - ]), - ); - let validator = crate::MorphTransactionValidator::new( - EthTransactionValidatorBuilder::new( - client.clone(), - MorphEvmConfig::new_with_default_factory(MORPH_MAINNET.clone()), - ) - .disable_balance_check() - .with_custom_tx_type(morph_primitives::MORPH_TX_TYPE_ID) - .build::(InMemoryBlobStore::default()), - ); - let pool = Pool::new( - validator, - CoinbaseTipOrdering::default(), - InMemoryBlobStore::default(), - Default::default(), - ); - let hashes: Vec<_> = (0..3) - .map(|nonce| { - futures::executor::block_on(pool.add_transaction( - reth_transaction_pool::TransactionOrigin::Local, - legacy_tx(nonce), - )) - .unwrap() - .hash - }) - .collect(); - assert_eq!(pool.all_transactions().pending.len(), 3); - futures::executor::block_on(maintain_morph_pool_with( - pool.clone(), - provider_state(client), - futures::stream::iter([commit_event()]), - )); - assert!(hashes.iter().all(|hash| pool.get(hash).is_some())); - assert_eq!(pool.all_transactions().pending.len(), 3); - } - - #[test] - fn ordinary_only_senders_are_revalidated_when_l1_fees_rise() { - use reth_transaction_pool::TransactionPoolExt; - - let sender = address!("0000000000000000000000000000000000000009"); - // Each ordinary transaction costs 2,100,000 wei before L1 fees. - // A 2,000,000 L1 fee still fits individually at 6,300,000; - // a 5,000,000 L1 fee does not. - for unrelated_morph in [false, true] { - for (l1_fee, eth_balance, first_unaffordable) in [ - (0u64, 6_300_000u64, None), - (2_000_000, 12_300_000, None), - (2_000_000, 6_300_000, None), - (5_000_000, 6_300_000, Some(0usize)), - ] { - let client = mock_provider(10_000_000, 100_000_000); - client.add_account(sender, ExtendedAccount::new(0, U256::from(20_000_000))); - let validator = crate::MorphTransactionValidator::new( - EthTransactionValidatorBuilder::new( - client.clone(), - MorphEvmConfig::new_with_default_factory(MORPH_MAINNET.clone()), - ) - .disable_balance_check() - .with_custom_tx_type(morph_primitives::MORPH_TX_TYPE_ID) - .build::(InMemoryBlobStore::default()), - ); - let pool = Pool::new( - validator, - CoinbaseTipOrdering::default(), - InMemoryBlobStore::default(), - Default::default(), - ); - let ordinary: Vec<_> = (0..3) - .map(|nonce| { - futures::executor::block_on(pool.add_transaction( - reth_transaction_pool::TransactionOrigin::Local, - legacy_tx_for_sender(nonce, sender), - )) - .unwrap() - .hash - }) - .collect(); - if unrelated_morph { - futures::executor::block_on(pool.add_transaction( - reth_transaction_pool::TransactionOrigin::Local, - token_fee_tx(0), - )) - .unwrap(); - } - assert_eq!( - pool.all_transactions().pending.len(), - 3 + usize::from(unrelated_morph) - ); - - client.add_account(sender, ExtendedAccount::new(0, U256::from(eth_balance))); - client.add_account( - morph_revm::L1_GAS_PRICE_ORACLE_ADDRESS, - ExtendedAccount::new(0, U256::ZERO).extend_storage([ - (storage_key(U256::from(1)), U256::from(1)), - ( - storage_key(U256::from(7)), - U256::from(l1_fee) * U256::from(1_000_000_000), - ), - ]), - ); - let event = commit_event(); - pool.on_canonical_state_change(reth_transaction_pool::CanonicalStateUpdate { - new_tip: event.tip(), - pending_block_base_fee: 10, - pending_block_blob_fee: None, - changed_accounts: vec![reth_provider::ChangedAccount { - address: sender, - nonce: 0, - balance: U256::from(eth_balance), - }], - mined_transactions: Vec::new(), - update_kind: reth_transaction_pool::PoolUpdateKind::Commit, - }); - assert_eq!( - pool.all_transactions().pending.len(), - 3 + usize::from(unrelated_morph), - "standard maintenance cannot see the L1 fee shortfall" - ); - - // Later rounds judge the parked descendants on their own, one per round; none - // of them can cover the same L1 fee either. - for _ in 0..3 { - futures::executor::block_on(maintain_morph_pool_with( - pool.clone(), - provider_state(client.clone()), - futures::stream::iter([event.clone()]), - )); - } - let all = pool.all_transactions(); - let pending: Vec<_> = all - .pending - .iter() - .filter(|tx| tx.sender() == sender) - .map(|tx| *tx.hash()) - .collect(); - let queued: Vec<_> = all - .queued - .iter() - .filter(|tx| tx.sender() == sender) - .map(|tx| *tx.hash()) - .collect(); - if let Some(index) = first_unaffordable { - assert!( - pool.get(&ordinary[index]).is_none(), - "remove the first L1-unaffordable ordinary transaction; unrelated MorphTx={unrelated_morph}" - ); - assert_eq!(pending, ordinary[..index]); - assert!( - ordinary[index..] - .iter() - .all(|hash| pool.get(hash).is_none()), - "parked descendants that cannot pay either are removed by later rounds" - ); - assert!(queued.is_empty()); - } else { - assert_eq!(pending, ordinary); - assert!(queued.is_empty()); - } - } - } - } - - #[test] - fn ordinary_only_senders_keep_nonce_gaps_and_eth_parked_transactions() { - use reth_transaction_pool::TransactionPoolExt; - - for (nonces, state_nonce, eth_balance, pending_nonces, queued_nonces) in [ - (vec![0, 2], 0, 3_100_000u64, vec![0], vec![2]), - (vec![5], 0, 3_100_000, vec![], vec![5]), - // Parked behind a gap and unable to cover its L1 fee: removed, not left for later. - (vec![5], 0, 2_100_000, vec![], vec![]), - (vec![0, 1], 0, 2_000_000, vec![], vec![0, 1]), - (vec![0, 1], 1, 3_100_000, vec![1], vec![]), - ] { - let client = mock_provider(10_000_000, 0); - let validator = crate::MorphTransactionValidator::new( - EthTransactionValidatorBuilder::new( - client.clone(), - MorphEvmConfig::new_with_default_factory(MORPH_MAINNET.clone()), - ) - .disable_balance_check() - .with_custom_tx_type(morph_primitives::MORPH_TX_TYPE_ID) - .build::(InMemoryBlobStore::default()), - ); - let pool = Pool::new( - validator, - CoinbaseTipOrdering::default(), - InMemoryBlobStore::default(), - Default::default(), - ); - for nonce in nonces { - futures::executor::block_on(pool.add_transaction( - reth_transaction_pool::TransactionOrigin::Local, - legacy_tx(nonce), - )) - .unwrap(); - } - client.add_account( - SIGNER, - ExtendedAccount::new(state_nonce, U256::from(eth_balance)), - ); - // Every ordinary transaction now owes 1,000,000 wei in L1 fees. - client.add_account( - morph_revm::L1_GAS_PRICE_ORACLE_ADDRESS, - ExtendedAccount::new(0, U256::ZERO).extend_storage([ - (storage_key(U256::from(1)), U256::from(1)), - ( - storage_key(U256::from(7)), - U256::from(1_000_000_000_000_000u64), - ), - ]), - ); - let event = commit_event(); - // Run Morph first to cover a pool snapshot that still contains a mined nonce. - futures::executor::block_on(maintain_morph_pool_with( - pool.clone(), - provider_state(client.clone()), - futures::stream::iter([event.clone()]), - )); - pool.on_canonical_state_change(reth_transaction_pool::CanonicalStateUpdate { - new_tip: event.tip(), - pending_block_base_fee: 10, - pending_block_blob_fee: None, - changed_accounts: vec![reth_provider::ChangedAccount { - address: SIGNER, - nonce: state_nonce, - balance: U256::from(eth_balance), - }], - mined_transactions: Vec::new(), - update_kind: reth_transaction_pool::PoolUpdateKind::Commit, - }); - // And run after reth parks/removes transactions, covering either task order. - futures::executor::block_on(maintain_morph_pool_with( - pool.clone(), - provider_state(client), - futures::stream::iter([event]), - )); - let all = pool.all_transactions(); - assert_eq!( - all.pending.iter().map(|tx| tx.nonce()).collect::>(), - pending_nonces - ); - assert_eq!( - all.queued.iter().map(|tx| tx.nonce()).collect::>(), - queued_nonces + let registry = ExtendedAccount::new(0, U256::ZERO).extend_storage( + call_mode_registry_storage(TOKEN_ID, FEE_TOKEN) + .into_iter() + .map(|(k, v)| (B256::from(k.to_be_bytes::<32>()), v)), ); - } - } + let token = ExtendedAccount::new(0, U256::ZERO) + .with_bytecode(Bytes::from_static(BALANCE_OF_RUNTIME)) + .extend_storage([( + B256::from(token_balance_key(SIGNER).to_be_bytes::<32>()), + U256::from(token_balance), + )]); + p.add_account(L2_TOKEN_REGISTRY_ADDRESS, registry); + p.add_account(FEE_TOKEN, token); + p.add_account(SIGNER, ExtendedAccount::new(0, U256::from(10_000_000u64))); + p + }; - #[test] - fn morph_after_legacy_nonce_is_revalidated_after_token_balance_drops() { - let client = mock_provider(10_000_000, 10 * TX_TOKEN_BUDGET); + // Start with enough tokens for both txs. + let p_initial = make_provider(3 * TX_TOKEN_BUDGET, &head0); let validator = crate::MorphTransactionValidator::new( EthTransactionValidatorBuilder::new( - client.clone(), + p_initial, MorphEvmConfig::new_with_default_factory(MORPH_MAINNET.clone()), ) .disable_balance_check() .with_custom_tx_type(morph_primitives::MORPH_TX_TYPE_ID) + .no_shanghai() + .no_cancun() .build::(InMemoryBlobStore::default()), ); - let pool = Pool::new( + let pool: TestPool = Pool::new( validator, CoinbaseTipOrdering::default(), InMemoryBlobStore::default(), Default::default(), ); - futures::executor::block_on(pool.add_transaction( + // tx0 needs 2*budget in tokens; tx1 needs 1*budget in tokens. + let tx0 = futures::executor::block_on(pool.add_transaction( reth_transaction_pool::TransactionOrigin::Local, - legacy_tx(0), + token_fee_tx(0, TOKEN_ID, U256::ZERO, 42_000), )) - .unwrap(); - let token_tx = futures::executor::block_on(pool.add_transaction( + .unwrap() + .hash; + let tx1 = futures::executor::block_on(pool.add_transaction( reth_transaction_pool::TransactionOrigin::Local, - token_fee_tx(1), + token_fee_tx(1, TOKEN_ID, U256::ZERO, 21_000), )) .unwrap() .hash; assert_eq!(pool.all_transactions().pending.len(), 2); - assert!(pool.all_transactions().queued.is_empty()); - set_token_balance(&client, 0); - futures::executor::block_on(maintain_morph_pool_with( - pool.clone(), - provider_state(client), - futures::stream::iter([commit_event()]), - )); - - assert!( - pool.get(&token_tx).is_none(), - "a pending MorphTx following a legacy nonce must still be checked after its token balance becomes zero" - ); - } - - #[test] - fn ordinary_l1_fee_shortfall_parks_the_morph_successor() { - use reth_transaction_pool::TransactionPoolExt; - - // Two individually affordable predecessors must both survive, even if - // their combined maximum gas and L1 costs exceed the account balance. - for (ordinary_count, l1_fee, eth_balance, token_balance) in [ - (1, 0u64, 2_100_000u64, 0u64), - (1, 1_000_000, 2_100_000, 0), - (1, 1_000_000, 2_100_000, 21_000_000), - (2, 1_000_000, 4_200_000, 21_000_000), - ] { - let client = mock_provider(10_000_000, 10 * TX_TOKEN_BUDGET); - let validator = crate::MorphTransactionValidator::new( - EthTransactionValidatorBuilder::new( - client.clone(), - MorphEvmConfig::new_with_default_factory(MORPH_MAINNET.clone()), + // 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>, + head: SealedHeader, + } + impl FeeStateSource for TwoBlockSource { + fn state_for(&self, header: &MorphHeader) -> Result { + let provider = self + .states + .get(&header.hash_slow()) + .expect("state for header"); + crate::validator::validation_state_for_header( + provider, + &MorphEvmConfig::new_with_default_factory(MORPH_MAINNET.clone()), + header, ) - .disable_balance_check() - .with_custom_tx_type(morph_primitives::MORPH_TX_TYPE_ID) - .build::(InMemoryBlobStore::default()), - ); - let pool = Pool::new( - validator, - CoinbaseTipOrdering::default(), - InMemoryBlobStore::default(), - Default::default(), - ); - let ordinary: Vec<_> = (0..ordinary_count) - .map(|nonce| { - futures::executor::block_on(pool.add_transaction( - reth_transaction_pool::TransactionOrigin::Local, - legacy_tx(nonce), - )) - .unwrap() - .hash - }) - .collect(); - let token_tx = futures::executor::block_on(pool.add_transaction( - reth_transaction_pool::TransactionOrigin::Local, - token_fee_tx(ordinary_count), - )) - .unwrap() - .hash; - assert_eq!(pool.all_transactions().pending.len(), ordinary.len() + 1); - - // All were affordable at admission. The new state still covers reth's - // ordinary transaction cost, but cannot cover the new L1 fee as well. - client.add_account(SIGNER, ExtendedAccount::new(0, U256::from(eth_balance))); - set_token_balance(&client, token_balance); - client.add_account( - morph_revm::L1_GAS_PRICE_ORACLE_ADDRESS, - ExtendedAccount::new(0, U256::ZERO).extend_storage([ - (storage_key(U256::from(1)), U256::from(1)), - ( - storage_key(U256::from(7)), - U256::from(l1_fee) * U256::from(1_000_000_000), - ), - ]), - ); - let mut block = head_block(); - block.header.inner.number = 2; - block.header.inner.timestamp += 1; - client.add_block(block.header.hash_slow(), block.clone()); - let event = reth_provider::CanonStateNotification::Commit { - new: std::sync::Arc::new(reth_provider::Chain::new( - [reth_primitives_traits::RecoveredBlock::new_unhashed( - block, - Vec::new(), - )], - Default::default(), - Default::default(), - )), - }; - // Exercise the same public canonical update used by standard maintenance. - pool.on_canonical_state_change(reth_transaction_pool::CanonicalStateUpdate { - new_tip: event.tip(), - pending_block_base_fee: 10, - pending_block_blob_fee: None, - changed_accounts: vec![reth_provider::ChangedAccount { - address: SIGNER, - nonce: 0, - balance: U256::from(eth_balance), - }], - mined_transactions: Vec::new(), - update_kind: reth_transaction_pool::PoolUpdateKind::Commit, - }); - assert_eq!( - pool.all_transactions().pending.len(), - ordinary.len() + 1, - "standard maintenance does not see L1 costs" - ); - - for _ in 0..3 { - futures::executor::block_on(maintain_morph_pool_with( - pool.clone(), - provider_state(client.clone()), - futures::stream::iter([event.clone()]), - )); } - let all = pool.all_transactions(); - if l1_fee == 0 { - assert!(ordinary.iter().all(|hash| pool.get(hash).is_some())); - assert!( - pool.get(&token_tx).is_none(), - "the unfunded MorphTx is removed" - ); - assert!(all.queued.is_empty()); - } else if ordinary_count == 2 { - assert!(ordinary.iter().all(|hash| pool.get(hash).is_some())); - assert!(pool.get(&token_tx).is_some()); - assert_eq!(all.pending.len(), 3); - assert!(all.queued.is_empty()); - } else { - let (unaffordable, affordable) = ordinary.split_last().unwrap(); - assert!( - pool.get(unaffordable).is_none(), - "the first L1-unaffordable predecessor must be removed" - ); - assert!(affordable.iter().all(|hash| pool.get(hash).is_some())); - assert_eq!(all.pending.len(), affordable.len()); - if token_balance == 0 { - assert!( - pool.get(&token_tx).is_none(), - "a parked successor the sender cannot pay for is removed by a later round" - ); - assert!(all.queued.is_empty()); - } else { - assert_eq!( - all.queued.iter().map(|tx| *tx.hash()).collect::>(), - [token_tx], - "preserve the successor in queued while it still has tokens" - ); - } + fn canonical_head(&self) -> Result>, BoxError> { + Ok(Some(self.head.clone())) } } - } - #[test] - fn removing_a_morph_tx_parks_its_descendants_instead_of_deleting_them() { - let client = mock_provider(10_000_000, 10 * TX_TOKEN_BUDGET); - let validator = crate::MorphTransactionValidator::new( - EthTransactionValidatorBuilder::new( - client.clone(), - MorphEvmConfig::new_with_default_factory(MORPH_MAINNET.clone()), - ) - .disable_balance_check() - .with_custom_tx_type(morph_primitives::MORPH_TX_TYPE_ID) - .build::(InMemoryBlobStore::default()), + let source = TwoBlockSource { + states: HashMap::from([ + (head0.hash_slow(), make_provider(0, &head0)), + (head1.hash_slow(), make_provider(TX_TOKEN_BUDGET, &head1)), + ]), + head: SealedHeader::seal_slow(head1), + }; + + let sealed_block0 = reth_primitives_traits::RecoveredBlock::new_unhashed( + morph_primitives::Block::new(head0, Default::default()), + Vec::new(), ); - let pool = Pool::new( - validator, - CoinbaseTipOrdering::default(), - InMemoryBlobStore::default(), + let chain = Arc::new(reth_provider::Chain::new( + vec![sealed_block0], Default::default(), - ); - - // nonce 0 pays in tokens, nonce 1 is a plain ETH transaction that only depends on - // nonce 0 through the nonce sequence. - let unpayable = futures::executor::block_on(pool.add_transaction( - reth_transaction_pool::TransactionOrigin::Local, - token_fee_tx(0), - )) - .unwrap() - .hash; - let descendant = futures::executor::block_on(pool.add_transaction( - reth_transaction_pool::TransactionOrigin::Local, - legacy_tx(1), - )) - .unwrap() - .hash; + Default::default(), + )); + let event = reth_provider::CanonStateNotification::Commit { new: chain }; - // The sender spends its whole token balance elsewhere, so nonce 0 is no longer payable. - set_token_balance(&client, 0); - let event = commit_event(); futures::executor::block_on(maintain_morph_pool_with( pool.clone(), - provider_state(client), + source, futures::stream::iter([event]), )); - // Without the removal, every early return of the maintenance round would pass the - // descendant check below as well. - assert!( - pool.get(&unpayable).is_none(), - "the transaction the sender can no longer pay for must be removed" - ); - let queued = pool.all_transactions().queued; + assert!(pool.get(&tx0).is_none(), "unaffordable tx0 must be removed"); assert!( - queued.iter().any(|tx| *tx.hash() == descendant), - "an independently affordable ETH-fee successor must be parked, not deleted" + pool.get(&tx1).is_some(), + "tx1 payable at canonical head must survive parked in queued" ); + assert_eq!(pool.all_transactions().pending.len(), 0); + assert_eq!(pool.all_transactions().queued.len(), 1); } + // Ensure `DynDatabase` import is exercised even when tests are trimmed. #[test] - fn a_morph_tx_parked_behind_a_nonce_gap_is_removed_before_the_gap_is_filled() { - let client = mock_provider(10_000_000, 10 * TX_TOKEN_BUDGET); - let validator = crate::MorphTransactionValidator::new( - EthTransactionValidatorBuilder::new( - client.clone(), - MorphEvmConfig::new_with_default_factory(MORPH_MAINNET.clone()), - ) - .disable_balance_check() - .with_custom_tx_type(morph_primitives::MORPH_TX_TYPE_ID) - .build::(InMemoryBlobStore::default()), - ); - let pool = Pool::new( - validator, - CoinbaseTipOrdering::default(), - InMemoryBlobStore::default(), - Default::default(), - ); - - // Admitted while the sender could pay, then parked: nonce 0 is missing. - let parked = futures::executor::block_on(pool.add_transaction( - reth_transaction_pool::TransactionOrigin::Local, - token_fee_tx(1), - )) - .unwrap() - .hash; - assert_eq!(pool.all_transactions().queued.len(), 1); + fn counting_db_reuses_cache_per_round() { + struct CountingDb { + inner: InMemoryDB, + reads: HashMap, + } + impl Database for CountingDb { + type Error = std::convert::Infallible; + 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 { + *self.reads.entry(*address).or_default() += 1; + 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()) + } + } - // The sender spends every token before nonce 0 shows up. - set_token_balance(&client, 0); - futures::executor::block_on(maintain_morph_pool_with( - pool.clone(), - provider_state(client), - futures::stream::iter([commit_event()]), - )); - assert!( - pool.get(&parked).is_none(), - "a parked MorphTx the sender can no longer pay for must be removed" + let mut inner = call_mode_token_state( + TOKEN_ID, + FEE_TOKEN, + SIGNER, + U256::from(TX_TOKEN_BUDGET), + BALANCE_OF_RUNTIME, ); + inner.insert_account_info(&SIGNER, AccountInfo::default()); + let mut db = CountingDb { + inner, + reads: HashMap::new(), + }; + let txs = [ + token_fee_tx(0, TOKEN_ID, U256::ZERO, 21_000), + token_fee_tx(1, TOKEN_ID, U256::ZERO, 21_000), + token_fee_tx(2, TOKEN_ID, U256::ZERO, 21_000), + ]; - // Filling the gap promotes whatever is parked without running the validator again, so - // an unpayable nonce 1 left in place would now be pending and offered to the builder. - futures::executor::block_on(pool.add_transaction( - reth_transaction_pool::TransactionOrigin::Local, - legacy_tx(0), - )) - .unwrap(); - let all = pool.all_transactions(); - assert_eq!( - all.pending.iter().map(|tx| tx.nonce()).collect::>(), - [0] + assert!( + collect_removable_transactions( + &mut db, + &L1BlockInfo::default(), + &test_evm_env(MorphHardfork::Celadon), + 30_000_000, + txs.iter().collect(), + ) + .is_empty() ); - assert!(all.queued.is_empty()); + assert_eq!(db.reads[&L2_TOKEN_REGISTRY_ADDRESS], 5); + assert_eq!(db.reads[&FEE_TOKEN], 1); } } diff --git a/crates/txpool/src/morph_tx_validation.rs b/crates/txpool/src/morph_tx_validation.rs index 4d90a53b..fba0fe6c 100644 --- a/crates/txpool/src/morph_tx_validation.rs +++ b/crates/txpool/src/morph_tx_validation.rs @@ -4,17 +4,19 @@ //! 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::{ - MorphTxEnvelope, + MorphTxEnvelope, TxMorph, transaction::morph_transaction::{MORPH_TX_VERSION_1, MORPH_TX_VERSION_2}, }; -use morph_revm::{MorphEvmEnv, MorphInvalidTransaction, TokenFeeInfo}; -use reth_revm::revm::context::result::EVMError; +use morph_revm::{MorphEvmEnv, TokenFeeInfo}; +use reth_evm::Database; -use crate::{MorphTxError, MorphTxValidationError}; +use crate::{ + MorphTxError, MorphTxValidationError, + state_cache::{StateCache, TokenFeeValidator}, +}; /// High-level input for MorphTx validation. /// @@ -31,10 +33,8 @@ pub struct MorphTxValidationInput<'a> { pub l1_data_fee: U256, /// Current hardfork pub hardfork: MorphHardfork, - /// The environment a call-mode fee token's `balanceOf` is evaluated in. - /// - /// Must be the environment of the block whose state `db` exposes, so admission and - /// maintenance resolve the same balance the execution layer would. + /// Execution environment of the block whose state is read, used if the fee token + /// resolves balances through an EVM `balanceOf` call. pub evm_env: &'a MorphEvmEnv, } @@ -47,6 +47,8 @@ pub struct MorphTxValidationResult { pub token_info: Option, /// The required token amount pub required_token_amount: U256, + /// The amount that will be paid (min of fee_limit and required) + pub amount_to_pay: U256, } /// Validates a MorphTx transaction's token-related fields. @@ -54,36 +56,32 @@ pub struct MorphTxValidationResult { /// This is the main entry point for MorphTx validation. It: /// 1. Validates structural MorphTx rules (`version`, `fee_limit`, memo length, fee ordering) /// 2. Validates ETH balance >= tx.value() (value is still paid in ETH) -/// 3. For `fee_token_id > 0`, validates token balance with REVM-compatible fee_limit semantics +/// 3. For `fee_token_id > 0`, validates token usability and balance with REVM-compatible fee_limit semantics /// 4. For `fee_token_id == 0`, validates ETH can cover full tx cost + L1 data fee /// pub fn validate_morph_tx( db: &mut DB, input: &MorphTxValidationInput<'_>, -) -> Result> { - validate_morph_tx_with_token_info(input, |token_id| { - TokenFeeInfo::load_for_caller(db, token_id, input.sender, input.evm_env) +) -> Result> { + let cache = StateCache::default(); + let mut validator = TokenFeeValidator::new(&cache, db, input.evm_env.clone()); + validate_morph_tx_with(input, |token_id, sender| { + validator.resolve_token_fee_info(token_id, sender) }) } -/// Shared checks with a caller-provided, fixed-state token lookup. -/// Maintenance supplies a per-round cache; admission performs a fresh lookup. -pub(crate) fn validate_morph_tx_with_token_info( - input: &MorphTxValidationInput<'_>, - load_token: impl FnOnce(u16) -> Result, EVMError>, -) -> 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.into()), - }; - - if !input.hardfork.is_jade() && morph_tx.version == MORPH_TX_VERSION_1 { - return Err(MorphTxError::InvalidFormat { +/// Validates MorphTx hardfork version gates (Jade V1 / Celadon V2) without any DB access. +/// +/// 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> { + 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(), - } - .into()); + }); } // V2 (EIP-7702 authorization list) is gated on Celadon. The list itself is @@ -91,20 +89,60 @@ pub(crate) fn validate_morph_tx_with_token_info( // 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(), - } - .into()); + }); } + 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(), - } - .into()); + }); } + 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 +/// `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.into()), + }; + + validate_morph_tx_stateless(morph_tx, input.hardfork)?; + let tx_value = morph_tx.value; if tx_value > input.eth_balance { return Err(MorphTxError::InsufficientEthForValue { @@ -137,35 +175,31 @@ pub(crate) fn validate_morph_tx_with_token_info( uses_token_fee: false, token_info: None, required_token_amount: U256::ZERO, + amount_to_pay: U256::ZERO, }); } - let token_info = load_token(fee_token_id) - .map_err(|err| match err { - EVMError::Database(err) => MorphTxValidationError::State(err), - _ => MorphTxValidationError::Invalid(MorphTxError::TokenBalanceQueryFailed { - token_id: fee_token_id, - }), - })? - .ok_or(MorphTxError::TokenNotFound { - token_id: fee_token_id, - })?; + let token_info = resolve_token(fee_token_id, input.sender)?; - // Check token is active + // Defensive usability guards in case a custom resolver did not check them. if !token_info.is_active { return Err(MorphTxError::TokenNotActive { token_id: fee_token_id, } .into()); } - - // Check price ratio is valid if token_info.price_ratio.is_zero() { return Err(MorphTxError::InvalidPriceRatio { token_id: fee_token_id, } .into()); } + if token_info.scale.is_zero() { + return Err(MorphTxError::InvalidTokenScale { + token_id: fee_token_id, + } + .into()); + } // Txpool admission follows geth's conservative budget check and requires // enough tokens for the max fee cap. Execution still charges the effective price. @@ -192,180 +226,149 @@ pub(crate) fn validate_morph_tx_with_token_info( uses_token_fee: true, token_info: Some(token_info), required_token_amount, + amount_to_pay: required_token_amount, }) } #[cfg(test)] pub(crate) mod tests { use super::*; - - /// The environment the fee-token balance query is evaluated in. - fn test_evm_env(hardfork: MorphHardfork) -> MorphEvmEnv { - MorphEvmEnv::new( - reth_revm::revm::context::CfgEnv::new_with_spec(hardfork), - morph_revm::MorphBlockEnv::default(), - ) - } use alloy_consensus::Signed; use alloy_primitives::{B256, Bytes, Signature, TxKind, address}; + use evm2::bytecode::Bytecode; + use evm2::evm::{AccountInfo, CacheDB, DynDatabase, EmptyDB, InMemoryDB}; use morph_primitives::{TxMorph, transaction::morph_transaction::MORPH_TX_VERSION_1}; use morph_revm::{ L2_TOKEN_REGISTRY_ADDRESS, compute_mapping_slot, compute_mapping_slot_for_address, }; - use reth_revm::revm::database::{CacheDB, EmptyDB}; - use reth_revm::revm::state::{AccountInfo, Bytecode}; - - // --------------------------------------------------------------------------------- - // Fee-token fixtures, shared with the validator and maintenance tests. - // - // Fee tokens are paid in EVM-call mode only: the registry's `balanceSlot` word is zero, - // so every balance read runs the token's `balanceOf` in the EVM. - // --------------------------------------------------------------------------------- - - /// Storage slot of the `balances` mapping that [`BALANCE_OF_RUNTIME`] reads. - pub(crate) const TOKEN_BALANCES_SLOT: u8 = 7; - - /// A fee token answering every call as ERC20 `balanceOf(address)`: - /// `mstore(0, calldataload(4)) mstore(32, 7) mstore(0, sload(keccak256(0, 64))) - /// return(0, 32)`, i.e. `balances[account]` from the mapping at [`TOKEN_BALANCES_SLOT`]. + + /// The environment the fee-token balance query is evaluated in. + pub(crate) fn test_evm_env(hardfork: MorphHardfork) -> MorphEvmEnv { + MorphEvmEnv::new(hardfork, morph_revm::MorphBlockEnv::default(), 2818) + } + + /// Minimal ERC20 `balanceOf(address)` runtime bytecode: + /// + /// Reads `calldataload(4)` (the queried account), hashes `(account, slot 0)` with `KECCAK256`, + /// loads that storage slot, and returns the 32-byte word. pub(crate) const BALANCE_OF_RUNTIME: &[u8] = &[ - 0x60, - 0x04, - 0x35, - 0x5f, - 0x52, // PUSH1 4, CALLDATALOAD, PUSH0, MSTORE - 0x60, - TOKEN_BALANCES_SLOT, - 0x60, - 0x20, - 0x52, // PUSH1 slot, PUSH1 32, MSTORE - 0x60, - 0x40, - 0x5f, - 0x20, - 0x54, // PUSH1 64, PUSH0, KECCAK256, SLOAD - 0x5f, - 0x52, - 0x60, - 0x20, - 0x5f, - 0xf3, // PUSH0, MSTORE, PUSH1 32, PUSH0, RETURN + 0x60, 0x04, // PUSH1 0x04 + 0x35, // CALLDATALOAD -> account (32 bytes, left-padded) + 0x5f, // PUSH0 + 0x52, // MSTORE [0..32] = account + 0x5f, // PUSH0 + 0x60, 0x20, // PUSH1 0x20 + 0x52, // MSTORE [32..64] = 0 (mapping base slot 0) + 0x60, 0x40, // PUSH1 0x40 + 0x5f, // PUSH0 + 0x20, // KECCAK256(0, 64) + 0x54, // SLOAD + 0x5f, // PUSH0 + 0x52, // MSTORE + 0x60, 0x20, // PUSH1 0x20 + 0x5f, // PUSH0 + 0xf3, // RETURN ]; - /// `balanceOf` implementations that do not produce a balance: one reverts, one returns - /// a single byte instead of a word, one halts on `INVALID`. - pub(crate) const FAILING_BALANCE_OF: [&[u8]; 3] = [ - &[0x5f, 0x5f, 0xfd], // PUSH0, PUSH0, REVERT - &[0x60, 0x01, 0x5f, 0xf3], // PUSH1 1, PUSH0, RETURN - &[0xfe], // INVALID + /// Bytecodes that make a call-mode `balanceOf` fail deterministically. + pub(crate) const FAILING_BALANCE_OF: &[(&str, &[u8])] = &[ + ("revert", &[0x5f, 0x5f, 0xfd]), + ("short return", &[0x60, 0x10, 0x5f, 0xf3]), + ("invalid opcode", &[0xfe]), ]; - /// Registry storage registering `token` as active fee token `token_id` in EVM-call mode, - /// with 18 decimals, a scale of 1 and a price ratio of 1. + /// Storage slot of `account`'s balance in the [`BALANCE_OF_RUNTIME`] contract. + pub(crate) fn token_balance_key(account: Address) -> U256 { + compute_mapping_slot_for_address(U256::ZERO, account) + } + + /// 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] { - let mut token_key = [0u8; 32]; - token_key[30..].copy_from_slice(&token_id.to_be_bytes()); - let base = compute_mapping_slot(U256::from(151), &token_key); - let mut active_with_decimals = [0u8; 32]; - active_with_decimals[30] = 18; - active_with_decimals[31] = 1; + 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; // decimals + packed[31] = 1; // is_active = true [ (base, U256::from_be_bytes(token.into_word().0)), - // A zero `balanceSlot` word selects EVM-call mode. - (base + U256::from(1), U256::ZERO), - ( - base + U256::from(2), - U256::from_be_bytes(active_with_decimals), - ), - (base + U256::from(3), U256::from(1)), - ( - compute_mapping_slot(U256::from(153), &token_key), - U256::from(1), - ), + (base + U256::from(1), U256::ZERO), // call mode + (base + U256::from(2), U256::from_be_bytes(packed)), + (base + U256::from(3), U256::ONE), // scale = 1 + (compute_mapping_slot(U256::from(153), &key), U256::ONE), // price_ratio = 1 ] } - /// Key of `account` in the `balances` mapping that [`BALANCE_OF_RUNTIME`] reads. - pub(crate) fn token_balance_key(account: Address) -> U256 { - compute_mapping_slot_for_address(U256::from(TOKEN_BALANCES_SLOT), account) - } - - /// State registering `token` as call-mode fee token `token_id`, whose `balanceOf` runs - /// `code`, with `balance` recorded for `holder` in its `balances` mapping. + /// Builds an in-memory DB containing an active 1:1 call-mode fee token with `runtime` code + /// and `token_balance` for `payer`. pub(crate) fn call_mode_token_state( token_id: u16, token: Address, - code: &'static [u8], - holder: Address, - balance: U256, - ) -> CacheDB { + payer: Address, + token_balance: U256, + runtime: &[u8], + ) -> InMemoryDB { let mut db = CacheDB::new(EmptyDB::default()); for (slot, value) in call_mode_registry_storage(token_id, token) { - db.insert_account_storage(L2_TOKEN_REGISTRY_ADDRESS, slot, value) - .unwrap(); + db.insert_account_storage(&L2_TOKEN_REGISTRY_ADDRESS, &slot, &value); } - let code = Bytecode::new_raw(Bytes::from_static(code)); - db.insert_account_info( - token, - AccountInfo { - code_hash: code.hash_slow(), - code: Some(code), - ..Default::default() - }, - ); - db.insert_account_storage(token, token_balance_key(holder), balance) - .unwrap(); + let code = Bytecode::new_legacy(Bytes::copy_from_slice(runtime)); + db.insert_account_info(&token, AccountInfo::default().with_code(code)); + db.insert_account_storage(&token, &token_balance_key(payer), &token_balance); db } - /// Which read of the fee token [`UnreadableTokenDb`] fails. - #[derive(Debug, Clone, Copy)] + #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) enum TokenRead { - /// Any storage slot of the token. - Storage, - /// The token's code, which the EVM then has to fetch by hash. - Code, + Registry, + TokenAccount, + TokenStorage, + } + + #[derive(Debug, Clone, Copy, PartialEq, Eq)] + pub(crate) struct ReadError(pub(crate) TokenRead); + + impl std::fmt::Display for ReadError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "simulated DB read failure: {:?}", self.0) + } } - /// Fails one kind of read of `token` with a provider error; everything else reads through. - #[derive(Debug)] + impl std::error::Error for ReadError {} + + /// Database wrapper that injects a read error on the chosen target. pub(crate) struct UnreadableTokenDb { - pub(crate) inner: CacheDB, + pub(crate) inner: InMemoryDB, pub(crate) token: Address, - pub(crate) failing: TokenRead, + pub(crate) fail_on: TokenRead, } - impl reth_revm::Database for UnreadableTokenDb { - type Error = reth_provider::ProviderError; + impl Database for UnreadableTokenDb { + type Error = ReadError; - fn basic(&mut self, address: Address) -> Result, Self::Error> { - let mut info = self.inner.basic(address).unwrap(); - if address == self.token && matches!(self.failing, TokenRead::Code) { - // A real provider returns only the code hash; the code is loaded separately. - if let Some(info) = info.as_mut() { - info.code = None; - } + fn get_account(&mut self, address: &Address) -> Result, Self::Error> { + if self.fail_on == TokenRead::TokenAccount && *address == self.token { + return Err(ReadError(TokenRead::TokenAccount)); } - Ok(info) + Ok(DynDatabase::get_account(&mut self.inner, address).unwrap()) } - fn code_by_hash(&mut self, code_hash: B256) -> Result { - let token_code_hash = self.inner.basic(self.token).unwrap().map(|i| i.code_hash); - if matches!(self.failing, TokenRead::Code) && token_code_hash == Some(code_hash) { - return Err(reth_provider::ProviderError::BestBlockNotFound); - } - 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 && matches!(self.failing, TokenRead::Storage) { - return Err(reth_provider::ProviderError::BestBlockNotFound); + fn get_storage(&mut self, address: &Address, index: &U256) -> Result { + if self.fail_on == TokenRead::Registry && *address == L2_TOKEN_REGISTRY_ADDRESS { + return Err(ReadError(TokenRead::Registry)); + } + if self.fail_on == TokenRead::TokenStorage && *address == self.token { + return Err(ReadError(TokenRead::TokenStorage)); } - Ok(self.inner.storage(address, index).unwrap()) + Ok(DynDatabase::get_storage(&mut self.inner, address, index).unwrap()) } - fn block_hash(&mut self, number: u64) -> Result { - Ok(self.inner.block_hash(number).unwrap()) + fn get_block_hash(&mut self, number: &U256) -> Result { + Ok(DynDatabase::get_block_hash(&mut self.inner, number).unwrap()) } } @@ -374,8 +377,8 @@ pub(crate) mod tests { use alloy_consensus::TxEip1559; let sender = address!("1000000000000000000000000000000000000001"); + let env = test_evm_env(MorphHardfork::Viridian); - // Create a dummy EIP-1559 transaction for testing let tx = TxEip1559 { chain_id: 2818, nonce: 0, @@ -396,10 +399,10 @@ pub(crate) mod tests { let input = MorphTxValidationInput { consensus_tx: &envelope, sender, - eth_balance: U256::from(1_000_000_000_000_000_000u128), // 1 ETH + eth_balance: U256::from(1_000_000_000_000_000_000u128), l1_data_fee: U256::from(100_000), hardfork: MorphHardfork::Viridian, - evm_env: &test_evm_env(MorphHardfork::Viridian), + evm_env: &env, }; assert_eq!(input.sender, sender); @@ -411,6 +414,7 @@ pub(crate) mod tests { #[test] fn test_validate_morph_tx_rejects_invalid_format_before_state_checks() { let sender = address!("1000000000000000000000000000000000000001"); + let env = test_evm_env(MorphHardfork::Jade); let tx = TxMorph { chain_id: 2818, nonce: 0, @@ -439,12 +443,11 @@ pub(crate) mod tests { eth_balance: U256::from(1_000_000_000_000_000_000u128), l1_data_fee: U256::ZERO, hardfork: MorphHardfork::Jade, - evm_env: &test_evm_env(MorphHardfork::Jade), + evm_env: &env, }; let mut db = EmptyDB::default(); let err = validate_morph_tx(&mut db, &input).unwrap_err(); - assert_eq!( err, MorphTxValidationError::Invalid(MorphTxError::InvalidFormat { @@ -458,6 +461,7 @@ pub(crate) mod tests { use alloy_consensus::TxEip1559; let sender = address!("1000000000000000000000000000000000000001"); + let env = test_evm_env(MorphHardfork::Jade); let tx = TxEip1559 { chain_id: 2818, nonce: 0, @@ -480,8 +484,8 @@ pub(crate) mod tests { sender, eth_balance: U256::from(1_000_000_000_000_000_000u128), l1_data_fee: U256::ZERO, - hardfork: MorphHardfork::Viridian, - evm_env: &test_evm_env(MorphHardfork::Viridian), + hardfork: MorphHardfork::Jade, + evm_env: &env, }; let mut db = EmptyDB::default(); @@ -493,8 +497,9 @@ pub(crate) mod tests { } #[test] - fn test_validate_morph_tx_insufficient_eth_for_value() { + fn test_validate_morph_tx_v1_rejected_before_jade_as_fork_not_active() { let sender = address!("1000000000000000000000000000000000000001"); + let env = test_evm_env(MorphHardfork::Emerald); let tx = TxMorph { chain_id: 2818, nonce: 0, @@ -502,55 +507,12 @@ pub(crate) mod tests { max_fee_per_gas: 2_000_000_000, max_priority_fee_per_gas: 1_000_000_000, to: TxKind::Call(address!("0000000000000000000000000000000000000002")), - value: U256::from(10u128.pow(18)), // 1 ETH value - access_list: Default::default(), - version: 0, - fee_token_id: 1, - fee_limit: U256::from(1000u64), - 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 input = MorphTxValidationInput { - consensus_tx: &envelope, - sender, - eth_balance: U256::from(100u64), // Insufficient ETH - l1_data_fee: U256::ZERO, - hardfork: MorphHardfork::Viridian, - evm_env: &test_evm_env(MorphHardfork::Viridian), - }; - let mut db = EmptyDB::default(); - - let err = validate_morph_tx(&mut db, &input).unwrap_err(); - assert!(matches!( - err, - MorphTxValidationError::Invalid(MorphTxError::InsufficientEthForValue { .. }) - )); - } - - #[test] - fn test_validate_morph_tx_eth_fee_path_sufficient_balance() { - let sender = address!("1000000000000000000000000000000000000001"); - // fee_token_id = 0 with version 1 (Jade) means ETH-fee path - let tx = TxMorph { - chain_id: 2818, - nonce: 0, - gas_limit: 21_000, - max_fee_per_gas: 1_000_000_000, // 1 Gwei - max_priority_fee_per_gas: 500_000_000, - to: TxKind::Call(address!("0000000000000000000000000000000000000002")), value: U256::ZERO, access_list: Default::default(), version: MORPH_TX_VERSION_1, fee_token_id: 0, fee_limit: U256::ZERO, - reference: None, + reference: Some(B256::ZERO), memo: None, authorization_list: Vec::new(), input: Default::default(), @@ -560,40 +522,39 @@ pub(crate) mod tests { Signature::test_signature(), B256::ZERO, )); - - // gas_fee = 21000 * 1_000_000_000 = 21_000_000_000_000 - // total = gas_fee + l1_data_fee + value = 21_000_000_000_000 + 1000 + 0 let input = MorphTxValidationInput { consensus_tx: &envelope, sender, - eth_balance: U256::from(10u128.pow(18)), // 1 ETH (sufficient) - l1_data_fee: U256::from(1000u64), - hardfork: MorphHardfork::Jade, - evm_env: &test_evm_env(MorphHardfork::Jade), + eth_balance: U256::from(1_000_000_000_000_000_000u128), + l1_data_fee: U256::ZERO, + hardfork: MorphHardfork::Emerald, + evm_env: &env, }; let mut db = EmptyDB::default(); - let result = validate_morph_tx(&mut db, &input).unwrap(); - assert!( - !result.uses_token_fee, - "fee_token_id=0 should use ETH-fee path" + let err = validate_morph_tx(&mut db, &input).unwrap_err(); + assert_eq!( + err, + MorphTxValidationError::Invalid(MorphTxError::ForkNotActive { + reason: "MorphTx version 1 is not yet active (jade fork not reached)".to_string(), + }) ); - assert_eq!(result.required_token_amount, U256::ZERO); } #[test] - fn test_validate_morph_tx_eth_fee_path_insufficient_balance() { + fn test_validate_morph_tx_v2_rejected_before_celadon_as_fork_not_active() { let sender = address!("1000000000000000000000000000000000000001"); + let env = test_evm_env(MorphHardfork::Jade); let tx = TxMorph { chain_id: 2818, nonce: 0, gas_limit: 21_000, - max_fee_per_gas: 1_000_000_000, - max_priority_fee_per_gas: 500_000_000, + max_fee_per_gas: 2_000_000_000, + max_priority_fee_per_gas: 1_000_000_000, to: TxKind::Call(address!("0000000000000000000000000000000000000002")), value: U256::ZERO, access_list: Default::default(), - version: MORPH_TX_VERSION_1, + version: MORPH_TX_VERSION_2, fee_token_id: 0, fee_limit: U256::ZERO, reference: None, @@ -606,186 +567,53 @@ pub(crate) mod tests { Signature::test_signature(), B256::ZERO, )); - - let input = MorphTxValidationInput { - consensus_tx: &envelope, - sender, - eth_balance: U256::from(100u64), // Way too low - l1_data_fee: U256::from(1000u64), - hardfork: MorphHardfork::Jade, - evm_env: &test_evm_env(MorphHardfork::Jade), - }; - let mut db = EmptyDB::default(); - - let err = validate_morph_tx(&mut db, &input).unwrap_err(); - assert!(matches!( - err, - MorphTxValidationError::Invalid(MorphTxError::InsufficientEthForValue { .. }) - )); - } - - #[test] - fn test_validate_morph_tx_token_fee_path_token_not_found() { - let sender = address!("1000000000000000000000000000000000000001"); - let tx = TxMorph { - chain_id: 2818, - nonce: 0, - gas_limit: 21_000, - max_fee_per_gas: 1_000_000_000, - max_priority_fee_per_gas: 500_000_000, - to: TxKind::Call(address!("0000000000000000000000000000000000000002")), - value: U256::ZERO, - access_list: Default::default(), - version: 0, - fee_token_id: 42, // Non-existent token - fee_limit: U256::from(1000u64), - 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 input = MorphTxValidationInput { + let mut input = MorphTxValidationInput { consensus_tx: &envelope, sender, - eth_balance: U256::from(10u128.pow(18)), + eth_balance: U256::from(1_000_000_000_000_000_000u128), l1_data_fee: U256::ZERO, - hardfork: MorphHardfork::Viridian, - evm_env: &test_evm_env(MorphHardfork::Viridian), - }; - let mut db = EmptyDB::default(); - - // EmptyDB has no token registry state, so token lookup will fail - let err = validate_morph_tx(&mut db, &input).unwrap_err(); - assert!( - matches!( - err, - MorphTxValidationError::Invalid(MorphTxError::TokenNotFound { token_id: 42 }) - ), - "expected TokenNotFound {{ token_id: 42 }}, got {err:?}" - ); - } - - fn v2_eth_fee_envelope( - authorization_list: Vec, - ) -> MorphTxEnvelope { - let tx = TxMorph { - chain_id: 2818, - nonce: 0, - gas_limit: 100_000, - max_fee_per_gas: 1_000_000_000, - max_priority_fee_per_gas: 500_000_000, - to: TxKind::Call(address!("0000000000000000000000000000000000000002")), - value: U256::ZERO, - access_list: Default::default(), - version: MORPH_TX_VERSION_2, - fee_token_id: 0, - fee_limit: U256::ZERO, - reference: None, - memo: None, - authorization_list, - input: Default::default(), - }; - MorphTxEnvelope::Morph(Signed::new_unchecked( - tx, - Signature::test_signature(), - B256::ZERO, - )) - } - - fn sample_authorization() -> alloy_eips::eip7702::SignedAuthorization { - alloy_eips::eip7702::Authorization { - chain_id: U256::from(2818), - address: address!("0000000000000000000000000000000000000042"), - nonce: 0, - } - .into_signed(Signature::test_signature()) - } - - #[test] - fn test_validate_morph_tx_v2_rejected_before_celadon() { - let envelope = v2_eth_fee_envelope(vec![sample_authorization()]); - let input = MorphTxValidationInput { - consensus_tx: &envelope, - sender: address!("1000000000000000000000000000000000000001"), - eth_balance: U256::from(10u128.pow(18)), - l1_data_fee: U256::from(1000u64), hardfork: MorphHardfork::Jade, - evm_env: &test_evm_env(MorphHardfork::Jade), + evm_env: &env, }; let mut db = EmptyDB::default(); let err = validate_morph_tx(&mut db, &input).unwrap_err(); - assert!(matches!( + assert_eq!( err, - MorphTxValidationError::Invalid(MorphTxError::InvalidFormat { ref reason }) - if reason == "MorphTx version 2 is not yet active (celadon fork not reached)" - )); - } - - #[test] - fn test_validate_morph_tx_v2_eth_fee_path_accepted_after_celadon() { - let envelope = v2_eth_fee_envelope(vec![sample_authorization()]); - let input = MorphTxValidationInput { - consensus_tx: &envelope, - sender: address!("1000000000000000000000000000000000000001"), - eth_balance: U256::from(10u128.pow(18)), - l1_data_fee: U256::from(1000u64), - hardfork: MorphHardfork::Celadon, - evm_env: &test_evm_env(MorphHardfork::Celadon), - }; - let mut db = EmptyDB::default(); - - let result = validate_morph_tx(&mut db, &input).unwrap(); - assert!(!result.uses_token_fee); - } - - /// A V2 without authorizations is admitted like a V1 (still Celadon-gated). - #[test] - fn test_validate_morph_tx_v2_empty_authorization_list_accepted() { - let envelope = v2_eth_fee_envelope(vec![]); - let mut input = MorphTxValidationInput { - consensus_tx: &envelope, - sender: address!("1000000000000000000000000000000000000001"), - eth_balance: U256::from(10u128.pow(18)), - l1_data_fee: U256::ZERO, - hardfork: MorphHardfork::Celadon, - evm_env: &test_evm_env(MorphHardfork::Celadon), - }; - let mut db = EmptyDB::default(); + MorphTxValidationError::Invalid(MorphTxError::ForkNotActive { + reason: "MorphTx version 2 is not yet active (celadon fork not reached)" + .to_string(), + }) + ); + let celadon_env = test_evm_env(MorphHardfork::Celadon); + input.hardfork = MorphHardfork::Celadon; + input.evm_env = &celadon_env; let result = validate_morph_tx(&mut db, &input).unwrap(); assert!(!result.uses_token_fee); - - input.hardfork = MorphHardfork::Jade; - let err = validate_morph_tx(&mut db, &input).unwrap_err(); - assert!(matches!( - err, - MorphTxValidationError::Invalid(MorphTxError::InvalidFormat { ref reason }) - if reason == "MorphTx version 2 is not yet active (celadon fork not reached)" - )); } const FEE_TOKEN: Address = address!("5300000000000000000000000000000000000042"); const TOKEN_PAYER: Address = address!("1000000000000000000000000000000000000001"); - /// `gas_limit * max_fee_per_gas` of [`token_fee_envelope`]; with the fixtures' 1:1 price - /// ratio and no L1 fee this is also its token requirement. - const TOKEN_FEE: u64 = 21_000 * 100; + const TX_FEE: u64 = 21_000 * 100; fn token_fee_envelope() -> MorphTxEnvelope { let tx = TxMorph { chain_id: 2818, + nonce: 0, gas_limit: 21_000, max_fee_per_gas: 100, max_priority_fee_per_gas: 10, to: TxKind::Call(address!("0000000000000000000000000000000000000002")), + value: U256::ZERO, + access_list: Default::default(), + version: 0, fee_token_id: 1, - ..Default::default() + fee_limit: U256::ZERO, + reference: None, + memo: None, + authorization_list: Vec::new(), + input: Default::default(), }; MorphTxEnvelope::Morph(Signed::new_unchecked( tx, @@ -794,34 +622,32 @@ pub(crate) mod tests { )) } - /// Runs the MorphTx checks for [`token_fee_envelope`] from a sender without ETH. fn validate_token_fee( db: &mut DB, - ) -> Result> { + ) -> Result> { let envelope = token_fee_envelope(); - let evm_env = test_evm_env(MorphHardfork::Jade); + let env = test_evm_env(MorphHardfork::Celadon); let input = MorphTxValidationInput { consensus_tx: &envelope, sender: TOKEN_PAYER, eth_balance: U256::ZERO, l1_data_fee: U256::ZERO, - hardfork: MorphHardfork::Jade, - evm_env: &evm_env, + hardfork: MorphHardfork::Celadon, + evm_env: &env, }; validate_morph_tx(db, &input) } #[test] - fn a_call_mode_token_balance_is_read_through_balance_of() { - let fee = U256::from(TOKEN_FEE); - let mut db = call_mode_token_state(1, FEE_TOKEN, BALANCE_OF_RUNTIME, TOKEN_PAYER, fee); + fn call_mode_token_fee_accepts_sufficient_and_rejects_short_balance() { + let fee = U256::from(TX_FEE); + let mut db = call_mode_token_state(1, FEE_TOKEN, TOKEN_PAYER, fee, BALANCE_OF_RUNTIME); let result = validate_token_fee(&mut db).unwrap(); assert!(result.uses_token_fee); assert_eq!(result.required_token_amount, fee); - assert_eq!(result.token_info.map(|info| info.balance), Some(fee)); - let short = fee - U256::from(1); - let mut db = call_mode_token_state(1, FEE_TOKEN, BALANCE_OF_RUNTIME, TOKEN_PAYER, short); + let short = fee - U256::ONE; + let mut db = call_mode_token_state(1, FEE_TOKEN, TOKEN_PAYER, short, BALANCE_OF_RUNTIME); assert_eq!( validate_token_fee(&mut db).unwrap_err(), MorphTxValidationError::Invalid(MorphTxError::InsufficientTokenBalance { @@ -833,47 +659,50 @@ pub(crate) mod tests { ); } - /// A `balanceOf` that reverts, answers with less than a word or halts yields no balance. - /// That is a verdict on the transaction, but not one that blames the relaying peer. #[test] fn a_balance_query_without_a_balance_is_an_invalid_transaction() { use reth_transaction_pool::error::PoolTransactionError; - for code in FAILING_BALANCE_OF { + for (label, runtime) in FAILING_BALANCE_OF { let mut db = - call_mode_token_state(1, FEE_TOKEN, code, TOKEN_PAYER, U256::from(TOKEN_FEE)); + call_mode_token_state(1, FEE_TOKEN, TOKEN_PAYER, U256::from(TX_FEE), runtime); + let err = validate_token_fee(&mut db).unwrap_err(); assert_eq!( - validate_token_fee(&mut db).unwrap_err(), + err, MorphTxValidationError::Invalid(MorphTxError::TokenBalanceQueryFailed { - token_id: 1 + token_id: 1, }), - "balanceOf code {code:02x?}" + "case {label}" + ); + assert!( + !MorphTxError::TokenBalanceQueryFailed { token_id: 1 }.is_bad_transaction(), + "case {label} must not penalize peers" ); } - assert!(!MorphTxError::TokenBalanceQueryFailed { token_id: 1 }.is_bad_transaction()); } - /// A read failure inside the `balanceOf` call says nothing about the transaction. #[test] - fn an_unreadable_fee_token_is_a_state_error() { - for failing in [TokenRead::Storage, TokenRead::Code] { + fn unreadable_token_state_is_a_state_error() { + for fail_on in [ + TokenRead::Registry, + TokenRead::TokenAccount, + TokenRead::TokenStorage, + ] { let mut db = UnreadableTokenDb { inner: call_mode_token_state( 1, FEE_TOKEN, - BALANCE_OF_RUNTIME, TOKEN_PAYER, - U256::from(TOKEN_FEE), + U256::from(TX_FEE), + BALANCE_OF_RUNTIME, ), token: FEE_TOKEN, - failing, + fail_on, }; + let err = validate_token_fee(&mut db).unwrap_err(); assert!( - matches!( - validate_token_fee(&mut db), - Err(MorphTxValidationError::State(_)) - ), - "{failing:?}" + matches!(err, MorphTxValidationError::State(_)), + "expected State error for {fail_on:?}, got {err:?}" ); } } diff --git a/crates/txpool/src/state_cache.rs b/crates/txpool/src/state_cache.rs new file mode 100644 index 00000000..40a8f943 --- /dev/null +++ b/crates/txpool/src/state_cache.rs @@ -0,0 +1,486 @@ +//! Tip-scoped concurrent state cache and reusable `evm2` token-fee validator for Morph txpool. + +use crate::{MorphTxError, MorphTxValidationError}; +use alloy_primitives::{Address, B256, U256, map::DefaultHashBuilder}; +use dashmap::DashMap; +use evm2::{ + bytecode::Bytecode, + evm::{AccountInfo, Database, Db}, + registry::HandlerError, +}; +use morph_revm::{MorphEvm, MorphEvmEnv, TokenFeeInfo, TokenRegistryEntry, morph_evm}; +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(())` on deterministic EVM query failures + /// (`TokenBalanceQueryFailed`). Transient database read errors (`HandlerError::Database` / + /// `HandlerError::Fatal`) 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. + /// + /// Separates deterministic transaction/token verdicts ([`MorphTxValidationError::Invalid`]) + /// from transient database/provider read failures ([`MorphTxValidationError::State`]). + 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| MorphTxValidationError::State(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 }.into()); + } + if entry.price_ratio.is_zero() { + return Err(MorphTxError::InvalidPriceRatio { token_id }.into()); + } + if entry.scale.is_zero() { + return Err(MorphTxError::InvalidTokenScale { token_id }.into()); + } + + if entry.balance_slot.is_some() { + let balance = entry + .read_caller_balance_with_evm(&mut self.evm, caller) + .map_err(|err| MorphTxValidationError::State(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(()) => Err(MorphTxError::TokenBalanceQueryFailed { token_id }.into()), + }; + } + + 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(MorphTxValidationError::State(err.to_string())), + Err(HandlerError::Fatal(err)) => Err(MorphTxValidationError::State(err.to_string())), + Err(_) => { + self.cache.insert_call_balance((caller, token_id), Err(())); + Err(MorphTxError::TokenBalanceQueryFailed { token_id }.into()) + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use alloy_primitives::{Bytes, address, bytes}; + use evm2::evm::{CacheDB, DynDatabase, EmptyDB, InMemoryDB}; + use morph_chainspec::hardfork::MorphHardfork; + use morph_revm::{L2_TOKEN_REGISTRY_ADDRESS, MorphBlockEnv, 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(), + MorphTxValidationError::Invalid(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` + // and must surface as `MorphTxValidationError::State`. + 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(), + MorphTxValidationError::State(_) + )); + + // 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 as + // `MorphTxValidationError::Invalid(TokenBalanceQueryFailed)`. + 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_eq!( + v3.resolve_token_fee_info(1, caller).unwrap_err(), + MorphTxValidationError::Invalid(MorphTxError::TokenBalanceQueryFailed { + token_id: 1, + }) + ); + } + assert_eq!(revert_reads.load(Ordering::Relaxed), 1); + } +} diff --git a/crates/txpool/src/transaction.rs b/crates/txpool/src/transaction.rs index dca2d3ab..17df6783 100644 --- a/crates/txpool/src/transaction.rs +++ b/crates/txpool/src/transaction.rs @@ -14,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}; @@ -131,6 +132,28 @@ impl PoolTransaction for MorphPooledTransaction { fn encoded_length(&self) -> usize { self.inner.encoded_length } + + fn is_replacement_underpriced( + &self, + replacement: &Self, + price_bumps: &PriceBumpConfig, + ) -> bool { + // 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) + } } impl Typed2718 for MorphPooledTransaction { @@ -417,6 +440,99 @@ mod tests { 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) + } + fn create_morph_pooled_tx_with(fee_token_id: u16, value: U256) -> MorphPooledTransaction { use morph_primitives::TxMorph; let tx = TxMorph { @@ -443,6 +559,85 @@ mod tests { 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 / 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_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. /// /// The pool compares `cost()` against the sender's ETH balance to set the diff --git a/crates/txpool/src/validator.rs b/crates/txpool/src/validator.rs index 96f052d9..a123db10 100644 --- a/crates/txpool/src/validator.rs +++ b/crates/txpool/src/validator.rs @@ -9,21 +9,29 @@ //! - L1 data fee validation //! - MorphTx (0x7F) ERC20 token balance validation -use crate::MorphTxValidationError; +use crate::{ + MorphTxError, MorphTxValidationError, + 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}; use alloy_eips::{Encodable2718, Typed2718}; use alloy_primitives::{Address, B256, U256}; -use morph_chainspec::hardfork::{MorphHardfork, MorphHardforks}; +use morph_chainspec::hardfork::MorphHardforks; use morph_primitives::MorphTxEnvelope; -use morph_revm::{L1BlockInfo, MorphBlockEnv, MorphEvmEnv}; +use morph_revm::{L1BlockInfo, MorphEvmEnv}; use parking_lot::RwLock; use reth_chainspec::ChainSpecProvider; -use reth_evm::{ConfigureEvm, EvmFactory, EvmFactoryFor}; +use reth_evm::{ConfigureEvm, EvmEnvFor, database::StateProviderDatabase}; use reth_primitives_traits::{ - Block, BlockTy, GotExpected, HeaderTy, SealedBlock, transaction::error::InvalidTransactionError, + BlockTy, GotExpected, HeaderTy, SealedBlock, SealedHeader, + transaction::error::InvalidTransactionError, +}; +use reth_storage_api::{ + BlockReaderIdExt, StateProvider as _, StateProviderBox, StateProviderFactory, }; -use reth_revm::database::StateProviderDatabase; -use reth_storage_api::{BlockReaderIdExt, StateProviderBox, StateProviderFactory}; use reth_transaction_pool::{ EthPoolTransaction, EthTransactionValidator, PoolTransaction, TransactionOrigin, TransactionValidationOutcome, TransactionValidator, error::InvalidPoolTransactionError, @@ -32,25 +40,26 @@ use std::sync::Arc; /// 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; -/// A complete set of fee-validation inputs for one block. +/// A complete set of fee-validation inputs and tip-scoped state cache for one block. #[derive(Debug)] pub(crate) struct MorphValidationHead { - hash: B256, - number: u64, - timestamp: u64, - base_fee_per_gas: Option, + pub(crate) hash: B256, + pub(crate) number: u64, + pub(crate) timestamp: u64, + pub(crate) base_fee_per_gas: Option, pub(crate) l1_block_info: L1BlockInfo, pub(crate) evm_env: MorphEvmEnv, + pub(crate) state_cache: Arc, } -/// Tracks L1 fee parameters and the matching block environment. +/// Tracks L1 fee parameters, the matching block environment, and the tip-scoped state cache. /// /// A complete head is published atomically. Readers retain an immutable snapshot while /// later canonical updates prepare and publish a replacement. @@ -91,6 +100,7 @@ impl MorphL1BlockInfo { base_fee_per_gas: header.base_fee_per_gas(), l1_block_info: info, evm_env, + state_cache: Arc::new(StateCache::default()), })); } @@ -123,15 +133,16 @@ impl MorphL1BlockInfo { /// State and fee-validation inputs pinned to one block for a transaction batch. /// -/// Created lazily by [`MorphTransactionValidator::validate_one_with_state`]. Reusing it -/// keeps account reads, token reads and the EVM environment on the same block, even if -/// the canonical head advances. Start with `None` to validate a new batch at the new head. +/// Created lazily by [`MorphTransactionValidator::validate_one_with_state`]; pass the same +/// `&mut Option` across calls in a batch to reuse the state provider, +/// L1 fee parameters, and tip-scoped [`StateCache`]. pub struct MorphValidationState { pub(crate) head: Arc, pub(crate) provider: StateProviderBox, } -/// Opens state, EVM environment and L1 parameters for exactly one header. +/// Opens the state, L1 fee parameters, EVM environment, and a fresh tip-scoped [`StateCache`] +/// for `header`. pub(crate) fn validation_state_for_header( client: &Client, evm_config: &Evm, @@ -140,56 +151,46 @@ pub(crate) fn validation_state_for_header( where Client: StateProviderFactory, Evm: ConfigureEvm, - EvmFactoryFor: EvmFactory, + EvmEnvFor: Into, { - let evm_env = evm_config - .evm_env(header) - .map_err(|err| std::io::Error::other(err.to_string()))?; - let provider = client.state_by_block_hash(header.hash_slow())?; - let l1_block_info = L1BlockInfo::try_fetch( - &mut StateProviderDatabase::new(&provider), - *evm_env.cfg_env.spec(), - )?; + let hash = header.hash_slow(); + let provider = client.state_by_block_hash(hash)?; + let evm_env: MorphEvmEnv = evm_config.evm_env(header)?.into(); + let state_cache = Arc::new(StateCache::default()); + let hardfork = evm_env.spec; + let l1_block_info = { + let evm_state_provider = (&provider).into_evm_state_provider(); + let mut db = StateCacheDb::new( + &state_cache, + StateProviderDatabase::new(&evm_state_provider), + ); + L1BlockInfo::try_fetch(&mut db, hardfork)? + }; + Ok(MorphValidationState { head: Arc::new(MorphValidationHead { - hash: header.hash_slow(), + hash, number: header.number(), timestamp: header.timestamp(), base_fee_per_gas: header.base_fee_per_gas(), l1_block_info, evm_env, + state_cache, }), provider, }) } -impl std::fmt::Debug for MorphValidationState { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("MorphValidationState") - .field("head", &self.head) - .finish_non_exhaustive() - } -} - /// Validator for Morph L2 transactions. /// /// This validator extends [`EthTransactionValidator`] with Morph-specific checks: /// - Rejects EIP-4844 blob transactions (not supported on L2) /// - Rejects L1 message transactions (only included by sequencer) /// - Rejects EIP-7702 transactions before Viridian and MorphTx before Emerald -/// - Enforces the EIP-3860 initcode size limit regardless of Shanghai activation +/// - Enforces EIP-3860 max initcode size regardless of Shanghai activation /// - Validates L1 data fee affordability /// - Validates MorphTx (0x7F) ERC20 token balance and fee_limit /// -/// # MorphTx Validation -/// -/// For token-fee MorphTx (type 0x7F, `fee_token_id > 0`), this validator performs -/// additional checks: -/// 1. Token must be registered and active in L2TokenRegistry -/// 2. Fee limit must be sufficient for the calculated token cost -/// 3. Token balance must cover the fee -/// 4. ETH balance must cover the transaction value (value is still in ETH) -/// /// # Balance Check Configuration /// /// When using MorphTx, the inner `EthTransactionValidator` should have balance @@ -248,19 +249,16 @@ where + BlockReaderIdExt
>, Tx: EthPoolTransaction, Evm: ConfigureEvm, - // Pins the cached environment to Morph's, so the fee-token balance query runs in + // Pins the cached environment to Morph's, so call-mode `balanceOf` runs in // exactly what the execution layer would use. - EvmFactoryFor: EvmFactory, + EvmEnvFor: Into, { /// Create a new [`MorphTransactionValidator`]. pub fn new(inner: EthTransactionValidator) -> Self { let this = Self::with_block_info(inner, MorphL1BlockInfo::default()); - if let Ok(Some(block)) = this - .inner - .client() - .block_by_number_or_tag(alloy_eips::BlockNumberOrTag::Latest) - { - this.update_l1_block_info(block.header()); + if let Ok(Some(header)) = this.inner.client().latest_header() { + this.sync_inner_to_header(header.clone()); + this.update_l1_block_info(header.header()); } this @@ -277,33 +275,92 @@ where } } + /// Synchronizes the inner [`EthTransactionValidator`]'s `block_gas_limit`, + /// `fork_tracker`, and validation gas rules with `header`. + /// + /// Upstream `EthTransactionValidator::on_new_head_block` only inspects the + /// block header, so wrapping the [`SealedHeader`] with an empty default body + /// refreshes inner limits and fork flags without loading a full block body. + fn sync_inner_to_header(&self, header: SealedHeader>) { + let block = + SealedBlock::>::from_sealed_parts(header, Default::default()); + self.inner.on_new_head_block(&block); + } + /// Update the L1 block info for the given header. pub fn update_l1_block_info(&self, header: &HeaderTy) { match validation_state_for_header(self.client(), self.inner.evm_config(), header) { Ok(state) => *self.block_info.head.write() = Some(state.head), Err(err) => { - tracing::warn!(target: "morph::txpool", %err, "Failed to refresh fee-validation head") + // Clear any stale/orphaned head so `current_validation_state` falls back + // to `latest_header()` instead of staying pinned to an unreadable block. + *self.block_info.head.write() = None; + tracing::warn!(target: "morph::txpool", %err, "Failed to refresh fee-validation head"); } } } /// Opens the state of the head last published through `on_new_head_block`. /// - /// Until a head is published, falls back to the provider's latest header without - /// publishing it, so it can never overwrite a newer canonical update. + /// If no head has been published yet, if the canonical tip has moved ahead + /// (for example after a `depth > max_update_depth` catch-up where upstream + /// maintenance skips `on_new_head_block`), or if the cached head's state is + /// no longer available (pruned or orphaned), falls back to the provider's + /// latest canonical header and refreshes the cached head and inner validator + /// without downgrading a newer concurrent `on_new_head_block`. fn current_validation_state( &self, ) -> Result> { - let head = self.block_info.head.read().clone(); - if let Some(head) = head { - let provider = self.client().state_by_block_hash(head.hash)?; - return Ok(MorphValidationState { head, provider }); + let cached_head = self.block_info.head.read().clone(); + let canonical_tip = self.client().chain_info().ok(); + + if let Some(ref head) = cached_head { + let matches_tip = canonical_tip + .as_ref() + .is_none_or(|tip| tip.best_hash.is_zero() || tip.best_hash == head.hash); + if matches_tip { + match self.client().state_by_block_hash(head.hash) { + Ok(provider) => { + return Ok(MorphValidationState { + head: Arc::clone(head), + provider, + }); + } + Err(err) => { + tracing::debug!( + target: "morph::txpool", + cached_hash = %head.hash, + cached_number = head.number, + %err, + "Cached validation head state unavailable; refreshing from latest header" + ); + } + } + } } - let header = self + + let latest = self .client() .latest_header()? .ok_or_else(|| std::io::Error::other("latest validation header is unavailable"))?; - validation_state_for_header(self.client(), self.inner.evm_config(), header.header()) + let state = + validation_state_for_header(self.client(), self.inner.evm_config(), latest.header())?; + + // Publish the refreshed head and sync `self.inner` together under the write lock + // only when no newer `on_new_head_block` raced ahead. + let mut guard = self.block_info.head.write(); + let can_replace = match (guard.as_ref(), cached_head.as_ref()) { + (None, _) => true, + (Some(current), Some(seen)) if current.hash == seen.hash => true, + (Some(current), _) if current.number < state.head.number => true, + _ => false, + }; + if can_replace { + self.sync_inner_to_header(latest); + *guard = Some(Arc::clone(&state.head)); + } + + Ok(state) } /// Validates a single transaction. @@ -328,40 +385,43 @@ where /// Validates a single transaction, reusing a state and head snapshot. /// /// When `state` is `None`, validation opens the state of the head last published by - /// `on_new_head_block`. Both are reused for subsequent transactions in the batch. - /// Reset `state` to `None` to pick up a newer head. + /// `on_new_head_block` (refreshing automatically if the canonical head has moved). Both + /// the provider and the tip-scoped [`StateCache`] are reused for subsequent transactions + /// in the batch. Reset `state` to `None` to pick up a newer head. pub fn validate_one_with_state( &self, origin: TransactionOrigin, transaction: Tx, state: &mut Option, ) -> TransactionValidationOutcome { - // Reject EIP-4844 blob transactions - not supported on L2 - if transaction.is_eip4844() { - return TransactionValidationOutcome::Invalid( - transaction, - InvalidTransactionError::Eip4844Disabled.into(), - ); - } - - // Reject L1 message transactions - only included by sequencer - if is_l1_message(&transaction) { - return TransactionValidationOutcome::Invalid( - transaction, - InvalidTransactionError::TxTypeNotSupported.into(), - ); + if let Some(err) = reject_unsupported_tx_type(&transaction) { + return TransactionValidationOutcome::Invalid(transaction, err); } - if state.is_none() { match self.current_validation_state() { Ok(snapshot) => *state = Some(snapshot), Err(err) => return TransactionValidationOutcome::Error(*transaction.hash(), err), } } - let state = state.as_ref().expect("validation state initialized above"); + let snapshot = state.as_ref().expect("validation state initialized above"); + self.validate_one_with_snapshot(origin, transaction, snapshot, None) + } + + fn validate_one_with_snapshot( + &self, + origin: TransactionOrigin, + transaction: Tx, + state: &MorphValidationState, + mut token_validator: Option<&mut TokenFeeValidator<'_>>, + ) -> TransactionValidationOutcome { + if let Some(err) = reject_unsupported_tx_type(&transaction) { + return TransactionValidationOutcome::Invalid(transaction, err); + } let head = &state.head; - // 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() @@ -369,7 +429,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(), ); } @@ -385,10 +449,30 @@ where { return TransactionValidationOutcome::Invalid( transaction, - InvalidTransactionError::TxTypeNotSupported.into(), + MorphTxError::ForkNotActive { + reason: "MorphTx type is not yet active (emerald fork not reached)".to_string(), + } + .into(), ); } + let hardfork = head.evm_env.spec; + + // 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 fork_gate_res = match transaction.consensus_ref().into_inner() { + MorphTxEnvelope::Morph(signed) => { + validate_morph_tx_fork_gate(signed.tx(), hardfork) + } + _ => Err(MorphTxError::InvalidTokenId), + }; + if let Err(err) = fork_gate_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 @@ -438,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); @@ -457,7 +557,6 @@ where } = outcome { let l1_block_info = head.l1_block_info; - let hardfork = *head.evm_env.cfg_env.spec(); // Calculate L1 data fee (always calculated for all transactions). // Clone consensus tx once — reused for both L1 fee encoding and MorphTx validation. @@ -469,15 +568,25 @@ where if is_morph_tx { // MorphTx: validate structural rules and ERC20 token balance via // 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, - state, - ) { + let validation_res = match token_validator.take() { + Some(validator) => self.validate_morph_tx_balance_with_validator( + &consensus_tx, + sender, + balance, + l1_data_fee, + head, + validator, + ), + None => self.validate_morph_tx_balance( + &consensus_tx, + sender, + balance, + l1_data_fee, + state, + ), + }; + if let Err(err) = validation_res { return morph_tx_validation_outcome(valid_tx.into_transaction(), err); } } else { @@ -501,18 +610,7 @@ where outcome } - /// Validates MorphTx (0x7F) ERC20 token balance and fee_limit. - /// - /// Accepts `&Recovered` directly (already cloned by the caller) - /// to avoid a redundant second `clone_into_consensus()`. - /// - /// This method performs the following checks (reference: go-ethereum tx_pool.go:727-791): - /// 1. Structural MorphTx rules (`version`, `fee_limit`, memo length, fee ordering) - /// 2. ETH balance must be >= transaction value (value is still in ETH) - /// 3. `fee_token_id == 0`: ETH-fee path, require ETH affordability for `cost + l1_fee` - /// 4. `fee_token_id > 0`: token must be registered and active in L2TokenRegistry - /// 5. Token price ratio must be valid (non-zero) - /// 6. Effective token limit must cover required token amount + /// Validates MorphTx (0x7F) ERC20 token balance and fee_limit against `state`. fn validate_morph_tx_balance( &self, consensus_tx: &reth_primitives_traits::Recovered, @@ -520,19 +618,44 @@ where eth_balance: U256, l1_data_fee: U256, state: &MorphValidationState, - ) -> Result> - { - let mut db = StateProviderDatabase::new(&state.provider); + ) -> Result> { + let evm_state_provider = (&state.provider).into_evm_state_provider(); + let mut validator = TokenFeeValidator::new( + &state.head.state_cache, + StateProviderDatabase::new(&evm_state_provider), + state.head.evm_env.clone(), + ); + self.validate_morph_tx_balance_with_validator( + consensus_tx, + sender, + eth_balance, + l1_data_fee, + &state.head, + &mut validator, + ) + } + + fn validate_morph_tx_balance_with_validator( + &self, + consensus_tx: &reth_primitives_traits::Recovered, + sender: Address, + eth_balance: U256, + l1_data_fee: U256, + head: &MorphValidationHead, + token_validator: &mut TokenFeeValidator<'_>, + ) -> Result> { let input = crate::MorphTxValidationInput { consensus_tx, sender, eth_balance, l1_data_fee, - hardfork: *state.head.evm_env.cfg_env.spec(), - evm_env: &state.head.evm_env, + hardfork: head.evm_env.spec, + evm_env: &head.evm_env, }; - let result = crate::validate_morph_tx(&mut db, &input)?; + let result = validate_morph_tx_with(&input, |token_id, caller| { + token_validator.resolve_token_fee_info(token_id, caller) + })?; let token_balance = result .token_info .as_ref() @@ -555,7 +678,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. /// @@ -564,10 +689,48 @@ where &self, transactions: Vec<(TransactionOrigin, Tx)>, ) -> Vec> { - let mut state = None; + if !transactions.iter().any(|(_, tx)| is_morph_tx(tx)) { + let mut state = None; + return transactions + .into_iter() + .map(|(origin, tx)| self.validate_one_with_state(origin, tx, &mut state)) + .collect(); + } + + let snapshot = match self.current_validation_state() { + Ok(snapshot) => snapshot, + Err(err) => { + // Avoid dropping transactions silently; report the same state error per tx. + let message = err.to_string(); + return transactions + .into_iter() + .map(|(_origin, tx)| { + if let Some(err) = reject_unsupported_tx_type(&tx) { + return TransactionValidationOutcome::Invalid(tx, err); + } + TransactionValidationOutcome::Error( + *tx.hash(), + Box::new(std::io::Error::other(message.clone())), + ) + }) + .collect(); + } + }; + + let evm_state_provider = (&snapshot.provider).into_evm_state_provider(); + let mut token_validator = TokenFeeValidator::new( + &snapshot.head.state_cache, + StateProviderDatabase::new(&evm_state_provider), + snapshot.head.evm_env.clone(), + ); + + // Reuse `token_validator` across the whole batch so `MorphEvm` and its pooled frames + // are allocated at most once per batch. transactions .into_iter() - .map(|(origin, tx)| self.validate_one_with_state(origin, tx, &mut state)) + .map(|(origin, tx)| { + self.validate_one_with_snapshot(origin, tx, &snapshot, Some(&mut token_validator)) + }) .collect() } } @@ -579,9 +742,7 @@ where + BlockReaderIdExt
>, Tx: EthPoolTransaction, Evm: ConfigureEvm, - // Pins the cached environment to Morph's, so the fee-token balance query runs in - // exactly what the execution layer would use. - EvmFactoryFor: EvmFactory, + EvmEnvFor: Into, { type Transaction = Tx; type Block = BlockTy; @@ -603,8 +764,35 @@ where } fn on_new_head_block(&self, new_tip_block: &SealedBlock) { + // 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` 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); - self.update_l1_block_info(new_tip_block.header()); + match refreshed { + Ok(state) => *guard = Some(state.head), + Err(err) => { + *guard = None; + tracing::warn!(target: "morph::txpool", %err, "Failed to refresh fee-validation head"); + } + } } } @@ -616,17 +804,15 @@ where /// simply could not be checked — so it is reported as /// [`TransactionValidationOutcome::Error`], which discards this attempt without blaming /// anyone and leaves the sender free to try again. -fn morph_tx_validation_outcome< - Tx: EthPoolTransaction, - E: std::error::Error + Send + Sync + 'static, ->( +fn morph_tx_validation_outcome( transaction: Tx, - err: MorphTxValidationError, + err: MorphTxValidationError, ) -> TransactionValidationOutcome { match err { - MorphTxValidationError::State(err) => { - TransactionValidationOutcome::Error(*transaction.hash(), Box::new(err)) - } + MorphTxValidationError::State(err) => TransactionValidationOutcome::Error( + *transaction.hash(), + Box::new(std::io::Error::other(err)), + ), MorphTxValidationError::Invalid(err) => { TransactionValidationOutcome::Invalid(transaction, err.into()) } @@ -638,6 +824,20 @@ fn is_l1_message(tx: &impl Typed2718) -> bool { tx.ty() == morph_primitives::L1_TX_TYPE_ID } +/// Rejects transaction types that are unconditionally disallowed in the Morph txpool +/// (EIP-4844 blob transactions and L1 message transactions). +fn reject_unsupported_tx_type( + transaction: &Tx, +) -> Option { + if transaction.is_eip4844() { + return Some(InvalidTransactionError::Eip4844Disabled.into()); + } + if is_l1_message(transaction) { + return Some(InvalidTransactionError::TxTypeNotSupported.into()); + } + None +} + /// Helper function to check if a transaction is a MorphTx (0x7F). fn is_morph_tx(tx: &impl Typed2718) -> bool { tx.ty() == morph_primitives::MORPH_TX_TYPE_ID @@ -646,24 +846,29 @@ fn is_morph_tx(tx: &impl Typed2718) -> bool { #[cfg(test)] mod tests { use super::*; - use crate::MorphTxError; + use crate::MorphPooledTransaction; use crate::morph_tx_validation::tests::{ - BALANCE_OF_RUNTIME, FAILING_BALANCE_OF, call_mode_registry_storage, token_balance_key, + BALANCE_OF_RUNTIME, FAILING_BALANCE_OF, call_mode_registry_storage, test_evm_env, + token_balance_key, }; - use alloy_consensus::{Sealable, Signed, TxEip1559, TxLegacy}; + use alloy_consensus::{Signed, TxEip1559, TxLegacy}; use alloy_eips::eip2718::Encodable2718; use alloy_primitives::{B256, Bytes, Signature, TxKind, address}; - use morph_chainspec::{MORPH_MAINNET, MorphChainSpec}; + use morph_chainspec::{MORPH_MAINNET, MorphChainSpec, MorphHardfork}; use morph_evm::MorphEvmConfig; - use morph_primitives::{MorphPrimitives, TxL1Msg, TxMorph}; + use morph_primitives::{MorphHeader, MorphPrimitives, TxL1Msg, TxMorph}; use morph_revm::L2_TOKEN_REGISTRY_ADDRESS; + use reth_chainspec::EthChainSpec; use reth_primitives_traits::Recovered; use reth_provider::test_utils::{ExtendedAccount, MockEthProvider}; use reth_transaction_pool::{ - CoinbaseTipOrdering, LocalTransactionConfig, Pool, TransactionPool, - blobstore::InMemoryBlobStore, validate::EthTransactionValidatorBuilder, + LocalTransactionConfig, blobstore::InMemoryBlobStore, + validate::EthTransactionValidatorBuilder, }; + const FEE_TOKEN: Address = address!("5300000000000000000000000000000000000042"); + const SIGNER: Address = address!("0000000000000000000000000000000000000001"); + fn new_mock_provider() -> MockEthProvider { MockEthProvider::::new() .with_chain_spec((**MORPH_MAINNET).clone()) @@ -674,392 +879,97 @@ mod tests { B256::from(slot.to_be_bytes::<32>()) } - /// The registry account with `token` registered as call-mode fee token `token_id`. - fn token_registry_account(token_id: u16, token: alloy_primitives::Address) -> ExtendedAccount { - ExtendedAccount::new(0, U256::ZERO).extend_storage( + fn call_mode_token_accounts( + token_id: u16, + token: Address, + payer: Address, + token_balance: U256, + runtime: &[u8], + ) -> [(Address, ExtendedAccount); 2] { + let registry = ExtendedAccount::new(0, U256::ZERO).extend_storage( call_mode_registry_storage(token_id, token) - .map(|(slot, value)| (storage_key(slot), value)), - ) + .into_iter() + .map(|(k, v)| (storage_key(k), v)), + ); + 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), + ] } - /// A fee token whose `balanceOf` runs `code`, with `balance` recorded for `holder`. - fn fee_token_account( - code: &'static [u8], - holder: alloy_primitives::Address, - balance: U256, - ) -> ExtendedAccount { - ExtendedAccount::new(0, U256::ZERO) - .with_bytecode(Bytes::from_static(code)) - .extend_storage([(storage_key(token_balance_key(holder)), balance)]) + fn head_at(number: u64, timestamp: u64, gas_limit: u64) -> MorphHeader { + MorphHeader { + inner: alloy_consensus::Header { + number, + timestamp, + gas_limit, + base_fee_per_gas: Some(1), + ..Default::default() + }, + ..Default::default() + } } - type TokenFeeValidator = MorphTransactionValidator< + fn validator_at_head( + client: MockEthProvider, + header: MorphHeader, + tx_fee_cap: u128, + ) -> MorphTransactionValidator< MockEthProvider, - crate::MorphPooledTransaction, + MorphPooledTransaction, MorphEvmConfig, - >; - - /// Registered call-mode token with a 1:1 price ratio at an Emerald-active head. - fn token_fee_validator( - eth_balance: U256, - token_balance: U256, - fee_cap: u128, - local_config: LocalTransactionConfig, - ) -> TokenFeeValidator { - let client = new_mock_provider(); - let signer = address!("0000000000000000000000000000000000000001"); - let token = address!("5300000000000000000000000000000000000042"); - let header = morph_primitives::MorphHeader::from(alloy_consensus::Header { - number: 1, - timestamp: 1_767_765_600, - gas_limit: 30_000_000, - base_fee_per_gas: Some(10), - ..Default::default() - }); - client.add_block( - header.hash_slow(), - morph_primitives::Block { - header, - body: Default::default(), - }, - ); - client.add_account(signer, ExtendedAccount::new(0, eth_balance)); - client.add_account(L2_TOKEN_REGISTRY_ADDRESS, token_registry_account(1, token)); - client.add_account( - token, - fee_token_account(BALANCE_OF_RUNTIME, signer, token_balance), - ); - let inner = EthTransactionValidatorBuilder::new( - client, - MorphEvmConfig::new_with_default_factory(MORPH_MAINNET.clone()), - ) - .disable_balance_check() - .with_custom_tx_type(morph_primitives::MORPH_TX_TYPE_ID) - .set_tx_fee_cap(fee_cap) - .with_local_transactions_config(local_config) - .build::(InMemoryBlobStore::default()); - MorphTransactionValidator::new(inner) + > { + let hash = header.hash_slow(); + let block = morph_primitives::Block::new(header, Default::default()); + client.add_block(hash, block); + let morph_evm_config = MorphEvmConfig::new_with_default_factory(MORPH_MAINNET.clone()); + let eth_validator = EthTransactionValidatorBuilder::new(client, morph_evm_config) + .disable_balance_check() + .with_custom_tx_type(morph_primitives::MORPH_TX_TYPE_ID) + .set_tx_fee_cap(tx_fee_cap) + .with_local_transactions_config(LocalTransactionConfig::default()) + .no_shanghai() + .no_cancun() + .build::(InMemoryBlobStore::default()); + MorphTransactionValidator::new(eth_validator) } - /// Maximum gas fee is 2,100,000 wei; value remains denominated in ETH. - fn token_fee_transaction(tx_nonce: u64, value: U256) -> crate::MorphPooledTransaction { + fn pooled_morph_tx( + version: u8, + fee_token_id: u16, + gas_limit: u64, + max_fee_per_gas: u128, + fee_limit: U256, + value: U256, + ) -> MorphPooledTransaction { let tx = TxMorph { - chain_id: 2818, - nonce: tx_nonce, - gas_limit: 21_000, - max_fee_per_gas: 100, - max_priority_fee_per_gas: 10, + chain_id: MORPH_MAINNET.chain().id(), + nonce: 0, + gas_limit, + max_fee_per_gas, + max_priority_fee_per_gas: max_fee_per_gas, to: TxKind::Call(address!("0000000000000000000000000000000000000002")), value, - fee_token_id: 1, - fee_limit: U256::ZERO, - ..Default::default() - }; - let recovered = Recovered::new_unchecked( - MorphTxEnvelope::Morph(Signed::new_unhashed(tx, Signature::test_signature())), - address!("0000000000000000000000000000000000000001"), - ); - let len = recovered.encode_2718_len(); - crate::MorphPooledTransaction::new(recovered, len) - } - - fn timestamp_sensitive_validator() -> TokenFeeValidator { - let validator = - token_fee_validator(U256::ZERO, U256::from(10_000_000), 0, Default::default()); - let client = validator.client(); - let token = address!("5300000000000000000000000000000000000042"); - // Return 10,000,000 only at the old head's timestamp. The token state stays - // unchanged so both reads of the cached provider must use the old environment. - let old_timestamp = 1_767_765_600u32; - let mut code = vec![0x42, 0x63]; // TIMESTAMP PUSH4 - code.extend_from_slice(&old_timestamp.to_be_bytes()); - code.extend_from_slice(&[ - 0x14, 0x62, 0x98, 0x96, 0x80, 0x02, 0x5f, 0x52, 0x60, 0x20, 0x5f, 0xf3, - ]); - client.add_account( - token, - ExtendedAccount::new(0, U256::ZERO).with_bytecode(code.into()), - ); - - validator - } - - fn replacement_header() -> morph_primitives::MorphHeader { - morph_primitives::MorphHeader::from(alloy_consensus::Header { - number: 1, - timestamp: 1_767_765_601, - gas_limit: 30_000_000, - base_fee_per_gas: Some(10), - ..Default::default() - }) - } - - #[test] - fn a_head_published_during_validation_does_not_change_the_balance_query() { - let mut validator = timestamp_sensitive_validator(); - let block_info = validator.block_info().clone(); - let client = validator.client().clone(); - let replacement = replacement_header(); - let env = MorphEvmConfig::new_with_default_factory(MORPH_MAINNET.clone()) - .evm_env(&replacement) - .unwrap(); - // This extension runs after the account read and before Morph fee validation, - // forcing the interleaving of a concurrent canonical-head publication. - validator - .inner - .set_additional_stateful_validation(move |_, _, _| { - client - .blocks - .lock() - .retain(|_, block| block.header.number() != replacement.number()); - client - .headers - .lock() - .retain(|_, header| header.number() != replacement.number()); - client.add_block( - replacement.hash_slow(), - morph_primitives::Block { - header: replacement.clone(), - body: Default::default(), - }, - ); - block_info.update(L1BlockInfo::default(), &replacement, env.clone()); - Ok(()) - }); - let tx = token_fee_transaction(0, U256::ZERO); - let in_flight = validator.validate_one(TransactionOrigin::Local, tx.clone()); - assert!( - matches!(in_flight, TransactionValidationOutcome::Valid { .. }), - "an in-flight validation must retain its original head: {in_flight:?}" - ); - let fresh = validator.validate_one(TransactionOrigin::Local, tx); - assert!( - matches!(fresh, TransactionValidationOutcome::Invalid(..)), - "a fresh validation must see the published head: {fresh:?}" - ); - } - - /// A `balanceOf` that yields no balance rejects the transaction without blaming the - /// peer that relayed it: the fault lies with the token, not the sender. - #[test] - fn a_failing_balance_query_is_rejected_without_penalizing_the_peer() { - for code in FAILING_BALANCE_OF { - let validator = - token_fee_validator(U256::ZERO, U256::from(10_000_000), 0, Default::default()); - validator.client().add_account( - address!("5300000000000000000000000000000000000042"), - fee_token_account( - code, - address!("0000000000000000000000000000000000000001"), - U256::from(10_000_000), - ), - ); - let outcome = validator.validate_one( - TransactionOrigin::External, - token_fee_transaction(0, U256::ZERO), - ); - let err = match outcome { - TransactionValidationOutcome::Invalid(_, err) => err, - other => panic!("balanceOf code {code:02x?}: {other:?}"), - }; - assert_eq!( - err.downcast_other_ref::(), - Some(&MorphTxError::TokenBalanceQueryFailed { token_id: 1 }), - "balanceOf code {code:02x?}" - ); - assert_eq!( - err.as_other().map(|other| other.is_bad_transaction()), - Some(false), - "balanceOf code {code:02x?}" - ); - } - } - - #[test] - fn token_fee_transaction_above_local_fee_cap_is_rejected() { - // The effective gas price is 20, so only the maximum fee budget exceeds this cap. - let validator = token_fee_validator( - U256::ZERO, - U256::from(10_000_000), - 500_000, - Default::default(), - ); - let outcome = validator.validate_one( - TransactionOrigin::Local, - token_fee_transaction(0, U256::ZERO), - ); - assert!( - matches!( - outcome, - TransactionValidationOutcome::Invalid( - _, - InvalidPoolTransactionError::ExceedsFeeCap { - max_tx_fee_wei: 2_100_000, - tx_fee_cap_wei: 500_000, - } - ) - ), - "{outcome:?}" - ); - } - - #[test] - fn token_fee_cap_accepts_zero_or_sufficient_cap_without_counting_value() { - for cap in [0, 2_100_000, 2_100_001] { - let validator = token_fee_validator( - U256::from(7), - U256::from(10_000_000), - cap, - Default::default(), - ); - let outcome = validator.validate_one( - TransactionOrigin::Local, - token_fee_transaction(0, U256::from(7)), - ); - assert!( - matches!(outcome, TransactionValidationOutcome::Valid { .. }), - "cap={cap}: {outcome:?}" - ); - } - } - - #[test] - fn token_fee_cap_respects_local_transaction_configuration() { - let local_sender = LocalTransactionConfig { - local_addresses: [address!("0000000000000000000000000000000000000001")] - .into_iter() - .collect(), - ..Default::default() + access_list: Default::default(), + version, + fee_token_id, + fee_limit, + reference: None, + memo: None, + authorization_list: Vec::new(), + input: Bytes::new(), }; - for (origin, config, should_reject) in [ - ( - TransactionOrigin::External, - LocalTransactionConfig::default(), - false, - ), - (TransactionOrigin::External, local_sender.clone(), true), - ( - TransactionOrigin::Local, - LocalTransactionConfig { - no_exemptions: true, - ..Default::default() - }, - false, - ), - ( - TransactionOrigin::External, - LocalTransactionConfig { - no_exemptions: true, - ..local_sender - }, - false, - ), - ] { - let validator = token_fee_validator(U256::ZERO, U256::from(10_000_000), 100, config); - let outcome = validator.validate_one(origin, token_fee_transaction(0, U256::ZERO)); - if should_reject { - assert!( - matches!( - outcome, - TransactionValidationOutcome::Invalid( - _, - InvalidPoolTransactionError::ExceedsFeeCap { .. } - ) - ), - "{outcome:?}" - ); - } else { - assert!( - matches!(outcome, TransactionValidationOutcome::Valid { .. }), - "{outcome:?}" - ); - } - } - } - - #[test] - fn token_fee_transaction_with_zero_eth_is_pending_and_selectable() { - let validator = token_fee_validator( - U256::ZERO, - U256::from(10_000_000), - 2_100_000, - Default::default(), - ); - let pool = Pool::new( - validator, - CoinbaseTipOrdering::default(), - InMemoryBlobStore::default(), - Default::default(), - ); - let added = futures::executor::block_on(pool.add_transaction( - TransactionOrigin::Local, - token_fee_transaction(0, U256::ZERO), - )) - .unwrap(); - let all = pool.all_transactions(); - assert_eq!(all.pending.len(), 1); - assert!(all.queued.is_empty()); - let best: Vec<_> = pool.best_transactions().map(|tx| *tx.hash()).collect(); - assert_eq!(best, [added.hash]); - } - - #[test] - fn token_fee_transactions_still_reserve_cumulative_eth_value() { - let validator = token_fee_validator( - U256::from(10), - U256::from(10_000_000), - 2_100_000, - Default::default(), - ); - let pool = Pool::new( - validator, - CoinbaseTipOrdering::default(), - InMemoryBlobStore::default(), - Default::default(), - ); - for nonce in [0, 1] { - futures::executor::block_on(pool.add_transaction( - TransactionOrigin::Local, - token_fee_transaction(nonce, U256::from(7)), - )) - .unwrap(); - } - let all = pool.all_transactions(); - assert_eq!(all.pending.len(), 1); - assert_eq!(all.pending[0].nonce(), 0); - assert_eq!(all.queued.len(), 1); - assert_eq!(all.queued[0].nonce(), 1); - let best: Vec<_> = pool.best_transactions().map(|tx| tx.nonce()).collect(); - assert_eq!(best, [0]); - } - - #[test] - fn an_unreadable_fee_token_state_is_an_error_not_an_invalid_transaction() { - let tx = token_fee_transaction(0, U256::ZERO); - let hash = *tx.hash(); - - let outcome = morph_tx_validation_outcome( + let envelope = MorphTxEnvelope::Morph(Signed::new_unchecked( tx, - MorphTxValidationError::State(std::io::Error::other("provider unavailable")), - ); - assert!( - matches!(outcome, TransactionValidationOutcome::Error(reported, _) if reported == hash), - "a failed state read must not mark the transaction known-bad: {outcome:?}" - ); - } - - #[test] - fn a_real_fee_token_failure_is_still_an_invalid_transaction() { - let outcome = morph_tx_validation_outcome( - token_fee_transaction(0, U256::ZERO), - MorphTxValidationError::::Invalid(MorphTxError::TokenNotActive { - token_id: 1, - }), - ); - assert!( - matches!(outcome, TransactionValidationOutcome::Invalid(..)), - "{outcome:?}" - ); + Signature::test_signature(), + B256::ZERO, + )); + let recovered = Recovered::new_unchecked(envelope, SIGNER); + let len = recovered.encode_2718_len(); + MorphPooledTransaction::new(recovered, len) } #[test] @@ -1067,323 +977,288 @@ mod tests { let info = MorphL1BlockInfo::new(); assert_eq!(info.timestamp(), 0); assert_eq!(info.number(), 0); + assert_eq!(info.base_fee_per_gas(), None); } #[test] fn test_morph_l1_block_info_update() { let info = MorphL1BlockInfo::new(); - let l1_info = L1BlockInfo::default(); - let header = morph_primitives::MorphHeader::from(alloy_consensus::Header { - timestamp: 1234, - number: 100, - base_fee_per_gas: Some(42), - ..Default::default() - }); - let evm_env = MorphEvmConfig::new_with_default_factory(MORPH_MAINNET.clone()) - .evm_env(&header) - .unwrap(); - info.update(l1_info, &header, evm_env); + let header = head_at(100, 1234, 30_000_000); + info.update( + L1BlockInfo::default(), + &header, + test_evm_env(MorphHardfork::Celadon), + ); assert_eq!(info.timestamp(), 1234); assert_eq!(info.number(), 100); - assert_eq!(info.base_fee_per_gas(), Some(42)); + assert_eq!(info.base_fee_per_gas(), Some(1)); } #[test] fn validate_l1_message_rejected() { - // Create validator with mock provider let client = new_mock_provider(); 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) + let eth_validator = EthTransactionValidatorBuilder::new(client, morph_evm_config) .no_shanghai() .no_cancun() - .build::(InMemoryBlobStore::default()); + .build::(InMemoryBlobStore::default()); let validator = MorphTransactionValidator::new(eth_validator); - let origin = TransactionOrigin::External; - let signer = address!("0000000000000000000000000000000000000001"); - - // Create L1 message transaction (type 0x7E) let l1_msg_tx = TxL1Msg { queue_index: 0, gas_limit: 21_000, to: address!("0000000000000000000000000000000000000002"), value: U256::ZERO, input: Default::default(), - sender: signer, + sender: SIGNER, }; let envelope = MorphTxEnvelope::L1Msg(alloy_consensus::Sealed::new_unchecked( l1_msg_tx, B256::ZERO, )); - let recovered = Recovered::new_unchecked(envelope, signer); + let recovered = Recovered::new_unchecked(envelope, SIGNER); let len = recovered.encode_2718_len(); - let pooled_tx = crate::MorphPooledTransaction::new(recovered, len); + let pooled_tx = MorphPooledTransaction::new(recovered, len); + + let outcome = validator.validate_one(TransactionOrigin::External, pooled_tx); + assert!(outcome.is_invalid()); + } - // Validate and check rejection - let outcome = validator.validate_one(origin, pooled_tx); + #[test] + fn fork_not_active_rejections_do_not_penalize_peers() { + use alloy_primitives::TxHash; + use reth_transaction_pool::error::PoolError; - let err = match outcome { - TransactionValidationOutcome::Invalid(_, err) => err, - _ => panic!("Expected invalid transaction for L1 message"), + let client = new_mock_provider(); + client.add_account(SIGNER, ExtendedAccount::new(0, U256::from(10u128.pow(18)))); + // Timestamp 0 is before Viridian, Emerald, Jade, and Celadon on mainnet. + let validator = validator_at_head(client, head_at(1, 0, 30_000_000), 0); + + // Pre-Emerald MorphTx -> ForkNotActive, not bad tx. + let tx = pooled_morph_tx(0, 0, 21_000, 1_000_000, U256::ZERO, U256::ZERO); + let outcome = validator.validate_one(TransactionOrigin::External, tx); + let TransactionValidationOutcome::Invalid(_, err) = outcome else { + panic!("expected pre-Emerald MorphTx to be rejected"); }; - assert_eq!(err.to_string(), "transaction type not supported"); + assert!(!PoolError::new(TxHash::ZERO, err).is_bad_transaction()); } #[test] - fn validate_valid_eip1559_transaction() { - // Create validator with mock provider and disable balance check for simplicity + fn malformed_morph_tx_rejected_before_stateful_validation() { let client = new_mock_provider(); - let signer = address!("0000000000000000000000000000000000000001"); - client.add_account(signer, ExtendedAccount::new(0, U256::from(10u128.pow(18)))); - 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); + // Post-Celadon timestamp (way in the future) so fork gates pass. + let validator = validator_at_head(client, head_at(1, 2_000_000_000, 30_000_000), 0); + // Invalid format: fee_token_id == 0 with non-zero fee_limit (V1). + let tx = pooled_morph_tx(1, 0, 21_000, 1_000_000, U256::from(1u64), U256::ZERO); + let outcome = validator.validate_one(TransactionOrigin::External, tx); + let TransactionValidationOutcome::Invalid(_, err) = outcome else { + panic!("expected malformed MorphTx to be rejected"); + }; + assert!( + err.to_string().contains("invalid MorphTx format"), + "expected InvalidFormat before stateful check, got: {err}" + ); + } - let origin = TransactionOrigin::External; + #[test] + fn morph_tx_tip_above_fee_cap_returns_standard_non_penalizing_error() { + use alloy_primitives::TxHash; + use reth_transaction_pool::error::PoolError; - // Create valid EIP-1559 transaction - let tx = TxEip1559 { - chain_id: 2818, + 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, - input: Default::default(), - max_fee_per_gas: 2_000_000_000, - max_priority_fee_per_gas: 1_000_000_000, 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 signature = Signature::test_signature(); - let signed_tx = Signed::new_unchecked(tx, signature, B256::ZERO); - let envelope = MorphTxEnvelope::Eip1559(signed_tx); - let recovered = Recovered::new_unchecked(envelope, signer); + 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_tx = crate::MorphPooledTransaction::new(recovered, len); - - // Validate and check acceptance - let outcome = validator.validate_one(origin, pooled_tx); + let pooled = MorphPooledTransaction::new(recovered, len); - match outcome { - TransactionValidationOutcome::Valid { .. } => { - // Success - transaction was accepted - } - TransactionValidationOutcome::Invalid(_, err) => { - panic!("Expected valid transaction, got invalid: {err}"); - } - TransactionValidationOutcome::Error(_, err) => { - panic!("Expected valid transaction, got error: {err:?}"); - } - } + 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 validate_valid_legacy_transaction() { - // Create validator with mock provider and disable balance check for simplicity + fn local_token_fee_morph_tx_still_enforces_tx_fee_cap() { let client = new_mock_provider(); - let signer = address!("0000000000000000000000000000000000000001"); - client.add_account(signer, ExtendedAccount::new(0, U256::from(10u128.pow(18)))); - 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); - - let origin = TransactionOrigin::External; - - // Create valid Legacy transaction - let tx = TxLegacy { - chain_id: Some(2818), - nonce: 0, - gas_limit: 21_000, - to: TxKind::Call(address!("0000000000000000000000000000000000000002")), - value: U256::ZERO, - input: Default::default(), - gas_price: 2_000_000_000, - }; - let signature = Signature::test_signature(); - let signed_tx = Signed::new_unchecked(tx, signature, B256::ZERO); - let envelope = MorphTxEnvelope::Legacy(signed_tx); - let recovered = Recovered::new_unchecked(envelope, signer); - let len = recovered.encode_2718_len(); - let pooled_tx = crate::MorphPooledTransaction::new(recovered, len); - - // Validate and check acceptance - let outcome = validator.validate_one(origin, pooled_tx); + for (addr, acc) in call_mode_token_accounts( + 1, + FEE_TOKEN, + SIGNER, + U256::from(10u128.pow(18)), + BALANCE_OF_RUNTIME, + ) { + client.add_account(addr, acc); + } + 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 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 { .. } + ) + )); + } - match outcome { - TransactionValidationOutcome::Valid { .. } => { - // Success - transaction was accepted - } - TransactionValidationOutcome::Invalid(_, err) => { - panic!("Expected valid transaction, got invalid: {err}"); - } - TransactionValidationOutcome::Error(_, err) => { - panic!("Expected valid transaction, got error: {err:?}"); + #[test] + fn call_mode_token_fee_validation_and_reverts() { + for (label, runtime) in FAILING_BALANCE_OF { + let client = new_mock_provider(); + for (addr, acc) in + call_mode_token_accounts(1, FEE_TOKEN, SIGNER, U256::from(10_000_000u64), runtime) + { + client.add_account(addr, acc); } + client.add_account(SIGNER, ExtendedAccount::new(0, U256::ZERO)); + let validator = validator_at_head(client, head_at(1, 2_000_000_000, 30_000_000), 0); + let tx = pooled_morph_tx(0, 1, 21_000, 100, U256::ZERO, U256::ZERO); + let outcome = validator.validate_one(TransactionOrigin::External, tx); + let TransactionValidationOutcome::Invalid(_, err) = outcome else { + panic!("expected invalid outcome for failing balanceOf case {label}"); + }; + assert!(err.to_string().contains("balanceOf failed")); } } - /// EIP-3860 mempool admission: contract creation transactions whose initcode - /// exceeds 49 152 bytes must be rejected. This used to slip through because - /// morph-mainnet/hoodi genesis use the non-standard `shanghaiBlock` field - /// (inherited from scroll-tech go-ethereum) that alloy's `Genesis` parser - /// ignores, leaving Shanghai un-registered in the hardforks table and - /// `is_shanghai_active_at_timestamp` permanently `false` — which means reth's - /// Shanghai-gated EIP-3860 check (`EthTransactionValidator::validate_stateless`) is - /// always skipped. The rejection is therefore enforced unconditionally by - /// `MorphTransactionValidator` itself (see `validate_one_with_state`), not by - /// the chainspec or the inner reth validator. #[test] - fn validate_rejects_oversized_initcode() { + fn stale_head_auto_refreshes_when_canonical_tip_advances() { let client = new_mock_provider(); - let signer = address!("0000000000000000000000000000000000000001"); - client.add_account(signer, ExtendedAccount::new(0, U256::from(10u128.pow(18)))); - let morph_evm_config = MorphEvmConfig::new_with_default_factory(MORPH_MAINNET.clone()); - - // Built from the real `MORPH_MAINNET` chainspec, under which Shanghai is - // never active, so the inner `EthTransactionValidator` does not enforce - // EIP-3860. This test verifies that `MorphTransactionValidator` rejects - // the oversized initcode on its own. - let eth_validator: EthTransactionValidator< - _, - crate::MorphPooledTransaction, - MorphEvmConfig, - > = EthTransactionValidatorBuilder::new(client, morph_evm_config) - .disable_balance_check() - .build::(InMemoryBlobStore::default()); - let validator = MorphTransactionValidator::new(eth_validator); - - let oversize_initcode = vec![0u8; MAX_INITCODE_SIZE + 1]; - let tx = TxLegacy { - chain_id: Some(2818), - nonce: 0, - gas_limit: 30_000_000, - to: TxKind::Create, - value: U256::ZERO, - input: oversize_initcode.into(), - gas_price: 2_000_000_000, - }; - let signed_tx = Signed::new_unchecked(tx, Signature::test_signature(), B256::ZERO); - let envelope = MorphTxEnvelope::Legacy(signed_tx); - let recovered = Recovered::new_unchecked(envelope, signer); - let len = recovered.encode_2718_len(); - let pooled_tx = crate::MorphPooledTransaction::new(recovered, len); + client.add_account(SIGNER, ExtendedAccount::new(0, U256::from(10u128.pow(18)))); + // Start at timestamp 0 (pre-Emerald), with block gas limit 100_000. + let validator = validator_at_head(client.clone(), head_at(1, 0, 100_000), 0); + assert_eq!(validator.block_info().number(), 1); + + // Advance canonical tip in provider WITHOUT calling `on_new_head_block` + // (simulating deep catch-up where upstream maintenance skips `on_new_head_block`). + let new_header = head_at(50, 2_000_000_000, 30_000_000); + let new_hash = new_header.hash_slow(); + client.add_block( + new_hash, + morph_primitives::Block::new(new_header, Default::default()), + ); - let outcome = validator.validate_one(TransactionOrigin::External, pooled_tx); + // A post-Celadon MorphTx with gas_limit 200_000 (above old 100_000 limit!) must now pass + // because `current_validation_state` refreshes both `block_info` and `self.inner`. + let tx = pooled_morph_tx(2, 0, 200_000, 100, U256::ZERO, U256::ZERO); + let outcome = validator.validate_one(TransactionOrigin::Local, tx); + assert!( + outcome.is_valid(), + "expected stale validation head to auto-refresh, got {outcome:?}" + ); + assert_eq!(validator.block_info().number(), 50); - match outcome { - TransactionValidationOutcome::Invalid(_, err) => { - let msg = err.to_string(); - assert!( - msg.contains("max_init_code_size") || msg.contains("init code size"), - "expected EIP-3860 rejection, got: {msg}" - ); - } - other => panic!("expected oversized initcode to be rejected, got: {other:?}"), - } + // 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() + ); } - /// Counterpart to `validate_rejects_oversized_initcode`: an initcode - /// exactly at the EIP-3860 limit (49 152 bytes) must still be admitted. #[test] - fn validate_accepts_initcode_at_limit() { + fn post_viridian_calldata_heavy_tx_accepted_without_eip7623_floor_gas() { let client = new_mock_provider(); - let signer = address!("0000000000000000000000000000000000000001"); - client.add_account(signer, ExtendedAccount::new(0, U256::from(10u128.pow(18)))); - 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) - .disable_balance_check() - .build::(InMemoryBlobStore::default()); - let validator = MorphTransactionValidator::new(eth_validator); + client.add_account(SIGNER, ExtendedAccount::new(0, U256::from(10u128.pow(18)))); + let validator = validator_at_head(client, head_at(1, 2_000_000_000, 30_000_000), 0); - let initcode_at_limit = vec![0u8; MAX_INITCODE_SIZE]; - let tx = TxLegacy { - chain_id: Some(2818), + // 1,024 non-zero calldata bytes: + // - standard intrinsic gas: 21_000 + 16 * 1_024 = 37_384 + // - EIP-7623 floor gas: 21_000 + 40 * 1_024 = 61_960 + let tx = TxEip1559 { + chain_id: MORPH_MAINNET.chain().id(), nonce: 0, - gas_limit: 30_000_000, - to: TxKind::Create, + gas_limit: 40_000, + max_fee_per_gas: 1_000_000, + max_priority_fee_per_gas: 100, + to: TxKind::Call(address!("0000000000000000000000000000000000000002")), value: U256::ZERO, - input: initcode_at_limit.into(), - gas_price: 2_000_000_000, + access_list: Default::default(), + input: Bytes::from(vec![0xab; 1_024]), }; - let signed_tx = Signed::new_unchecked(tx, Signature::test_signature(), B256::ZERO); - let envelope = MorphTxEnvelope::Legacy(signed_tx); - let recovered = Recovered::new_unchecked(envelope, signer); + let envelope = MorphTxEnvelope::Eip1559(Signed::new_unchecked( + tx, + Signature::test_signature(), + B256::ZERO, + )); + let recovered = Recovered::new_unchecked(envelope, SIGNER); let len = recovered.encode_2718_len(); - let pooled_tx = crate::MorphPooledTransaction::new(recovered, len); + let pooled = MorphPooledTransaction::new(recovered, len); - let outcome = validator.validate_one(TransactionOrigin::External, pooled_tx); - // The validator may still reject this because of intrinsic gas or - // balance checks downstream; the only thing this test asserts is that - // EIP-3860 itself does NOT fire at exactly the limit. - if let TransactionValidationOutcome::Invalid(_, err) = &outcome { - let msg = err.to_string(); - assert!( - !msg.contains("max_init_code_size") && !msg.contains("init code size"), - "EIP-3860 must not reject initcode of exactly the size limit; got: {msg}" - ); - } - } + let outcome = validator.validate_one(TransactionOrigin::External, pooled); + assert!( + outcome.is_valid(), + "post-Viridian tx below EIP-7623 floor must be accepted: {outcome:?}" + ); - #[test] - fn validate_morph_tx_uses_max_fee_for_token_fee_admission() { - let validator = token_fee_validator(U256::ZERO, U256::from(300_000), 0, Default::default()); - let signer = address!("0000000000000000000000000000000000000001"); - // Effective execution price is 11, but admission must reserve the maximum 100. - let tx = TxMorph { - chain_id: 2818, + // Also ensure pre-Viridian legacy initcode word cost (EIP-3860) is enforced. + let legacy = TxLegacy { + chain_id: Some(MORPH_MAINNET.chain().id()), nonce: 0, + gas_price: 1_000_000, gas_limit: 21_000, - max_fee_per_gas: 100, - max_priority_fee_per_gas: 1, - to: TxKind::Call(address!("0000000000000000000000000000000000000002")), + to: TxKind::Create, value: U256::ZERO, - access_list: Default::default(), - version: 0, - fee_token_id: 1, - fee_limit: U256::from(300_000u64), - reference: None, - memo: None, - authorization_list: Vec::new(), - input: Default::default(), + input: Bytes::from(vec![0x00; 64]), }; - let envelope = MorphTxEnvelope::Morph(Signed::new_unchecked( - tx, + let envelope = MorphTxEnvelope::Legacy(Signed::new_unchecked( + legacy, Signature::test_signature(), B256::ZERO, )); - let recovered = Recovered::new_unchecked(envelope, signer); + let recovered = Recovered::new_unchecked(envelope, SIGNER); let len = recovered.encode_2718_len(); - let outcome = validator.validate_one( - TransactionOrigin::Local, - crate::MorphPooledTransaction::new(recovered, len), + let pooled = MorphPooledTransaction::new(recovered, len); + assert!( + validator + .validate_one(TransactionOrigin::External, pooled) + .is_invalid() ); - assert!(matches!(outcome, - TransactionValidationOutcome::Invalid(_, InvalidPoolTransactionError::Overdraft { cost, balance }) - if cost == U256::from(2_100_000) && balance == U256::from(300_000) - )); } } diff --git a/deny.toml b/deny.toml index d411d181..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`. @@ -82,6 +88,8 @@ license-files = [{ path = "LICENSE", hash = 0x001c7e6c }] unknown-registry = "warn" unknown-git = "deny" allow-git = [ - "https://github.com/morph-l2/reth", - "https://github.com/sigp/discv5", + "https://github.com/paradigmxyz/reth", + "https://github.com/paradigmxyz/reth-core", + # evm2 has no crates.io release; reth v2.11.0 requires this exact URL through a `[patch]`. + "https://github.com/DaniPopes/evm2", ]